data
stringlengths 512
2.99k
|
---|
Set bit 2 in the event flag to note this task has reached the // synchronisation point. The other two tasks will set the other two // bits defined by ALL_SYNC_BITS. All three tasks have reached the // synchronisation point when all the ALL_SYNC_BITS are set. Wait // indefinitely for this to happen. xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY ); // xEventGroupSync() was called with an indefinite block time, so // this task will only reach here if the synchronisation was made by all // three tasks, so there is no need to test the return value. } }
- Parameters
xEventGroup -- |
The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate().
uxBitsToSet -- The bits to set in the event group before determining if, and possibly waiting for, all the bits specified by the uxBitsToWait parameter are set.
uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set uxBitsToWaitFor to 0x07. Etc.
xTicksToWait |
The maximum amount of time (specified in 'ticks') to wait for all of the bits specified by uxBitsToWaitFor to become set.
-
- Returns
The value of the event group at the time either the bits being waited for became set, or the block time expired. Test the return value to know which bits were set. If xEventGroupSync() returned because its timeout expired then not all the bits being waited for will be set. If xEventGroupSync() returned because all the bits it was waiting for were set then the returned value is the event group value before any bits were automatically cleared.
-
EventBits_t xEventGroupGetBitsFromISR(EventGroupHandle_t xEventGroup)
A version of xEventGroupGetBits() that can be called from an ISR.
- Parameters
xEventGroup -- The event group being queried.
- Returns
The event group bits at the time xEventGroupGetBitsFromISR() was called.
-
void vEventGroupDelete(EventGroupHandle_t xEventGroup)
Delete an event group that was previously created by a call to xEventGroupCreate(). Tasks that are blocked on the event group will be unblocked and obtain 0 as the event group's value.
- Parameters
xEventGroup -- The event group being deleted.
-
BaseType_t xEventGroupGetStaticBuffer(EventGroupHandle_t xEventGroup, StaticEventGroup_t **ppxEventGroupBuffer)
Retrieve a pointer to a statically created event groups's data structure buffer. It is the same buffer that is supplied at the time of creation.
- Parameters
xEventGroup -- The event group for which to retrieve the buffer.
ppxEventGroupBuffer -- Used to return a pointer to the event groups's data structure buffer.
-
- Returns
pdTRUE if the buffer was retrieved, pdFALSE otherwise.
Macros
-
xEventGroupClearBitsFromISR(xEventGroup, uxBitsToClear)
A version of xEventGroupClearBits() that can be called from an interrupt.
Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed while interrupts are disabled, so protects event groups that are accessed from tasks by suspending the scheduler rather than disabling interrupts. As a result event groups cannot be accessed directly from an interrupt service routine. Therefore xEventGroupClearBitsFromISR() sends a message to the timer task to have the clear operation performed in the context of the timer task.
|
The event group being updated. BIT_0 | BIT_4 ); // The bits being set. if( xResult == pdPASS ) { // The message was posted successfully. portYIELD_FROM_ISR(pdTRUE); } }
Note
If this function returns pdPASS then the timer task is ready to run and a portYIELD_FROM_ISR(pdTRUE) should be executed to perform the needed clear on the event group. This behavior is different from xEventGroupSetBitsFromISR because the parameter xHigherPriorityTaskWoken is not present.
- Parameters
xEventGroup -- The event group in which the bits are to be cleared.
uxBitsToClear -- A bitwise value that indicates the bit or bits to clear. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09.
-
- Returns
If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full.
-
xEventGroupSetBitsFromISR(xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken)
A version of xEventGroupSetBits() that can be called from an interrupt.
Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed in interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() sends a message to the timer task to have the set operation performed in the context of the timer task - where a scheduler lock is used in place of a critical section.
|
The event group in which the bits are to be set.
uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09.
pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE by xEventGroupSetBitsFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below.
-
- Returns
If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full.
-
xEventGroupGetBits(xEventGroup)
Returns the current value of the bits in an event group. This function cannot be used from an interrupt.
- Parameters
xEventGroup -- The event group being queried.
-
- Returns
The event group bits at the time xEventGroupGetBits() was called.
Type Definitions
-
typedef struct EventGroupDef_t *EventGroupHandle_t
-
typedef TickType_t EventBits_t
Stream Buffer API
Header File
components/freertos/FreeRTOS-Kernel/include/freertos/stream_buffer.h
This header file can be included with:
#include "freertos/stream_buffer.h"
Functions
-
BaseType_t xStreamBufferGetStaticBuffers(StreamBufferHandle_t xStreamBuffer, uint8_t **ppucStreamBufferStorageArea, StaticStreamBuffer_t **ppxStaticStreamBuffer)
Retrieve pointers to a statically created stream buffer's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation.
- Parameters
xStreamBuffer -- The stream buffer for which to retrieve the buffers.
ppucStreamBufferStorageArea -- Used to return a pointer to the stream buffer's storage area buffer.
ppxStaticStreamBuffer -- Used to return a pointer to the stream buffer's data structure buffer.
-
- Returns
pdTRUE if buffers were retrieved, pdFALSE otherwise.
-
size_t xStreamBufferSend(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, TickType_t xTicksToWait)
Sends bytes to a stream buffer. The bytes are copied into the stream buffer.
|
Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0.
Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR).
Example use:
void vAFunction( StreamBufferHandle_t xStreamBuffer ) { size_t xBytesSent; uint8_t ucArrayToSend [] = { 0, 1, 2, 3 }; char *pcStringToSend = "String to send"; const TickType_t x100ms = pdMS_TO_TICKS( 100 ); // Send an array to the stream buffer, blocking for a maximum of 100ms to // wait for enough space to be available in the stream buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); if( xBytesSent != sizeof( ucArrayToSend ) ) |
{ // The call to xStreamBufferSend() times out before there was enough // space in the buffer for the data to be written, but it did // successfully write xBytesSent bytes. } // Send the string to the stream buffer. Return immediately if there is not // enough space in the buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ) ; if( xBytesSent != strlen( pcStringToSend ) ) { // The entire string could not be added to the stream buffer because // there was not enough free space in the buffer, but xBytesSent bytes // were sent. Could try again to send the remaining bytes. } |
The maximum amount of time the task should remain in the Blocked state to wait for enough space to become available in the stream buffer, should the stream buffer contain too little space to hold the another xDataLengthBytes bytes. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. A task does not use any CPU time when it is in the blocked state.
-
- Returns
The number of bytes written to the stream buffer. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible.
-
size_t xStreamBufferSendFromISR(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, BaseType_t *const pxHigherPriorityTaskWoken)
Interrupt safe version of the API function that sends a stream of bytes to the stream buffer.
NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0.
Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR).
Example use:
// |
xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), &xHigherPriorityTaskWoken ) ; if( xBytesSent != strlen( pcStringToSend ) ) { // There was not enough free space in the stream buffer for the entire // string to be written, ut xBytesSent bytes were written. } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferSendFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. |
It is possible that a stream buffer will have a task blocked on it waiting for data. Calling xStreamBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the example code below for an example.
-
- Returns
The number of bytes actually written to the stream buffer, which will be less than xDataLengthBytes if the stream buffer didn't have enough free space for all the bytes to be written.
-
size_t xStreamBufferReceive(StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, TickType_t xTicksToWait)
Receives bytes from a stream buffer.
|
Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0.
Use xStreamBufferReceive() to read from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read from a stream buffer from an interrupt service routine (ISR).
Example use:
void |
vAFunction( StreamBuffer_t xStreamBuffer ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. // Wait in the Blocked state (so not using any CPU processing time) for a // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be // available. xReceivedBytes = xStreamBufferReceive( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xBlockTime ); if( xReceivedBytes > 0 ) |
{ // A ucRxData contains another xReceivedBytes bytes of data, which can // be processed here.... } }
- Parameters
xStreamBuffer -- The handle of the stream buffer from which bytes are to be received.
pvRxData -- A pointer to the buffer into which the received bytes will be copied.
xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes.
|
The maximum amount of time the task should remain in the Blocked state to wait for data to become available if the stream buffer is empty. xStreamBufferReceive() will return immediately if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. A task does not use any CPU time when it is in the Blocked state.
-
- Returns
The number of bytes actually read from the stream buffer, which will be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed out before xBufferLengthBytes were available.
-
size_t xStreamBufferReceiveFromISR(StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, BaseType_t *const pxHigherPriorityTaskWoken)
An interrupt safe version of the API function that receives bytes from a stream buffer.
Use xStreamBufferReceive() to read bytes from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an interrupt service routine (ISR).
Example use:
// |
xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), &xHigherPriorityTaskWoken ); if( xReceivedBytes > 0 ) { // ucRxData contains xReceivedBytes read from the stream buffer. // Process the stream here.... } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferReceiveFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. |
It is possible that a stream buffer will have a task blocked on it waiting for space to become available. Calling xStreamBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example.
-
- Returns
The number of bytes read from the stream buffer, if any.
-
void vStreamBufferDelete(StreamBufferHandle_t xStreamBuffer)
Deletes a stream buffer that was previously created using a call to xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream buffer was created using dynamic memory (that is, by xStreamBufferCreate()), then the allocated memory is freed.
A stream buffer handle must not be used after the stream buffer has been deleted.
- Parameters
xStreamBuffer -- The handle of the stream buffer to be deleted.
-
BaseType_t xStreamBufferIsFull(StreamBufferHandle_t xStreamBuffer)
Queries a stream buffer to see if it is full. A stream buffer is full if it does not have any free space, and therefore cannot accept any more data.
- Parameters
xStreamBuffer -- The handle of the stream buffer being queried.
- Returns
If the stream buffer is full then pdTRUE is returned. Otherwise pdFALSE is returned.
-
BaseType_t xStreamBufferIsEmpty(StreamBufferHandle_t xStreamBuffer)
Queries a stream buffer to see if it is empty. A stream buffer is empty if it does not contain any data.
- Parameters
xStreamBuffer -- The handle of the stream buffer being queried.
- Returns
If the stream buffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned.
-
BaseType_t xStreamBufferReset(StreamBufferHandle_t xStreamBuffer)
Resets a stream buffer to its initial, empty, state. Any data that was in the stream buffer is discarded. A stream buffer can only be reset if there are no tasks blocked waiting to either send to or receive from the stream buffer.
|
- Parameters
xStreamBuffer -- The handle of the stream buffer being reset.
- Returns
If the stream buffer is reset then pdPASS is returned. If there was a task blocked waiting to send to or read from the stream buffer then the stream buffer is not reset and pdFAIL is returned.
-
size_t xStreamBufferSpacesAvailable(StreamBufferHandle_t xStreamBuffer)
Queries a stream buffer to see how much free space it contains, which is equal to the amount of data that can be sent to the stream buffer before it is full.
- Parameters
xStreamBuffer -- The handle of the stream buffer being queried.
- Returns
The number of bytes that can be written to the stream buffer before the stream buffer would be full.
-
size_t xStreamBufferBytesAvailable(StreamBufferHandle_t xStreamBuffer)
Queries a stream buffer to see how much data it contains, which is equal to the number of bytes that can be read from the stream buffer before the stream buffer would be empty.
- Parameters
xStreamBuffer -- The handle of the stream buffer being queried.
- Returns
The number of bytes that can be read from the stream buffer before the stream buffer would be empty.
-
BaseType_t xStreamBufferSetTriggerLevel(StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel)
A stream buffer's trigger level is the number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size.
A trigger level is set when the stream buffer is created, and can be modified using xStreamBufferSetTriggerLevel().
- Parameters
xStreamBuffer -- The handle of the stream buffer being updated.
|
The new trigger level for the stream buffer.
-
- Returns
If xTriggerLevel was less than or equal to the stream buffer's length then the trigger level will be updated and pdTRUE is returned. Otherwise pdFALSE is returned.
-
BaseType_t xStreamBufferSendCompletedFromISR(StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken)
For advanced users only.
The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferSendCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME.
See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
- Parameters
xStreamBuffer -- The handle of the stream buffer to which data was written.
|
*pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferSendCompletedFromISR(). If calling xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR.
-
- Returns
If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned.
-
BaseType_t xStreamBufferReceiveCompletedFromISR(StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken)
For advanced users only.
The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME.
See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
- Parameters
xStreamBuffer -- The handle of the stream buffer from which data was read.
|
*pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferReceiveCompletedFromISR(). If calling xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR.
-
- Returns
If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned.
Macros
-
xStreamBufferCreateWithCallback(xBufferSizeBytes, xTriggerLevelBytes, pxSendCompletedCallback, pxReceiveCompletedCallback)
Creates a new stream buffer using dynamically allocated memory. See xStreamBufferCreateStatic() for a version that uses statically allocated memory (memory that is allocated at compile time).
configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for xStreamBufferCreate() to be available.
Example use:
void vAFunction( void ) { StreamBufferHandle_t xStreamBuffer; const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; // Create a stream buffer that can hold 100 bytes. The memory used to hold // both the stream buffer structure and the data in the stream buffer is // allocated dynamically. |
The total number of bytes the stream buffer will be able to hold at any one time.
xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size.
pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
-
- Returns
If NULL is returned, then the stream buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the stream buffer data structures and storage area. A non-NULL value being returned indicates that the stream buffer has been created successfully - the returned value should be stored as the handle to the created stream buffer.
-
xStreamBufferCreateStaticWithCallback(xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback)
Creates a new stream buffer using statically allocated memory. See xStreamBufferCreate() for a version that uses dynamically allocated memory.
configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for xStreamBufferCreateStatic() to be available.
Example use:
// Used to dimension the array used to hold the streams. The available space // will actually be one less than this, so 999. |
As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer // parameters were NULL, xStreamBuffer will not be NULL, and can be used to // reference the created stream buffer in other stream buffer API calls. // Other code that uses the stream buffer can go here. }
- Parameters
xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucStreamBufferStorageArea parameter.
xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size.
pucStreamBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which streams are copied when they are written to the stream buffer.
pxStaticStreamBuffer -- Must point to a variable of type StaticStreamBuffer_t, which will be used to hold the stream buffer's data structure.
pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
-
- Returns
If the stream buffer is created successfully then a handle to the created stream buffer is returned. If either pucStreamBufferStorageArea or pxStaticstreamBuffer are NULL then NULL is returned.
|
Type Definitions
-
typedef struct StreamBufferDef_t *StreamBufferHandle_t
-
typedef void (*StreamBufferCallbackFunction_t)(StreamBufferHandle_t xStreamBuffer, BaseType_t xIsInsideISR, BaseType_t *const pxHigherPriorityTaskWoken)
Type used as a stream buffer's optional callback.
Message Buffer API
Header File
components/freertos/FreeRTOS-Kernel/include/freertos/message_buffer.h
This header file can be included with:
#include "freertos/message_buffer.h"
Macros
-
xMessageBufferCreateWithCallback(xBufferSizeBytes, pxSendCompletedCallback, pxReceiveCompletedCallback)
Creates a new message buffer using dynamically allocated memory. See xMessageBufferCreateStatic() for a version that uses statically allocated memory (memory that is allocated at compile time).
configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for xMessageBufferCreate() to be available.
Example use:
void vAFunction( void ) { MessageBufferHandle_t xMessageBuffer; const size_t xMessageBufferSizeBytes = 100; // Create a message buffer that can hold 100 bytes. The memory used to hold // both the message buffer structure and the messages themselves is allocated // dynamically. Each message added to the buffer consumes an additional 4 // bytes which are used to hold the length of the message. xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes ); if( xMessageBuffer == NULL ) { // There was not enough heap memory space available to create the // message buffer. } else { // The message buffer was created successfully and can now be used. }
- Parameters
xBufferSizeBytes -- |
The total number of bytes (not messages) the message buffer will be able to hold at any one time. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architectures a 10 byte message will take up 14 bytes of message buffer space.
pxSendCompletedCallback -- Callback invoked when a send operation to the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
pxReceiveCompletedCallback -- Callback invoked when a receive operation from the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
-
- Returns
If NULL is returned, then the message buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the message buffer data structures and storage area. A non-NULL value being returned indicates that the message buffer has been created successfully - the returned value should be stored as the handle to the created message buffer.
-
xMessageBufferCreateStaticWithCallback(xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback)
Creates a new message buffer using statically allocated memory. See xMessageBufferCreate() for a version that uses dynamically allocated memory.
Example use:
// Used to dimension the array used to hold the messages. The available space // will actually be one less than this, so 999. |
As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer // parameters were NULL, xMessageBuffer will not be NULL, and can be used to // reference the created message buffer in other message buffer API calls. // Other code that uses the message buffer can go here. }
- Parameters
xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucMessageBufferStorageArea parameter. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture a 10 byte message will take up 14 bytes of message buffer space. The maximum number of bytes that can be stored in the message buffer is actually (xBufferSizeBytes - 1).
pucMessageBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which messages are copied when they are written to the message buffer.
pxStaticMessageBuffer -- Must point to a variable of type StaticMessageBuffer_t, which will be used to hold the message buffer's data structure.
pxSendCompletedCallback -- Callback invoked when a new message is sent to the message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
pxReceiveCompletedCallback -- Callback invoked when a message is read from a message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h.
-
- Returns
If the message buffer is created successfully then a handle to the created message buffer is returned. If either pucMessageBufferStorageArea or pxStaticmessageBuffer are NULL then NULL is returned.
-
xMessageBufferGetStaticBuffers(xMessageBuffer, ppucMessageBufferStorageArea, ppxStaticMessageBuffer)
Retrieve pointers to a statically created message buffer's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation.
- Parameters
xMessageBuffer -- The message buffer for which to retrieve the buffers.
ppucMessageBufferStorageArea -- Used to return a pointer to the message buffer's storage area buffer.
ppxStaticMessageBuffer -- Used to return a pointer to the message buffer's data structure buffer.
-
- Returns
pdTRUE if buffers were retrieved, pdFALSE otherwise.
-
xMessageBufferSend(xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait)
Sends a discrete message to the message buffer. The message can be any length that fits within the buffer's free space, and is copied into the buffer.
|
Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0.
Use xMessageBufferSend() to write to a message buffer from a task. Use xMessageBufferSendFromISR() to write to a message buffer from an interrupt service routine (ISR).
Example use:
void vAFunction( MessageBufferHandle_t xMessageBuffer ) { size_t xBytesSent; uint8_t ucArrayToSend [] = { 0, 1, 2, 3 }; char *pcStringToSend = "String to send"; const TickType_t x100ms = pdMS_TO_TICKS( 100 ); // Send an array to the message buffer, blocking for a maximum of 100ms to // wait for enough space to be available in the message buffer. xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); if( xBytesSent != sizeof( ucArrayToSend ) ) |
{ // The call to xMessageBufferSend() times out before there was enough // space in the buffer for the data to be written. } // Send the string to the message buffer. Return immediately if there is // not enough space in the buffer. xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); if( xBytesSent != strlen( pcStringToSend ) ) { // The string could not be added to the message buffer because there was // not enough free space in the buffer. } }
- Parameters
xMessageBuffer -- |
The maximum amount of time the calling task should remain in the Blocked state to wait for enough space to become available in the message buffer, should the message buffer have insufficient space when xMessageBufferSend() is called. The calling task will never block if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state.
-
- Returns
The number of bytes written to the message buffer. If the call to xMessageBufferSend() times out before there was enough space to write the message into the message buffer then zero is returned. If the call did not time out then xDataLengthBytes is returned.
-
xMessageBufferSendFromISR(xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken)
Interrupt safe version of the API function that sends a discrete message to the message buffer. The message can be any length that fits within the buffer's free space, and is copied into the buffer.
|
Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0.
Use xMessageBufferSend() to write to a message buffer from a task. Use xMessageBufferSendFromISR() to write to a message buffer from an interrupt service routine (ISR).
Example use:
// |
MessageBufferHandle_t xMessageBuffer; void vAnInterruptServiceRoutine( void ) { size_t xBytesSent; char *pcStringToSend = "String to send"; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Attempt to send the string to the message buffer. xBytesSent = xMessageBufferSendFromISR( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), &xHigherPriorityTaskWoken ) ; if( xBytesSent != strlen( pcStringToSend ) ) { // The string could not be added to the message buffer because there was // not enough free space in the buffer. } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xMessageBufferSendFromISR () then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. |
It is possible that a message buffer will have a task blocked on it waiting for data. Calling xMessageBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example.
-
- Returns
The number of bytes actually written to the message buffer. If the message buffer didn't have enough free space for the message to be stored then 0 is returned, otherwise xDataLengthBytes is returned.
-
xMessageBufferReceive(xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait)
Receives a discrete message from a message buffer. Messages can be of variable length and are copied out of the buffer.
|
Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0.
Use xMessageBufferReceive() to read from a message buffer from a task. Use xMessageBufferReceiveFromISR() to read from a message buffer from an interrupt service routine (ISR).
Example use:
void vAFunction( MessageBuffer_t xMessageBuffer ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); // Receive the next message from the message buffer. Wait in the Blocked // state (so not using any CPU processing time) for a maximum of 100ms for // a message to become available. xReceivedBytes = xMessageBufferReceive( xMessageBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xBlockTime ); if( xReceivedBytes > 0 ) { // A ucRxData contains a message that is xReceivedBytes long. Process // the message here.... } }
- Parameters
xMessageBuffer -- The handle of the message buffer from which a message is being received.
pvRxData -- A pointer to the buffer into which the received message is to be copied.
xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned.
|
The maximum amount of time the task should remain in the Blocked state to wait for a message, should the message buffer be empty. xMessageBufferReceive() will return immediately if xTicksToWait is zero and the message buffer is empty. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state.
-
- Returns
The length, in bytes, of the message read from the message buffer, if any. If xMessageBufferReceive() times out before a message became available then zero is returned. If the length of the message is greater than xBufferLengthBytes then the message will be left in the message buffer and zero is returned.
-
xMessageBufferReceiveFromISR(xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken)
An interrupt safe version of the API function that receives a discrete message from a message buffer. Messages can be of variable length and are copied out of the buffer.
|
Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0.
Use xMessageBufferReceive() to read from a message buffer from a task. Use xMessageBufferReceiveFromISR() to read from a message buffer from an interrupt service routine (ISR).
Example use:
// |
Receive the next message from the message buffer. xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer, ( void * ) ucRxData, sizeof( ucRxData ), &xHigherPriorityTaskWoken ); if( xReceivedBytes > 0 ) { // A ucRxData contains a message that is xReceivedBytes long. Process // the message here.... } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xMessageBufferReceiveFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. |
It is possible that a message buffer will have a task blocked on it waiting for space to become available. Calling xMessageBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example.
-
- Returns
The length, in bytes, of the message read from the message buffer, if any.
-
vMessageBufferDelete(xMessageBuffer)
Deletes a message buffer that was previously created using a call to xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message buffer was created using dynamic memory (that is, by xMessageBufferCreate()), then the allocated memory is freed.
A message buffer handle must not be used after the message buffer has been deleted.
- Parameters
xMessageBuffer -- The handle of the message buffer to be deleted.
-
-
xMessageBufferIsFull(xMessageBuffer)
Tests to see if a message buffer is full. A message buffer is full if it cannot accept any more messages, of any size, until space is made available by a message being removed from the message buffer.
- Parameters
xMessageBuffer -- The handle of the message buffer being queried.
-
- Returns
If the message buffer referenced by xMessageBuffer is full then pdTRUE is returned. Otherwise pdFALSE is returned.
-
xMessageBufferIsEmpty(xMessageBuffer)
Tests to see if a message buffer is empty (does not contain any messages).
- Parameters
xMessageBuffer -- The handle of the message buffer being queried.
-
- Returns
If the message buffer referenced by xMessageBuffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned.
-
xMessageBufferReset(xMessageBuffer)
Resets a message buffer to its initial empty state, discarding any message it contained.
A message buffer can only be reset if there are no tasks blocked on it.
- Parameters
xMessageBuffer -- The handle of the message buffer being reset.
-
- Returns
If the message buffer was reset then pdPASS is returned. If the message buffer could not be reset because either there was a task blocked on the message queue to wait for space to become available, or to wait for a a message to be available, then pdFAIL is returned.
-
xMessageBufferSpaceAvailable(xMessageBuffer)
message_buffer.hReturns the number of bytes of free space in the message buffer.
|
The handle of the message buffer being queried.
-
- Returns
The number of bytes that can be written to the message buffer before the message buffer would be full. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size of the largest message that can be written to the message buffer is 6 bytes.
-
xMessageBufferSpacesAvailable(xMessageBuffer)
-
xMessageBufferNextLengthBytes(xMessageBuffer)
Returns the length (in bytes) of the next message in a message buffer. Useful if xMessageBufferReceive() returned 0 because the size of the buffer passed into xMessageBufferReceive() was too small to hold the next message.
- Parameters
xMessageBuffer -- The handle of the message buffer being queried.
-
- Returns
The length (in bytes) of the next message in the message buffer, or 0 if the message buffer is empty.
-
xMessageBufferSendCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken)
For advanced users only.
The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xMessageBufferSendCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME.
See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
- Parameters
xMessageBuffer -- |
*pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferSendCompletedFromISR(). If calling xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR.
-
- Returns
If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned.
-
xMessageBufferReceiveCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken)
For advanced users only.
The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME.
See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
- Parameters
xMessageBuffer -- |
*pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferReceiveCompletedFromISR(). If calling xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR.
-
- Returns
If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned.
Type Definitions
-
typedef StreamBufferHandle_t MessageBufferHandle_t
Type by which message buffers are referenced. For example, a call to xMessageBufferCreate() returns an MessageBufferHandle_t variable that can then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), etc. Message buffer is essentially built as a stream buffer hence its handle is also set to same type as a stream buffer handle. |
FreeRTOS (Supplemental Features)
ESP-IDF provides multiple features to supplement the features offered by FreeRTOS. These supplemental features are available on all FreeRTOS implementations supported by ESP-IDF (i.e., ESP-IDF FreeRTOS and Amazon SMP FreeRTOS). This document describes these supplemental features and is split into the following sections:
Contents
Overview
ESP-IDF adds various new features to supplement the capabilities of FreeRTOS as follows:
Ring buffers: Ring buffers provide a FIFO buffer that can accept entries of arbitrary lengths.
ESP-IDF Tick and Idle Hooks: ESP-IDF provides multiple custom tick interrupt hooks and idle task hooks that are more numerous and more flexible when compared to FreeRTOS tick and idle hooks.
|
Additional API: ESP-IDF specific functions added to augment the features of FreeRTOS.
Component Specific Properties: Currently added only one component specific property
ORIG_INCLUDE_PATH.
Ring Buffers
FreeRTOS provides stream buffers and message buffers as the primary mechanisms to send arbitrarily sized data between tasks and ISRs. However, FreeRTOS stream buffers and message buffers have the following limitations:
Strictly single sender and single receiver
Data is passed by copy
Unable to reserve buffer space for a deferred send (i.e., send acquire)
Therefore, ESP-IDF provides a separate ring buffer implementation to address the issues above.
ESP-IDF ring buffers are strictly FIFO buffers that supports arbitrarily sized items. Ring buffers are a more memory efficient alternative to FreeRTOS queues in situations where the size of items is variable. The capacity of a ring buffer is not measured by the number of items it can store, but rather by the amount of memory used for storing items.
The ring buffer provides APIs to send an item, or to allocate space for an item in the ring buffer to be filled manually by the user. For efficiency reasons, items are always retrieved from the ring buffer by reference. As a result, all retrieved items must also be returned to the ring buffer by using
vRingbufferReturnItem() or
vRingbufferReturnItemFromISR(), in order for them to be removed from the ring buffer completely.
The ring buffers are split into the three following types:
No-Split buffers guarantee that an item is stored in contiguous memory and does not attempt to split an item under any circumstances. Use No-Split buffers when items must occupy contiguous memory. Only this buffer type allows reserving buffer space for deferred sending. |
Allow-Split buffers allow an item to be split in two parts when wrapping around the end of the buffer if there is enough space at the tail and the head of the buffer combined to store the item. Allow-Split buffers are more memory efficient than No-Split buffers but can return an item in two parts when retrieving.
Byte buffers do not store data as separate items. All data is stored as a sequence of bytes, and any number of bytes can be sent or retrieved each time. Use byte buffers when separate items do not need to be maintained, e.g., a byte stream.
|
Note
Each item stored in No-Split or Allow-Split buffers requires an additional 8 bytes for a header. Item sizes are also rounded up to a 32-bit aligned size, i.e., multiple of 4 bytes. However the true item size is recorded within the header. The sizes of No-Split and Allow-Split buffers will also be rounded up when created.
Usage
The following example demonstrates the usage of
xRingbufferCreate() and
xRingbufferSend() to create a ring buffer and then send an item to it:
#include "freertos/ringbuf.h"
static char tx_item |
ring buffer
RingbufHandle_t buf_handle;
buf_handle = xRingbufferCreate(1028, RINGBUF_TYPE_NOSPLIT);
if (buf_handle == NULL) {
printf("Failed to create ring buffer\n");
}
//Send an item
UBaseType_t res = xRingbufferSend(buf_handle, tx_item, sizeof(tx_item), pdMS_TO_TICKS(1000));
if (res != pdTRUE) {
printf("Failed to send item\n");
}
The following example demonstrates the usage of
xRingbufferSendAcquire() and
xRingbufferSendComplete() instead of
xRingbufferSend() to acquire memory on the ring buffer (of type
RINGBUF_TYPE_NOSPLIT) and then send an item to it. |
//Retrieve space for DMA descriptor and corresponding data buffer
//This has to be done with SendAcquire, or the address may be different when we copy
dma_item_t item;
UBaseType_t res = xRingbufferSendAcquire(buf_handle,
&item, DMA_ITEM_SIZE(buffer_size), pdMS_TO_TICKS(1000));
if (res != pdTRUE) {
printf("Failed to acquire memory for item\n");
}
item->dma_desc = (lldesc_t) {
.size = buffer_size,
.length = buffer_size,
.eof = 0,
.owner = 1,
.buf = &item->buf,
};
//Actually send to the ring buffer for consumer to use
res = xRingbufferSendComplete(buf_handle, &item);
if (res != pdTRUE) {
printf("Failed to send item\n");
}
The following example demonstrates retrieving and returning an item from a No-Split ring buffer using
xRingbufferReceive() and
vRingbufferReturnItem()
...
//Receive an item from no-split ring buffer
size_t item_size;
char *item = (char *)xRingbufferReceive(buf_handle, &item_size, pdMS_TO_TICKS(1000));
//Check received item
if (item != NULL) {
//Print item
for (int i = 0; i < item_size; i++) {
printf("%c", item[i]);
}
printf("\n");
//Return Item
vRingbufferReturnItem(buf_handle, (void *)item);
} else {
//Failed to receive item
printf("Failed to receive item\n");
}
The following example demonstrates retrieving and returning an item from an Allow-Split ring buffer using
xRingbufferReceiveSplit() and
vRingbufferReturnItem()
...
//Receive an item from allow-split ring buffer
size_t item_size1, item_size2;
char *item1, *item2;
BaseType_t ret = xRingbufferReceiveSplit(buf_handle, (void **)&item1, (void **)&item2, &item_size1, &item_size2, pdMS_TO_TICKS(1000));
//Check received item
if (ret == pdTRUE && item1 != NULL) {
for (int i = 0; i < item_size1; i++) {
printf("%c", item1[i]);
}
vRingbufferReturnItem(buf_handle, (void *)item1);
//Check if item was split
if (item2 != NULL) {
for (int i = 0; i < item_size2; i++) {
printf("%c", item2[i]);
}
vRingbufferReturnItem(buf_handle, (void *)item2);
}
printf("\n");
} else {
//Failed to receive item
printf("Failed to receive item\n");
}
The following example demonstrates retrieving and returning an item from a byte buffer using
xRingbufferReceiveUpTo() and
vRingbufferReturnItem()
...
//Receive data from byte buffer
size_t item_size;
char *item = (char *)xRingbufferReceiveUpTo(buf_handle, &item_size, pdMS_TO_TICKS(1000), sizeof(tx_item));
//Check received data
if (item != NULL) {
//Print item
for (int i = 0; i < item_size; i++) {
printf("%c", item[i]);
}
printf("\n");
//Return Item
vRingbufferReturnItem(buf_handle, (void *)item);
} else {
//Failed to receive item
printf("Failed to receive item\n");
}
For ISR safe versions of the functions used above, call
xRingbufferSendFromISR(),
xRingbufferReceiveFromISR(),
xRingbufferReceiveSplitFromISR(),
xRingbufferReceiveUpToFromISR(), and
vRingbufferReturnItemFromISR().
|
Since every retrieval must be followed by a return, the space is freed as soon as the data is returned.
Referring to the diagram above, the 38 bytes of continuous stored data at the tail of the buffer is retrieved, returned, and freed. The next call to
xRingbufferReceive() or
xRingbufferReceiveFromISR() then wraps around and does the same to the 30 bytes of continuous stored data at the head of the buffer.
Ring Buffers with Queue Sets
Ring buffers can be added to FreeRTOS queue sets using
xRingbufferAddToQueueSetRead() such that every time a ring buffer receives an item or data, the queue set is notified. Once added to a queue set, every attempt to retrieve an item from a ring buffer should be preceded by a call to
xQueueSelectFromSet(). To check whether the selected queue set member is the ring buffer, call
xRingbufferCanRead().
The following example demonstrates queue set usage with ring buffers:
#include "freertos/queue.h"
#include "freertos/ringbuf.h"
...
//Create ring buffer and queue set
RingbufHandle_t buf_handle = xRingbufferCreate(1028, RINGBUF_TYPE_NOSPLIT);
QueueSetHandle_t queue_set = xQueueCreateSet(3);
//Add ring buffer to queue set
if (xRingbufferAddToQueueSetRead(buf_handle, queue_set) != pdTRUE) {
printf("Failed to add to queue set\n");
}
...
//Block on queue set
QueueSetMemberHandle_t member = xQueueSelectFromSet(queue_set, pdMS_TO_TICKS(1000));
//Check |
if member is ring buffer
if (member != NULL && xRingbufferCanRead(buf_handle, member) == pdTRUE) {
//Member is ring buffer, receive item from ring buffer
size_t item_size;
char *item = (char *)xRingbufferReceive(buf_handle, &item_size, 0);
//Handle item
...
} else {
...
}
Ring Buffers with Static Allocation
The
xRingbufferCreateStatic() can be used to create ring buffers with specific memory requirements (such as a ring buffer being allocated in external RAM). All blocks of memory used by a ring buffer must be manually allocated beforehand, then passed to the
xRingbufferCreateStatic() to be initialized as a ring buffer. These blocks include the following:
The ring buffer's data structure of type
StaticRingbuffer_t.
The ring buffer's storage area of size
xBufferSize. |
Note that
xBufferSizemust be 32-bit aligned for No-Split and Allow-Split buffers.
The manner in which these blocks are allocated depends on the users requirements (e.g., all blocks being statically declared, or dynamically allocated with specific capabilities such as external RAM).
Note
When deleting a ring buffer created via
xRingbufferCreateStatic(), the function
vRingbufferDelete() will not free any of the memory blocks. This must be done manually by the user after
vRingbufferDelete() is called.
The code snippet below demonstrates a ring buffer being allocated entirely in external RAM.
|
a ring buffer with manually allocated memory
RingbufHandle_t handle = xRingbufferCreateStatic(BUFFER_SIZE, BUFFER_TYPE, buffer_storage, buffer_struct);
...
//Delete the ring buffer after used
vRingbufferDelete(handle);
//Manually free all blocks of memory
free(buffer_struct);
free(buffer_storage);
ESP-IDF Tick and Idle Hooks
FreeRTOS allows applications to provide a tick hook and an idle hook at compile time:
FreeRTOS tick hook can be enabled via the CONFIG_FREERTOS_USE_TICK_HOOK option. The application must provide the
void vApplicationTickHook( void )callback.
|
The application must provide the
void vApplicationIdleHook( void )callback.
However, the FreeRTOS tick hook and idle hook have the following draw backs:
The FreeRTOS hooks are registered at compile time
Only one of each hook can be registered
On multi-core targets, the FreeRTOS hooks are symmetric, meaning each core's tick interrupt and idle tasks ends up calling the same hook
Therefore, ESP-IDF tick and idle hooks are provided to supplement the features of FreeRTOS tick and idle hooks. The ESP-IDF hooks have the following features:
The hooks can be registered and deregistered at run-time
Multiple hooks can be registered (with a maximum of 8 hooks of each type per core)
On multi-core targets, the hooks can be asymmetric, meaning different hooks can be registered to each core
ESP-IDF hooks can be registered and deregistered using the following APIs:
For tick hooks:
Register using
esp_register_freertos_tick_hook()or
esp_register_freertos_tick_hook_for_cpu()
Deregister using
esp_deregister_freertos_tick_hook()or
esp_deregister_freertos_tick_hook_for_cpu()
-
For idle hooks:
Register using
esp_register_freertos_idle_hook()or
esp_register_freertos_idle_hook_for_cpu()
Deregister using
esp_deregister_freertos_idle_hook()or
esp_deregister_freertos_idle_hook_for_cpu()
-
Note
The tick interrupt stays active while the cache is disabled, therefore any tick hook (FreeRTOS or ESP-IDF) functions must be placed in internal RAM. |
TLSP Deletion Callbacks
Vanilla FreeRTOS provides a Thread Local Storage Pointers (TLSP) feature. These are pointers stored directly in the Task Control Block (TCB) of a particular task. TLSPs allow each task to have its own unique set of pointers to data structures. Vanilla FreeRTOS expects users to:
set a task's TLSPs by calling
vTaskSetThreadLocalStoragePointer()after the task has been created.
get a task's TLSPs by calling
pvTaskGetThreadLocalStoragePointer()during the task's lifetime.
free the memory pointed to by the TLSPs before the task is deleted.
However, there can be instances where users may want the freeing of TLSP memory to be automatic. Therefore, ESP-IDF provides the additional feature of TLSP deletion callbacks. These user-provided deletion callbacks are called automatically when a task is deleted, thus allowing the TLSP memory to be cleaned up without needing to add the cleanup logic explicitly to the code of every task.
The TLSP deletion callbacks are set in a similar fashion to the TLSPs themselves.
vTaskSetThreadLocalStoragePointerAndDelCallback()sets both a particular TLSP and its associated callback.
Calling the Vanilla FreeRTOS function
vTaskSetThreadLocalStoragePointer()simply sets the TLSP's associated Deletion Callback to NULL, meaning that no callback is called for that TLSP during task deletion.
When implementing TLSP callbacks, users should note the following:
The callback must never attempt to block or yield and critical sections should be kept as short as possible.
The callback is called shortly before a deleted task's memory is freed. Thus, the callback can either be called from
vTaskDelete()itself, or from the idle task.
|
IDF Additional API
The freertos/esp_additions/include/freertos/idf_additions.h header contains FreeRTOS-related helper functions added by ESP-IDF. Users can include this header via
#include "freertos/idf_additions.h".
Component Specific Properties
Besides standard component variables that are available with basic cmake build properties, FreeRTOS component also provides arguments (only one so far) for simpler integration with other modules:
ORIG_INCLUDE_PATH - contains an absolute path to freertos root include folder. Thus instead of #include "freertos/FreeRTOS.h" you can refer to headers directly: #include "FreeRTOS.h".
API Reference
Ring Buffer API
Header File
This header file can be included with:
#include "freertos/ringbuf.h"
This header file is a part of the API provided by the
esp_ringbufcomponent. To declare that your component depends on
esp_ringbuf, add the following to your CMakeLists.txt:
REQUIRES esp_ringbuf
or
PRIV_REQUIRES |
Note that items require space for a header in no-split/allow-split buffers
xBufferType -- [in] Type of ring buffer, see documentation.
-
- Returns
A handle to the created ring buffer, or NULL in case of error.
-
RingbufHandle_t xRingbufferCreateNoSplit(size_t xItemSize, size_t xItemNum)
Create a ring buffer of type RINGBUF_TYPE_NOSPLIT for a fixed item_size.
This API is similar to xRingbufferCreate(), but it will internally allocate additional space for the headers.
- Parameters
xItemSize -- [in] Size of each item to be put into the ring buffer
xItemNum -- [in] Maximum number of items the buffer needs to hold simultaneously
-
- Returns
A RingbufHandle_t handle to the created ring buffer, or NULL in case of error.
-
RingbufHandle_t xRingbufferCreateStatic(size_t xBufferSize, RingbufferType_t xBufferType, uint8_t |
[in] Type of ring buffer, see documentation
pucRingbufferStorage -- [in] Pointer to the ring buffer's storage area. Storage area must have the same size as specified by xBufferSize
pxStaticRingbuffer -- [in] Pointed to a struct of type StaticRingbuffer_t which will be used to hold the ring buffer's data structure
-
- Returns
A handle to the created ring buffer
-
BaseType_t xRingbufferSend(RingbufHandle_t xRingbuffer, const void *pvItem, size_t xItemSize, TickType_t xTicksToWait)
Insert an item into the ring buffer.
Attempt to insert an item into the ring buffer. This function will block until enough free space is available or until it times out.
|
[in] Ticks to wait for room in the ring buffer.
-
- Returns
pdTRUE if succeeded
pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer
-
-
BaseType_t xRingbufferSendFromISR(RingbufHandle_t xRingbuffer, const void *pvItem, size_t xItemSize, BaseType_t *pxHigherPriorityTaskWoken)
Insert an item into the ring buffer in an ISR.
Attempt to insert an item into the ring buffer from an ISR. This function will return immediately if there is insufficient free space in the buffer.
|
[out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task.
-
- Returns
pdTRUE if succeeded
pdFALSE when the ring buffer does not have space.
-
-
BaseType_t xRingbufferSendAcquire(RingbufHandle_t xRingbuffer, void **ppvItem, size_t xItemSize, TickType_t xTicksToWait)
Acquire memory from the ring buffer to be written to by an external source and to be sent later.
Attempt to allocate buffer for an item to be sent into the ring buffer. This function will block until enough free space is available or until it times out.
The item, as well as the following items
SendAcquireor
Sendafter it, will not be able to be read from the ring buffer until this item is actually sent into the ring buffer.
Note
Only applicable for no-split ring buffers now, the actual size of memory that the item will occupy will be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion.
Note
An xItemSize of 0 will result in a buffer being acquired, but the buffer will have a size of 0.
- Parameters
xRingbuffer -- [in] Ring buffer to allocate the memory
ppvItem -- [out] Double pointer to memory acquired (set to NULL if no memory were retrieved)
xItemSize -- [in] Size of item to acquire.
xTicksToWait |
[in] Ticks to wait for room in the ring buffer.
-
- Returns
pdTRUE if succeeded
pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer
-
-
BaseType_t xRingbufferSendComplete(RingbufHandle_t xRingbuffer, void *pvItem)
Actually send an item into the ring buffer allocated before by
xRingbufferSendAcquire.
Note
Only applicable for no-split ring buffers. Only call for items allocated by
xRingbufferSendAcquire.
- Parameters
xRingbuffer -- [in] Ring buffer to insert the item into
pvItem -- [in] Pointer to item in allocated memory to insert.
-
- Returns
pdTRUE if succeeded
pdFALSE if fail for some reason.
-
-
void *xRingbufferReceive(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait)
Retrieve an item from the ring buffer.
Attempt to retrieve an item from the ring buffer. This function will block until an item is available or until it times out.
Note
A call to vRingbufferReturnItem() is required after this to free the item retrieved.
Note
It is possible to receive items with a pxItemSize of 0 on no-split/allow split buffers.
- Parameters
xRingbuffer -- [in] Ring buffer to retrieve the item from
pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written.
|
[in] Ticks to wait for items in the ring buffer.
-
- Returns
Pointer to the retrieved item on success; *pxItemSize filled with the length of the item.
NULL on timeout, *pxItemSize is untouched in that case.
-
-
void *xRingbufferReceiveFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize)
Retrieve an item from the ring buffer in an ISR.
Attempt to retrieve an item from the ring buffer. This function returns immediately if there are no items available for retrieval
Note
A call to vRingbufferReturnItemFromISR() is required after this to free the item retrieved.
Note
Byte buffers do not allow multiple retrievals before returning an item
Note
Two calls to RingbufferReceiveFromISR() are required if the bytes wrap around the end of the ring buffer.
Note
It is possible to receive items with a pxItemSize of 0 on no-split/allow split buffers.
- Parameters
xRingbuffer -- [in] Ring buffer to retrieve the item from
pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written.
-
- Returns
Pointer to the retrieved item on success; *pxItemSize filled with the length of the item.
NULL when the ring buffer is empty, *pxItemSize is untouched in that case.
-
-
BaseType_t xRingbufferReceiveSplit(RingbufHandle_t xRingbuffer, void **ppvHeadItem, void **ppvTailItem, size_t *pxHeadItemSize, size_t *pxTailItemSize, TickType_t xTicksToWait)
Retrieve a split item from an allow-split ring buffer.
Attempt to retrieve a split item from an allow-split ring buffer. If the item is not split, only a single item is retried. If the item is split, both parts will be retrieved. This function will block until an item is available or until it times out.
Note
Call(s) to vRingbufferReturnItem() is required after this to free up the item(s) retrieved.
Note
This function should only be called on allow-split buffers
Note
It is possible to receive items with a pxItemSize of 0 on allow split buffers.
- Parameters
xRingbuffer -- [in] Ring buffer to retrieve the item from
ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved)
ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split)
pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved)
pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split)
xTicksToWait |
[in] Ticks to wait for items in the ring buffer.
-
- Returns
pdTRUE if an item (split or unsplit) was retrieved
pdFALSE when no item was retrieved
-
-
BaseType_t xRingbufferReceiveSplitFromISR(RingbufHandle_t xRingbuffer, void **ppvHeadItem, void **ppvTailItem, size_t *pxHeadItemSize, size_t *pxTailItemSize)
Retrieve a split item from an allow-split ring buffer in an ISR.
Attempt to retrieve a split item from an allow-split ring buffer. If the item is not split, only a single item is retried. If the item is split, both parts will be retrieved. This function returns immediately if there are no items available for retrieval
Note
Calls to vRingbufferReturnItemFromISR() is required after this to free up the item(s) retrieved.
Note
This function should only be called on allow-split buffers
Note
It is possible to receive items with a pxItemSize of 0 on allow split buffers.
- Parameters
xRingbuffer -- [in] Ring buffer to retrieve the item from
ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved)
ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split)
pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved)
pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split)
-
- Returns
pdTRUE if an item (split or unsplit) was retrieved
pdFALSE when no item was retrieved
-
-
void *xRingbufferReceiveUpTo(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait, size_t xMaxSize)
Retrieve bytes from a byte buffer, specifying the maximum amount of bytes to retrieve.
Attempt to retrieve data from a byte buffer whilst specifying a maximum number of bytes to retrieve. This function will block until there is data available for retrieval or until it times out.
Note
A call to vRingbufferReturnItem() is required after this to free up the data retrieved.
Note
This function should only be called on byte buffers
Note
Byte buffers do not allow multiple retrievals before returning an item
Note
Two calls to RingbufferReceiveUpTo() are required if the bytes wrap around the end of the ring buffer.
- Parameters
xRingbuffer -- [in] Ring buffer to retrieve the item from
pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written.
|
[in] Maximum number of bytes to return.
-
- Returns
Pointer to the retrieved item on success; *pxItemSize filled with the length of the item.
NULL on timeout, *pxItemSize is untouched in that case.
-
-
void *xRingbufferReceiveUpToFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize, size_t xMaxSize)
Retrieve bytes from a byte buffer, specifying the maximum amount of bytes to retrieve. Call this from an ISR.
Attempt to retrieve bytes from a byte buffer whilst specifying a maximum number of bytes to retrieve. This function will return immediately if there is no data available for retrieval.
Note
A call to vRingbufferReturnItemFromISR() is required after this to free up the data received.
Note
This function should only be called on byte buffers
Note
Byte buffers do not allow multiple retrievals before returning an item
- Parameters
xRingbuffer -- [in] Ring buffer to retrieve the item from
pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written.
|
[out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task.
-
-
void vRingbufferDelete(RingbufHandle_t xRingbuffer)
Delete a ring buffer.
Note
This function will not deallocate any memory if the ring buffer was created using xRingbufferCreateStatic(). Deallocation must be done manually be the user.
- Parameters
xRingbuffer -- [in] Ring buffer to delete
-
size_t xRingbufferGetMaxItemSize(RingbufHandle_t xRingbuffer)
Get maximum size of an item that can be placed in the ring buffer.
This function returns the maximum size an item can have if it was placed in an empty ring buffer.
|
Note
The max item size for a no-split buffer is limited to ((buffer_size/2)-header_size). This limit is imposed so that an item of max item size can always be sent to an empty no-split buffer regardless of the internal positions of the buffer's read/write/free pointers.
- Parameters
xRingbuffer -- [in] Ring buffer to query
- Returns
Maximum size, in bytes, of an item that can be placed in a ring buffer.
-
size_t xRingbufferGetCurFreeSize(RingbufHandle_t xRingbuffer)
Get current free size available for an item/data in the buffer.
This gives the real time free space available for an item/data in the ring buffer. This represents the maximum size an item/data can have if it was currently sent to the ring buffer.
Note
An empty no-split buffer has a max current free size for an item that is limited to ((buffer_size/2)-header_size). See API reference for xRingbufferGetMaxItemSize().
Warning
This API is not thread safe. So, if multiple threads are accessing the same ring buffer, it is the application's responsibility to ensure atomic access to this API and the subsequent Send
- Parameters
xRingbuffer -- [in] Ring buffer to query
- Returns
Current free size, in bytes, available for an entry
-
BaseType_t xRingbufferAddToQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet)
Add the ring buffer to a queue set. Notified when data has been written to the ring buffer.
This function adds the ring buffer to a queue set, thus allowing a task to block on multiple queues/ring buffers. The queue set is notified when the new data becomes available to read on the ring buffer.
- Parameters
xRingbuffer -- [in] Ring buffer to add to the queue set
xQueueSet -- [in] Queue set to add the ring buffer to
-
- Returns
pdTRUE on success, pdFALSE otherwise
-
-
static inline BaseType_t xRingbufferCanRead(RingbufHandle_t xRingbuffer, QueueSetMemberHandle_t xMember)
Check if the selected queue set member is a particular ring buffer.
This API checks if queue set member returned from xQueueSelectFromSet() is a particular ring buffer. If so, this indicates the ring buffer has items waiting to be retrieved.
- Parameters
xRingbuffer -- |
[in] Member returned from xQueueSelectFromSet
-
- Returns
pdTRUE when selected queue set member is the ring buffer
pdFALSE otherwise.
-
-
BaseType_t xRingbufferRemoveFromQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet)
Remove the ring buffer from a queue set.
This function removes a ring buffer from a queue set. The ring buffer must have been previously added to the queue set using xRingbufferAddToQueueSetRead().
- Parameters
xRingbuffer -- [in] Ring buffer to remove from the queue set
xQueueSet -- [in] Queue set to remove the ring buffer from
-
- Returns
pdTRUE on success
pdFALSE otherwise
-
-
void vRingbufferGetInfo(RingbufHandle_t xRingbuffer, UBaseType_t *uxFree, UBaseType_t *uxRead, UBaseType_t *uxWrite, UBaseType_t *uxAcquire, UBaseType_t *uxItemsWaiting)
Get information about ring buffer status.
Get information of a ring buffer's current status such as free/read/write/acquire pointer positions, and number of items waiting to be retrieved. Arguments can be set to NULL if they are not required.
- Parameters
xRingbuffer -- [in] Ring buffer to remove from the queue set
uxFree -- [out] Pointer use to store free pointer position
uxRead -- [out] Pointer use to store read pointer position
uxWrite -- [out] Pointer use to store write pointer position
uxAcquire -- [out] Pointer use to store acquire pointer position
uxItemsWaiting -- [out] Pointer use to store number of items (bytes for byte buffer) waiting to be retrieved
-
-
void xRingbufferPrintInfo(RingbufHandle_t xRingbuffer)
Debugging function to print the internal pointers in the ring buffer.
- Parameters
xRingbuffer -- Ring buffer to show
-
BaseType_t xRingbufferGetStaticBuffer(RingbufHandle_t xRingbuffer, uint8_t **ppucRingbufferStorage, StaticRingbuffer_t **ppxStaticRingbuffer)
Retrieve the pointers to a statically created ring buffer.
- Parameters
xRingbuffer -- [in] Ring buffer
ppucRingbufferStorage -- [out] Used to return a pointer to the queue's storage area buffer
ppxStaticRingbuffer -- [out] Used to return a pointer to the queue's data structure buffer
-
- Returns
pdTRUE if buffers were retrieved, pdFALSE otherwise.
-
RingbufHandle_t xRingbufferCreateWithCaps(size_t xBufferSize, RingbufferType_t xBufferType, UBaseType_t uxMemoryCaps)
Creates a ring buffer with specific memory capabilities.
This function is similar to xRingbufferCreate(), except that it allows the memory allocated for the ring buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL).
Note
A queue created using this function must only be deleted using vRingbufferDeleteWithCaps()
- Parameters
xBufferSize -- |
[in] Memory capabilities of the queue's memory (see esp_heap_caps.h)
-
- Returns
Handle to the created ring buffer or NULL on failure.
-
void vRingbufferDeleteWithCaps(RingbufHandle_t xRingbuffer)
Deletes a ring buffer previously created using xRingbufferCreateWithCaps()
- Parameters
xRingbuffer -- Ring buffer
Structures
-
struct xSTATIC_RINGBUFFER
Struct that is equivalent in size to the ring buffer's data structure.
The contents of this struct are not meant to be used directly. This structure is meant to be used when creating a statically allocated ring buffer where this struct is of the exact size required to store a ring buffer's control data structure.
Type Definitions
-
typedef void *RingbufHandle_t
Type by which ring buffers are referenced. For example, a call to xRingbufferCreate() returns a RingbufHandle_t variable that can then be used as a parameter to xRingbufferSend(), xRingbufferReceive(), etc.
-
typedef struct xSTATIC_RINGBUFFER StaticRingbuffer_t
Struct that is equivalent in size to the ring buffer's data structure.
The contents of this struct are not meant to be used directly. This structure is meant to be used when creating a statically allocated ring buffer where this struct is of the exact size required to store a ring buffer's control data structure.
Enumerations
-
enum RingbufferType_t
Values:
-
enumerator RINGBUF_TYPE_NOSPLIT
No-split buffers will only store an item in contiguous memory and will never split an item. Each item requires an 8 byte overhead for a header and will always internally occupy a 32-bit aligned size of space.
-
enumerator RINGBUF_TYPE_ALLOWSPLIT
Allow-split buffers will split an item into two parts if necessary in order to store it. Each item requires an 8 byte overhead for a header, splitting incurs an extra header. Each item will always internally occupy a 32-bit aligned size of space.
-
enumerator RINGBUF_TYPE_BYTEBUF
Byte buffers store data as a sequence of bytes and do not maintain separate items, therefore byte buffers have no overhead. All data is stored as a sequence of byte and any number of bytes can be sent or retrieved each time.
-
enumerator RINGBUF_TYPE_MAX
- enumerator RINGBUF_TYPE_NOSPLIT
Hooks API
Header File
This header file can be included with:
#include "esp_freertos_hooks.h"
Functions
-
esp_err_t esp_register_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t new_idle_cb, UBaseType_t cpuid)
Register a callback to be called from the specified core's idle hook. The callback should return true if it should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called repeatedly as fast as possible by the idle hook.
|
[in] Callback to be called
cpuid -- [in] id of the core
-
- Returns
ESP_OK: Callback registered to the specified core's idle hook
ESP_ERR_NO_MEM: No more space on the specified core's idle hook to register callback
ESP_ERR_INVALID_ARG: cpuid is invalid
-
-
esp_err_t esp_register_freertos_idle_hook(esp_freertos_idle_cb_t new_idle_cb)
Register a callback to the idle hook of the core that calls this function. The callback should return true if it should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called repeatedly as fast as possible by the idle hook.
|
- Parameters
new_tick_cb -- [in] Callback to be called
- Returns
ESP_OK: Callback registered to the calling core's tick hook
ESP_ERR_NO_MEM: No more space on the calling core's tick hook to register the callback
-
-
void esp_deregister_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t old_idle_cb, UBaseType_t cpuid)
Unregister an idle callback from the idle hook of the specified core.
- Parameters
old_idle_cb -- [in] Callback to be unregistered
cpuid -- [in] id of the core
-
-
void esp_deregister_freertos_idle_hook(esp_freertos_idle_cb_t old_idle_cb)
|
Unregister an idle callback. If the idle callback is registered to the idle hooks of both cores, the idle hook will be unregistered from both cores.
- Parameters
old_idle_cb -- [in] Callback to be unregistered
-
void esp_deregister_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t old_tick_cb, UBaseType_t cpuid)
Unregister a tick callback from the tick hook of the specified core.
- Parameters
old_tick_cb -- [in] Callback to be unregistered
cpuid -- [in] id of the core
-
-
void esp_deregister_freertos_tick_hook(esp_freertos_tick_cb_t old_tick_cb)
|
Unregister a tick callback. If the tick callback is registered to the tick hooks of both cores, the tick hook will be unregistered from both cores.
- Parameters
old_tick_cb -- [in] Callback to be unregistered
Type Definitions
-
typedef bool (*esp_freertos_idle_cb_t)(void)
-
typedef void (*esp_freertos_tick_cb_t)(void)
Additional API
Header File
components/freertos/esp_additions/include/freertos/idf_additions.h
This header file can be included with:
#include "freertos/idf_additions.h"
Functions
-
BaseType_t xTaskCreatePinnedToCore(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask, const BaseType_t xCoreID)
Create a new task that is pinned to a particular core.
This function is similar to xTaskCreate(), but allows the creation of a pinned task. The task's pinned core is specified by the xCoreID argument. If xCoreID is set to tskNO_AFFINITY, then the task is unpinned and can run on any core.
|
The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity.
-
- Returns
pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h
-
TaskHandle_t xTaskCreateStaticPinnedToCore(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, StackType_t *const puxStackBuffer, StaticTask_t *const pxTaskBuffer, const BaseType_t xCoreID)
Create a new static task that is pinned to a particular core.
This function is similar to xTaskCreateStatic(), but allows the creation of a pinned task. The task's pinned core is specified by the xCoreID argument. If xCoreID is set to tskNO_AFFINITY, then the task is unpinned and can run on any core.
|
The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS.
pvParameters -- Pointer that will be used as the parameter for the task being created.
uxPriority -- The priority at which the task should run.
puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes
pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures,
xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity.
-
- Returns
The task handle if the task was created, NULL otherwise.
-
BaseType_t xTaskGetCoreID(TaskHandle_t xTask)
Get the current core ID of a particular task.
Helper function to get the core ID of a particular task. If the task is pinned to a particular core, the core ID is returned. If the task is not pinned to a particular core, tskNO_AFFINITY is returned.
If CONFIG_FREERTOS_UNICORE is enabled, this function simply returns 0.
|
See if this needs to be deprecated ( IDF-8145)
Note
If CONFIG_FREERTOS_SMP is enabled, please call xTaskGetIdleTaskHandle() instead.
- Parameters
xCoreID -- The core to query
- Returns
Handle of the idle task for the queried core
-
TaskHandle_t xTaskGetCurrentTaskHandleForCore(BaseType_t xCoreID)
Get the handle of the task currently running on a certain core.
Because of the nature of SMP processing, there is no guarantee that this value will still be valid on return and should only be used for debugging purposes.
|
[refactor-todo] Change return type to StackType_t (IDF-8158)
- Parameters
xTask -- Handle of the task associated with the stack returned. Set xTask to NULL to return the stack of the calling task.
- Returns
A pointer to the start of the stack.
-
void vTaskSetThreadLocalStoragePointerAndDelCallback(TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue, TlsDeleteCallbackFunction_t pvDelCallback)
Set local storage pointer and deletion callback.
Each task contains an array of pointers that is dimensioned by the configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does not use the pointers itself, so the application writer can use the pointers for any purpose they wish.
Local storage pointers set for a task can reference dynamically allocated resources. This function is similar to vTaskSetThreadLocalStoragePointer, but provides a way to release these resources when the task gets deleted. For each pointer, a callback function can be set. This function will be called when task is deleted, with the local storage pointer index and value as arguments.
- Parameters
xTaskToSet -- Task to set thread local storage pointer for
xIndex -- The index of the pointer to set, from 0 to configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1.
pvValue -- Pointer value to set.
pvDelCallback -- Function to call to dispose of the local storage pointer when the task is deleted.
-
-
BaseType_t xTaskCreatePinnedToCoreWithCaps(TaskFunction_t pvTaskCode, const char *const pcName, const configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pvCreatedTask, const BaseType_t xCoreID, UBaseType_t uxMemoryCaps)
Creates a pinned task where its stack has specific memory capabilities.
This function is similar to xTaskCreatePinnedToCore(), except that it allows the memory allocated for the task's stack to have specific capabilities (e.g., MALLOC_CAP_SPIRAM).
However, the specified capabilities will NOT apply to the task's TCB as a TCB must always be in internal RAM.
- Parameters
pvTaskCode -- Pointer to the task entry function
pcName -- A descriptive name for the task
usStackDepth -- The size of the task stack specified as the number of bytes
pvParameters -- Pointer that will be used as the parameter for the task being created.
uxPriority -- The priority at which the task should run.
pvCreatedTask -- Used to pass back a handle by which the created task can be referenced.
|
Core to which the task is pinned to, or tskNO_AFFINITY if unpinned.
uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h)
-
- Returns
pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h
-
static inline BaseType_t xTaskCreateWithCaps(TaskFunction_t pvTaskCode, const char *const pcName, configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *pvCreatedTask, UBaseType_t uxMemoryCaps)
Creates a task where its stack has specific memory capabilities.
This function is similar to xTaskCreate(), except that it allows the memory allocated for the task's stack to have specific capabilities (e.g., MALLOC_CAP_SPIRAM).
However, the specified capabilities will NOT apply to the task's TCB as a TCB must always be in internal RAM.
Note
A task created using this function must only be deleted using vTaskDeleteWithCaps()
- Parameters
pvTaskCode -- Pointer to the task entry function
pcName -- A descriptive name for the task
usStackDepth -- The size of the task stack specified as the number of bytes
pvParameters -- Pointer that will be used as the parameter for the task being created.
uxPriority -- The priority at which the task should run.
pvCreatedTask -- Used to pass back a handle by which the created task can be referenced.
uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h)
-
- Returns
pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h
-
void vTaskDeleteWithCaps(TaskHandle_t xTaskToDelete)
Deletes a task previously created using xTaskCreateWithCaps() or xTaskCreatePinnedToCoreWithCaps()
- Parameters
xTaskToDelete -- A handle to the task to be deleted
-
QueueHandle_t xQueueCreateWithCaps(UBaseType_t uxQueueLength, UBaseType_t uxItemSize, UBaseType_t uxMemoryCaps)
Creates a queue with specific memory capabilities.
This function is similar to xQueueCreate(), except that it allows the memory allocated for the queue to have specific capabilities (e.g., MALLOC_CAP_INTERNAL).
Note
A queue created using this function must only be deleted using vQueueDeleteWithCaps()
- Parameters
uxQueueLength -- The maximum number of items that the queue can contain.
|
The total number of bytes the stream buffer will be able to hold at any one time.
xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before unblocking
uxMemoryCaps -- Memory capabilities of the stream buffer's memory (see esp_heap_caps.h)
-
- Returns
Handle to the created stream buffer or NULL on failure.
-
static inline void vStreamBufferDeleteWithCaps(StreamBufferHandle_t xStreamBuffer)
Deletes a stream buffer previously created using xStreamBufferCreateWithCaps()
- Parameters
xStreamBuffer -- A handle to the stream buffer to be deleted.
-
static inline MessageBufferHandle_t xMessageBufferCreateWithCaps(size_t xBufferSizeBytes, UBaseType_t uxMemoryCaps)
Creates a message buffer with specific memory capabilities.
This function is similar to xMessageBufferCreate(), except that it allows the memory allocated for the message buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL).
Note
A message buffer created using this function must only be deleted using vMessageBufferDeleteWithCaps()
- Parameters
xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time.
uxMemoryCaps -- Memory capabilities of the message buffer's memory (see esp_heap_caps.h)
-
- Returns
Handle to the created message buffer or NULL on failure.
-
static inline void vMessageBufferDeleteWithCaps(MessageBufferHandle_t xMessageBuffer)
Deletes a stream buffer previously created using xMessageBufferCreateWithCaps()
- Parameters
xMessageBuffer -- A handle to the message buffer to be deleted.
-
EventGroupHandle_t xEventGroupCreateWithCaps(UBaseType_t uxMemoryCaps)
Creates an event group with specific memory capabilities.
This function is similar to xEventGroupCreate(), except that it allows the memory allocated for the event group to have specific capabilities (e.g., MALLOC_CAP_INTERNAL).
Note
An event group created using this function must only be deleted using vEventGroupDeleteWithCaps()
- Parameters
uxMemoryCaps -- Memory capabilities of the event group's memory (see esp_heap_caps.h)
- Returns
Handle to the created event group or NULL on failure.
-
void vEventGroupDeleteWithCaps(EventGroupHandle_t xEventGroup)
Deletes an event group previously created using xEventGroupCreateWithCaps()
- Parameters
xEventGroup -- |
Heap Memory Allocation
Stack and Heap
ESP-IDF applications use the common computer architecture patterns of stack (dynamic memory allocated by program control flow), heap (dynamic memory allocated by function calls), and static memory (memory allocated at compile time).
Because ESP-IDF is a multi-threaded RTOS environment, each RTOS task has its own stack. By default, each of these stacks is allocated from the heap when the task is created. See
xTaskCreateStatic() for the alternative where stacks are statically allocated.
Because ESP32 uses multiple types of RAM, it also contains multiple heaps with different capabilities. A capabilities-based memory allocator allows apps to make heap allocations for different purposes.
For most purposes, the C Standard Library's
malloc() and
free() functions can be used for heap allocation without any special consideration. However, in order to fully make use of all of the memory types and their characteristics, ESP-IDF also has a capabilities-based heap memory allocator. If you want to have a memory with certain properties (e.g., DMA-Capable Memory or executable-memory), you can create an OR-mask of the required capabilities and pass that to
heap_caps_malloc().
Memory Capabilities
The ESP32 contains multiple types of RAM:
DRAM (Data RAM) is memory that is connected to CPU's data bus and is used to hold data. This is the most common kind of memory accessed as a heap.
IRAM (Instruction RAM) is memory that is connected to the CPU's instruction bus and usually holds executable data only (i.e., instructions). If accessed as generic memory, all accesses must be aligned to 32-Bit Accessible Memory.
D/IRAM is RAM that is connected to CPU's data bus and instruction bus, thus can be used either Instruction or Data RAM.
For more details on these internal memory types, see Memory Types.
It is also possible to connect external SPI RAM to the ESP32. The external RAM is integrated into the ESP32's memory map via the cache, and accessed similarly to DRAM.
All DRAM memory is single-byte accessible, thus all DRAM heaps possess the
MALLOC_CAP_8BIT capability. Users can call
heap_caps_get_free_size(MALLOC_CAP_8BIT) to get the free size of all DRAM heaps.
If ran out of
MALLOC_CAP_8BIT, the users can use
MALLOC_CAP_IRAM_8BIT instead. In that case, IRAM can still be used as a "reserve" pool of internal memory if the users only access it in a 32-bit aligned manner, or if they enable
CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY).
|
At startup, the DRAM heap contains all data memory that is not statically allocated by the app. Reducing statically-allocated buffers increases the amount of available free heap.
To find the amount of statically allocated memory, use the idf.py size command.
Note
See the DRAM (Data RAM) section for more details about the DRAM usage limitations.
Note
At runtime, the available heap DRAM may be less than calculated at compile time, because, at startup, some memory is allocated from the heap before the FreeRTOS scheduler is started (including memory for the stacks of initial FreeRTOS tasks).
IRAM
At startup, the IRAM heap contains all instruction memory that is not used by the app executable code.
The idf.py size command can be used to find the amount of IRAM used by the app.
D/IRAM
Some memory in the ESP32 is available as either DRAM or IRAM. If memory is allocated from a D/IRAM region, the free heap size for both types of memory will decrease.
|
Special Capabilities
DMA-Capable Memory
Use the
MALLOC_CAP_DMA flag to allocate memory which is suitable for use with hardware DMA engines (for example SPI and I2S). This capability flag excludes any external PSRAM.
32-Bit Accessible Memory
If a certain memory structure is only addressed in 32-bit units, for example, an array of ints or pointers, it can be useful to allocate it with the
MALLOC_CAP_32BIT flag. This also allows the allocator to give out IRAM memory, which is sometimes unavailable for a normal
malloc() call. This can help to use all the available memory in the ESP32.
Please note that on ESP32 series chips,
MALLOC_CAP_32BIT cannot be used for storing floating-point variables. This is because
MALLOC_CAP_32BIT may return instruction RAM and the floating-point assembly instructions on ESP32 cannot access instruction RAM.
Memory allocated with
MALLOC_CAP_32BIT can only be accessed via 32-bit reads and writes, any other type of access will generate a fatal LoadStoreError exception.
External SPI Memory
When external RAM is enabled, external SPI RAM can be allocated using standard
malloc calls, or via
heap_caps_malloc(MALLOC_CAP_SPIRAM), depending on the configuration. See Configuring External RAM for more details.
On ESP32 only external SPI RAM under 4 MiB in size can be allocated this way. To use the region above the 4 MiB limit, you can use the himem API.
Thread Safety
Heap functions are thread-safe, meaning they can be called from different tasks simultaneously without any limitations.
It is technically possible to call
malloc,
free, and related functions from interrupt handler (ISR) context (see Calling Heap-Related Functions from ISR). However, this is not recommended, as heap function calls may delay other interrupts. It is strongly recommended to refactor applications so that any buffers used by an ISR are pre-allocated outside of the ISR. Support for calling heap functions from ISRs may be removed in a future update.
|
Implementation Notes
Knowledge about the regions of memory in the chip comes from the "SoC" component, which contains memory layout information for the chip, and the different capabilities of each region. Each region's capabilities are prioritized, so that (for example) dedicated DRAM and IRAM regions are used for allocations ahead of the more versatile D/IRAM regions.
Each contiguous region of memory contains its own memory heap. The heaps are created using the multi_heap functionality.
multi_heap allows any contiguous region of memory to be used as a heap.
The heap capabilities allocator uses knowledge of the memory regions to initialize each individual heap. Allocation functions in the heap capabilities API will find the most appropriate heap for the allocation based on desired capabilities, available space, and preferences for each region's use, and then calling
multi_heap_malloc() for the heap situated in that particular region.
Calling
free() involves finding the particular heap corresponding to the freed address, and then call
multi_heap_free() on that particular
multi_heap instance.
API Reference - Heap Allocation
Header File
This header file can be included with:
#include "esp_heap_caps.h"
Functions
-
esp_err_t heap_caps_register_failed_alloc_callback(esp_alloc_failed_hook_t callback)
registers a callback function to be invoked if a memory allocation operation fails
- Parameters
callback -- caller defined callback to be invoked
- Returns
ESP_OK if callback was registered.
-
void *heap_caps_malloc(size_t size, uint32_t caps)
Allocate a chunk of memory which has the given capabilities.
Equivalent semantics to libc malloc(), for capability-aware memory.
- Parameters
size -- Size, in bytes, of the amount of memory to allocate
caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned
-
- Returns
A pointer to the memory allocated on success, NULL on failure
-
void heap_caps_free(void *ptr)
Free memory previously allocated via heap_caps_malloc() or heap_caps_realloc().
Equivalent semantics to libc free(), for capability-aware memory.
In IDF,
free(p)is equivalent to
heap_caps_free(p).
- Parameters
ptr -- Pointer to memory previously returned from heap_caps_malloc() or heap_caps_realloc(). |
Use heap_caps_get_largest_free_block() for this purpose.
- Parameters
caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
- Returns
Amount of free bytes in the regions
-
size_t heap_caps_get_minimum_free_size(uint32_t caps)
Get the total minimum free memory of all regions with the given capabilities.
This adds all the low watermarks of the regions capable of delivering the memory with the given capabilities.
Note
Note the result may be less than the global all-time minimum available heap of this kind, as "low watermarks" are tracked per-region. Individual regions' heaps may have reached their "low watermarks" at different points in time. However, this result still gives a "worst case" indication for all-time minimum free heap.
- Parameters
caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
- Returns
Amount of free bytes in the regions
-
size_t heap_caps_get_largest_free_block(uint32_t caps)
Get the largest free block of memory able to be allocated with the given capabilities.
Returns the largest value of
sfor which
heap_caps_malloc(s, caps)will succeed.
- Parameters
caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
- Returns
Size of the largest free block in bytes.
-
void heap_caps_get_info(multi_heap_info_t *info, uint32_t caps)
Get heap info for all regions with the given capabilities.
Calls multi_heap_info() on all heaps which share the given capabilities. The information returned is an aggregate across all matching heaps. The meanings of fields are the same as defined for multi_heap_info_t, except that
minimum_free_byteshas the same caveats described in heap_caps_get_minimum_free_size().
- Parameters
info -- Pointer to a structure which will be filled with relevant heap metadata.
caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
-
-
void heap_caps_print_heap_info(uint32_t caps)
Print a summary of all memory with the given capabilities.
Calls multi_heap_info on all heaps which share the given capabilities, and prints a two-line summary for each, then a total summary.
- Parameters
caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
-
bool heap_caps_check_integrity_all(bool print_errors)
Check integrity of all heap memory in the system.
Calls multi_heap_check on all heaps. |
Reallocate a chunk of memory as preference in decreasing order.
- Parameters
ptr -- Pointer to previously allocated memory, or NULL for a new allocation.
size -- Size of the new buffer requested, or 0 to free the buffer.
num -- Number of variable paramters
-
- Returns
Pointer to a new buffer of size 'size', or NULL if allocation failed.
-
void *heap_caps_calloc_prefer(size_t n, size_t size, size_t num, ...)
Allocate a chunk of memory as preference in decreasing order.
- Parameters
n -- Number of continuing chunks of memory to allocate
size -- Size, in bytes, of a chunk of memory to allocate
num -- Number of variable paramters
-
- Returns
A pointer to the memory allocated on success, NULL on failure
-
void heap_caps_dump(uint32_t caps)
Dump the full structure of all heaps with matching capabilities.
Prints a large amount of output to serial (because of locking limitations, the output bypasses stdout/stderr). For each (variable sized) block in each matching heap, the following output is printed on a single line:
Block address (the data buffer returned by malloc is 4 bytes after this if heap debugging is set to Basic, or 8 bytes otherwise).
Data size (the data size may be larger than the size requested by malloc, either due to heap fragmentation or because of heap debugging level).
Address of next block in the heap.
If the block is free, the address of the next free block is also printed.
- Parameters
caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
-
-
void heap_caps_dump_all(void)
Dump the full structure of all heaps.
Covers all registered heaps. |
Call this function to add a region of memory to the heap at some later time.
This function does not consider any of the "reserved" regions or other data in soc_memory_layout, caller needs to consider this themselves.
All memory within the region specified by start & end parameters must be otherwise unused.
The capabilities of the newly registered memory will be determined by the start address, as looked up in the regions specified in soc_memory_layout.c.
Use heap_caps_add_region_with_caps() to register a region with custom capabilities.
Note
Please refer to following example for memory regions allowed for addition to heap based on an existing region (address range for demonstration purpose only):
Existing region: 0x1000 <-> 0x3000 New region: 0x1000 <-> 0x3000 (Allowed) New region: 0x1000 <-> 0x2000 (Allowed) New region: 0x0000 <-> 0x1000 (Allowed) New region: 0x3000 <-> 0x4000 (Allowed) New region: 0x0000 <-> 0x2000 (NOT Allowed) New region: 0x0000 <-> 0x4000 (NOT Allowed) New region: 0x1000 <-> 0x4000 (NOT Allowed) New region: 0x2000 <-> 0x4000 (NOT Allowed)
- Parameters
start -- Start address of new region.
|
Add a region of memory to the collection of heaps at runtime, with custom capabilities.
Similar to heap_caps_add_region(), only custom memory capabilities are specified by the caller.
Note
Please refer to following example for memory regions allowed for addition to heap based on an existing region (address range for demonstration purpose only):
Existing region: 0x1000 <-> 0x3000 New region: 0x1000 <-> 0x3000 (Allowed) New region: 0x1000 <-> 0x2000 (Allowed) New region: 0x0000 <-> 0x1000 (Allowed) New region: 0x3000 <-> 0x4000 (Allowed) New region: 0x0000 <-> 0x2000 (NOT Allowed) New region: 0x0000 <-> 0x4000 (NOT Allowed) New region: 0x1000 <-> 0x4000 (NOT Allowed) New region: 0x2000 <-> 0x4000 (NOT Allowed)
- Parameters
caps -- Ordered array of capability masks for the new region, in order of priority. |
End address of new region.
-
- Returns
ESP_OK on success
ESP_ERR_INVALID_ARG if a parameter is invalid
ESP_ERR_NO_MEM if no memory to register new heap.
ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap
ESP_FAIL if region overlaps the start and/or end of an existing region
-
API Reference - Multi-Heap API
(Note: The multi-heap API is used internally by the heap capabilities allocator. Most ESP-IDF programs never need to call this API directly.)
Header File
This header file can be included with:
#include "multi_heap.h"
Functions
-
void *multi_heap_aligned_alloc(multi_heap_handle_t heap, size_t size, size_t alignment)
allocate a chunk of memory with specific alignment
- Parameters
heap -- Handle to a registered heap.
size -- size in bytes of memory chunk
alignment -- how the memory must be aligned
-
- Returns
pointer to the memory allocated, NULL on failure
-
void *multi_heap_malloc(multi_heap_handle_t heap, size_t size)
malloc() a buffer in a given heap
Semantics are the same as standard malloc(), only the returned buffer will be allocated in the specified heap.
- Parameters
heap -- Handle to a registered heap.
size -- Size of desired buffer.
-
- Returns
Pointer to new memory, or NULL if allocation fails.
-
void multi_heap_aligned_free(multi_heap_handle_t heap, void *p)
free() a buffer aligned in a given heap.
Note
This function is deprecated, consider using multi_heap_free() instead
- Parameters
heap -- Handle to a registered heap.
p -- NULL, or a pointer previously returned from multi_heap_aligned_alloc() for the same heap.
-
-
void multi_heap_free(multi_heap_handle_t heap, void *p)
free() a buffer in a given heap.
Semantics are the same as standard free(), only the argument 'p' must be NULL or have been allocated in the specified heap.
- Parameters
heap -- Handle to a registered heap.
|
p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap.
size -- Desired new size for buffer.
-
- Returns
New buffer of 'size' containing contents of 'p', or NULL if reallocation failed.
-
size_t multi_heap_get_allocated_size(multi_heap_handle_t heap, void *p)
Return the size that a particular pointer was allocated with.
- Parameters
heap -- Handle to a registered heap.
p -- Pointer, must have been previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap.
-
- Returns
Size of the memory allocated at this block. May be more than the original size argument, due to padding and minimum block sizes.
-
multi_heap_handle_t multi_heap_register(void *start, size_t size)
|
Register a new heap for use.
This function initialises a heap at the specified address, and returns a handle for future heap operations.
There is no equivalent function for deregistering a heap - if all blocks in the heap are free, you can immediately start using the memory for other purposes.
- Parameters
start -- Start address of the memory to use for a new heap.
size -- Size (in bytes) of the new heap.
-
- Returns
Handle of a new heap ready for use, or NULL if the heap region was too small to be initialised.
-
void multi_heap_set_lock(multi_heap_handle_t heap, void *lock)
Associate a private lock pointer with a heap.
|
The lock in question must be recursive.
When the heap is first registered, the associated lock is NULL.
- Parameters
heap -- Handle to a registered heap.
lock -- Optional pointer to a locking structure to associate with this heap.
-
-
void multi_heap_dump(multi_heap_handle_t heap)
Dump heap information to stdout.
For debugging purposes, this function dumps information about every block in the heap to stdout.
- Parameters
heap -- Handle to a registered heap.
-
bool multi_heap_check(multi_heap_handle_t heap, bool print_errors)
Check heap integrity.
Walks the heap and checks all heap data structures are valid. If any errors are detected, an error-specific message can be optionally printed to stderr. Print behaviour can be overridden at compile time by defining MULTI_CHECK_FAIL_PRINTF in multi_heap_platform.h.
Note
This function is not thread-safe as it sets a global variable with the value of print_errors.
- Parameters
heap -- Handle to a registered heap.
print_errors -- If true, errors will be printed to stderr.
-
- Returns
true if heap is valid, false otherwise.
-
size_t multi_heap_free_size(multi_heap_handle_t heap)
|
Return free heap size.
Returns the number of bytes available in the heap.
Equivalent to the total_free_bytes member returned by multi_heap_get_heap_info().
Note that the heap may be fragmented, so the actual maximum size for a single malloc() may be lower. To know this size, see the largest_free_block member returned by multi_heap_get_heap_info().
- Parameters
heap -- Handle to a registered heap.
- Returns
Number of free bytes.
-
size_t multi_heap_minimum_free_size(multi_heap_handle_t heap)
Return the lifetime minimum free heap size.
|
Equivalent to the minimum_free_bytes member returned by multi_heap_get_info().
Returns the lifetime "low watermark" of possible values returned from multi_free_heap_size(), for the specified heap.
- Parameters
heap -- Handle to a registered heap.
- Returns
Number of free bytes.
-
void multi_heap_get_info(multi_heap_handle_t heap, multi_heap_info_t *info)
Return metadata about a given heap.
Fills a multi_heap_info_t structure with information about the specified heap.
- Parameters
heap -- Handle to a registered heap.
info -- Pointer to a structure to fill with heap metadata.
-
-
void *multi_heap_aligned_alloc_offs(multi_heap_handle_t heap, size_t size, size_t alignment, size_t offset)
Perform an aligned allocation from the provided offset.
- Parameters
heap -- The heap in which to perform the allocation
size -- The size of the allocation
alignment -- How the memory must be aligned
offset -- The offset at which the alignment should start
-
- Returns
void* The ptr to the allocated memory
Structures
-
struct multi_heap_info_t
Structure to access heap metadata via multi_heap_get_info.
Public Members
-
size_t total_free_bytes
Total free bytes in the heap. Equivalent to multi_free_heap_size().
-
size_t total_allocated_bytes
Total bytes allocated to data in the heap.
-
size_t largest_free_block
Size of the largest free block in the heap. This is the largest malloc-able size.
-
size_t minimum_free_bytes
Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size().
-
size_t allocated_blocks
Number of (variable size) blocks allocated in the heap.
-
size_t free_blocks
Number of (variable size) free blocks in the heap.
-
size_t total_blocks
Total number of (variable size) blocks in the heap.
- size_t total_free_bytes
Type Definitions
-
typedef struct multi_heap_info *multi_heap_handle_t
Opaque handle to a registered heap. |
Memory Management for MMU Supported Memory
Introduction
ESP32 Memory Management Unit (MMU) is relatively simple. It can do memory address translation between physical memory addresses and virtual memory addresses. So CPU can access physical memories via virtual addresses. There are multiple types of virtual memory addresses, which have different capabilities.
ESP-IDF provides a memory mapping driver that manages the relation between these physical memory addresses and virtual memory addresses, so as to achieve some features such as reading from SPI flash via a pointer.
Memory mapping driver is actually a capabilities-based virtual memory address allocator that allows applications to make virtual memory address allocations for different purposes. In the following chapters, we call this driver
esp_mmap driver.
ESP-IDF also provides a memory synchronization driver which can be used for potential memory desynchronization scenarios.
Physical Memory Types
Memory mapping driver currently supports mapping to following physical memory type(s):
SPI flash
Virtual Memory Capabilities
MMU_MEM_CAP_EXEC: This capability indicates that the virtual memory address has the execute permission. Note this permission scope is within the MMU hardware.
|
This capability indicates that the virtual memory address allows for 8 bits or multiples of 8 bits access.
8 MB external memory addresses (from 0x40400000 to 0x40C00000) which have the
MMU_MEM_CAP_EXEC and
MMU_MEM_CAP_READ capabilities are not available for users to allocate, due to hardware limitations.
You can call
esp_mmu_map_get_max_consecutive_free_block_size() to know the largest consecutive mappable block size with certain capabilities.
Memory Management Drivers
Driver Concept
Terminology
The virtual memory pool is made up with one or multiple virtual memory regions, see below figure:
A virtual memory pool stands for the whole virtual address range that can be mapped to physical memory.
A virtual memory region is a range of virtual address with same attributes.
A virtual memory block is a piece of virtual address range that is dynamically mapped.
A slot is the virtual address range between two virtual memory blocks.
A physical memory block is a piece of physical address range that is to-be-mapped or already mapped to a virtual memory block.
|
Dynamical mapping is done by calling
esp_mmapdriver API
esp_mmu_map(). This API maps the given physical memory block to a virtual memory block which is allocated by the
esp_mmapdriver.
Relation Between Memory Blocks
When mapping a physical memory block A, block A can have one of the following relations with another previously mapped physical memory block B:
Enclosed: block A is completely enclosed within block B, see figure below:
Identical: block A is completely the same as block B, see figure below:
Note that
esp_mmapdriver considers the identical scenario the same as the enclosed scenario.
Overlapped: block A is overlapped with block B, see figure below:
There is a special condition, when block A entirely encloses block B, see figure below:
Note that
esp_mmapdriver considers this scenario the same as the overlapped scenario.
Driver Behaviour
Memory Map
You can call
esp_mmu_map() to do a dynamical mapping. This API can allocate a certain size of virtual memory block according to the virtual memory capabilities you selected, then map this virtual memory block to the physical memory block as you requested. The
esp_mmap driver supports mapping to one or more types of physical memory, so you should specify the physical memory target when mapping.
By default, physical memory blocks and virtual memory blocks are one-to-one mapped. This means, when calling
esp_mmu_map():
If it is the enclosed scenario, this API will return an
ESP_ERR_INVALID_STATE. The
out_ptrwill be assigned to the start virtual memory address of the previously mapped one which encloses the to-be-mapped one.
If it is the identical scenario, this API will behaves exactly the same as the enclosed scenario.
If it is the overlapped scenario, this API will by default return an
ESP_ERR_INVALID_ARG. This means,
esp_mmapdriver by default does not allow mapping a physical memory address to multiple virtual memory addresses.
Specially, you can use
ESP_MMU_MMAP_FLAG_PADDR_SHARED. This flag stands for one-to-multiple mapping between a physical address and multiple virtual addresses:
If it is the overlapped scenario, this API will allocate a new virtual memory block as requested, then map to the given physical memory block.
Memory Unmap
You can call
esp_mmu_unmap() to unmap a previously mapped memory block. This API returns an
ESP_ERR_NOT_FOUND if you are trying to unmap a virtual memory block that is not mapped to any physical memory block yet.
Memory Address Conversion
The
esp_mmap driver provides two helper APIs to do the conversion between virtual memory address and physical memory address:
esp_mmu_vaddr_to_paddr()converts virtual address to physical address.
esp_mmu_paddr_to_vaddr()converts physical address to virtual address.
Memory Synchronization
MMU supported physical memories can be accessed by one or multiple methods.
SPI flash can be accessed by SPI1 (ESP-IDF
esp_flash driver APIs), or by pointers. |
ESP-IDF
esp_flash driver APIs have already considered the memory synchronization, so users do not need to worry about this.
PSRAM can be accessed by pointers, hardware guarantees the data consistency when PSRAM is only accessed via pointers.
Thread Safety
APIs in
esp_mmu_map.h are not guaranteed to be thread-safe.
APIs in
esp_cache.h are guaranteed to be thread-safe.
API Reference
API Reference - ESP MMAP Driver
Header File
This header file can be included with:
#include "esp_mmu_map.h"
This header file is a part of the API provided by the
esp_mmcomponent. To declare that your component depends on
esp_mm, add the following to your CMakeLists.txt:
REQUIRES esp_mm
or
PRIV_REQUIRES esp_mm
Functions
-
esp_err_t esp_mmu_map(esp_paddr_t paddr_start, size_t size, mmu_target_t target, mmu_mem_caps_t caps, int flags, void **out_ptr)
Map a physical memory block to external virtual address block, with given capabilities.
Note
This API does not guarantee thread safety
- Parameters
paddr_start -- |
Physical memory target you're going to map to, see
mmu_target_t.
out_len -- [out] Largest free block length, in bytes.
-
- Returns
ESP_OK
ESP_ERR_INVALID_ARG: Invalid arguments, could be null pointer
-
-
esp_err_t esp_mmu_map_dump_mapped_blocks(FILE *stream)
Dump all the previously mapped blocks
Note
This API shall not be called from an ISR.
Note
This API does not guarantee thread safety
- Parameters
stream -- stream to print information to; use stdout or stderr to print to the console; use fmemopen/open_memstream to print to a string buffer.
- Returns
ESP_OK
-
-
esp_err_t esp_mmu_vaddr_to_paddr(void *vaddr, esp_paddr_t *out_paddr, mmu_target_t *out_target)
Convert virtual address to physical address.
- Parameters
vaddr -- [in] Virtual address
out_paddr -- [out] Physical address
out_target -- [out] Physical memory target, see
mmu_target_t
-
- Returns
ESP_OK
ESP_ERR_INVALID_ARG: Null pointer, or vaddr is not within external memory
ESP_ERR_NOT_FOUND: Vaddr is not mapped yet
-
-
esp_err_t esp_mmu_paddr_to_vaddr(esp_paddr_t paddr, mmu_target_t target, mmu_vaddr_t type, void **out_vaddr)
Convert physical address to virtual address.
|
Paddr is not mapped yet
-
-
esp_err_t esp_mmu_paddr_find_caps(const esp_paddr_t paddr, mmu_mem_caps_t *out_caps)
If the physical address is mapped, this API will provide the capabilities of the virtual address where the physical address is mapped to.
Note
: Only return value is ESP_OK(which means physically address is successfully mapped), then caps you get make sense.
Note
This API only check one page (see CONFIG_MMU_PAGE_SIZE), starting from the
paddr
- Parameters
paddr -- [in] Physical address
out_caps -- [out] Bitwise OR of MMU_MEM_CAP_* flags indicating the capabilities of a virtual address where the physical address is mapped to.
-
- Returns
ESP_OK: Physical address successfully mapped.
|
Heap Memory Debugging
Overview
ESP-IDF integrates tools for requesting heap information, heap corruption detection, and heap tracing. These can help track down memory-related bugs.
For general information about the heap memory allocator, see Heap Memory Allocation.
Heap Information
To obtain information about the state of the heap, call the following functions:
heap_caps_get_free_size()can be used to return the current free memory for different memory capabilities.
heap_caps_get_largest_free_block()can be used to return the largest free block in the heap, which is also the largest single allocation currently possible. Tracking this value and comparing it to the total free heap allows you to detect heap fragmentation.
heap_caps_get_minimum_free_size()can be used to track the heap "low watermark" since boot.
heap_caps_get_info()returns a
multi_heap_info_tstructure, which contains the information from the above functions, plus some additional heap-specific data (number of allocations, etc.).
heap_caps_print_heap_info()prints a summary of the information returned by
heap_caps_get_info()to stdout.
heap_caps_dump()and
heap_caps_dump_all()output detailed information about the structure of each block in the heap. Note that this can be a large amount of output.
Heap Allocation and Free Function Hooks
Heap allocation and free detection hooks allow you to be notified of every successful allocation and free operation:
Providing a definition of
esp_heap_trace_alloc_hook()allows you to be notified of every successful memory allocation operation
Providing a definition of
esp_heap_trace_free_hook()allows you to be notified of every successful memory-free operations
This feature can be enabled by setting the CONFIG_HEAP_USE_HOOKS option.
|
esp_heap_trace_alloc_hook() and
esp_heap_trace_free_hook() have weak declarations (e.g.,
__attribute__((weak))), thus it is not necessary to provide declarations for both hooks. Given that it is technically possible to allocate and free memory from an ISR (though strongly discouraged from doing so), the
esp_heap_trace_alloc_hook() and
esp_heap_trace_free_hook() can potentially be called from an ISR.
It is not recommended to perform (or call API functions to perform) blocking operations or memory allocation/free operations in the hook functions. In general, the best practice is to keep the implementation concise and leave the heavy computation outside of the hook functions.
The example below shows how to define the allocation and free function hooks:
#include "esp_heap_caps.h"
void esp_heap_trace_alloc_hook(void* ptr, size_t size, uint32_t caps)
{
...
}
void esp_heap_trace_free_hook(void* ptr)
{
...
}
void app_main()
{
...
}
Heap Corruption Detection
Heap corruption detection allows you to detect various types of heap memory errors:
Out-of-bound writes & buffer overflows
Writes to freed memory
Reads from freed or uninitialized memory
Assertions
The heap implementation (heap/multi_heap.c, etc.) includes numerous assertions that will fail if the heap memory is corrupted. To detect heap corruption most effectively, ensure that assertions are enabled in the project configuration via the CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL option.
If a heap integrity assertion fails, a line will be printed like
CORRUPT HEAP: |
The memory address printed is the address of the heap structure that has corrupt content.
It is also possible to manually check heap integrity by calling
heap_caps_check_integrity_all() or related functions. This function checks all of the requested heap memory for integrity and can be used even if assertions are disabled. If the integrity checks detects an error, it will print the error along with the address(es) of corrupt heap structures.
Memory Allocation Failed Hook
Users can use
heap_caps_register_failed_alloc_callback() to register a callback that is invoked every time an allocation operation fails.
Additionally, users can enable the CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS, which will automatically trigger a system abort if any allocation operation fails.
The example below shows how to register an allocation failure callback:
#include "esp_heap_caps.h"
void heap_caps_alloc_failed_hook(size_t requested_size, uint32_t caps, const char *function_name)
{
printf("%s was called but failed to allocate %d bytes with 0x%X capabilities. |
void *ptr = heap_caps_malloc(allocation_size, MALLOC_CAP_DEFAULT);
...
}
Finding Heap Corruption
Memory corruption can be one of the hardest classes of bugs to find and fix, as the source of the corruption could be completely unrelated to the symptoms of the corruption. Here are some tips:
A crash with a
CORRUPT HEAP:message usually includes a stack trace, but this stack trace is rarely useful. The crash is the symptom of memory corruption when the system realizes the heap is corrupt. But usually, the corruption happens elsewhere and earlier in time.
Increasing the heap memory debugging Configuration level to "Light impact" or "Comprehensive" gives you a more accurate message with the first corrupt memory address.
Adding regular calls to
heap_caps_check_integrity_all()or
heap_caps_check_integrity_addr()in your code helps you pin down the exact time that the corruption happened. You can move these checks around to "close in on" the section of code that corrupted the heap.
Based on the memory address that has been corrupted, you can use JTAG debugging to set a watchpoint on this address and have the CPU halt when it is written to.
If you do not have JTAG, but you do know roughly when the corruption happens, set a watchpoint in software just beforehand via
esp_cpu_set_watchpoint(). A fatal exception will occur when the watchpoint triggers. The following is an example of how to use the function -
esp_cpu_set_watchpoint(0, (void *)addr, 4, ESP_WATCHPOINT_STORE). Note that watchpoints are per-CPU and are set on the current running CPU only. So if you do not know which CPU is corrupting memory, call this function on both CPUs.
For buffer overflows, heap tracing in
HEAP_TRACE_ALLmode tells which callers are allocating which addresses from the heap. |
You can try to find the function that allocates memory with an address immediately before the corrupted address, since it is probably the function that overflows the buffer.
Calling
heap_caps_dump()or
heap_caps_dump_all()can give an indication of what heap blocks are surrounding the corrupted region and may have overflowed or underflowed, etc.
Configuration
Temporarily increasing the heap corruption detection level can give more detailed information about heap corruption errors.
In the project configuration menu, under
Component config, there is a menu
Heap memory debugging. The option CONFIG_HEAP_CORRUPTION_DETECTION can be set to one of the following three levels:
|
This mode does not have the limitation of the standalone mode, because traced data are sent to the host over JTAG connection using app_trace library. Later on, they can be analyzed using special tools.
Heap tracing can perform two functions:
Leak checking: find memory that is allocated and never freed.
Heap use analysis: show all functions that are allocating or freeing memory while the trace is running.
How to Diagnose Memory Leaks
If you suspect a memory leak, the first step is to figure out which part of the program is leaking memory. Use the
heap_caps_get_free_size() or related functions in heap information to track memory use over the life of the application. Try to narrow the leak down to a single function or sequence of functions where free memory always decreases and never recovers.
Standalone Mode
Once you have identified the code which you think is leaking:
Enable the CONFIG_HEAP_TRACING_DEST option.
Call the function
heap_trace_init_standalone()early in the program, to register a buffer that can be used to record the memory trace.
Call the function
heap_trace_start()to begin recording all mallocs or frees in the system. Call this immediately before the piece of code which you suspect is leaking memory.
Call the function
heap_trace_stop()to stop the trace once the suspect piece of code has finished executing.
Call the function
heap_trace_dump()to dump the results of the heap trace.
The following code snippet demonstrates how application code would typically initialize, start, and stop heap tracing:
#include "esp_heap_trace.h"
#define NUM_RECORDS 100
static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
...
|