目錄
在《FreeRTOS --(2)內存管理 heap1》知道 heap 1 的內存管理其實只是簡單的實現了內存對齊的分配策略,heap 2 的實現策略相比 heap 1 稍微複雜一點,不僅僅是提供了分配內存的接口,同時也提供了釋放內存的接口;
但是 heap 2 的內存分配策略中,並沒有提供空閒內存的合併策略,對內存碎片沒有處理;換句話來說,如果有多次的,大小各異的內存申請和釋放的場景下,很可能導致很多內存碎片;
1、內存大小
和 heap 1 一樣,用於內存管理的內存大小來自於一個大數組,數組的下標就是整個需要被管理的內存的大小,這個是和具體芯片所支持的 RAM 大小相關:
configTOTAL_HEAP_SIZE
被管理的內存定義爲:
static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
ucHeap 就是管理的對象;
2、對齊
有的處理器是對內存對齊有要求的,比如 ARM-CM3 等,AAPCS規則要求堆棧保持8字節對齊。給任務分配棧時需要保證棧是8字節對齊的。所以這裏 FreeRTOS 就需要涉及到對齊操作;針對 ARM-CM3 這類處理器來說,在portmacro.h 文件中,定義了對齊的字節數:
/* Hardware specifics. */
#define portBYTE_ALIGNMENT 8
而在 portable.h 中,定義了對應的 Mask(8字節對齊,那麼都要是 8 的倍數,也就是二進制的 4'b1000,所以 MASK 是 4'b0111 也就是 0x07):
#if portBYTE_ALIGNMENT == 8
#define portBYTE_ALIGNMENT_MASK ( 0x0007 )
#endif
和 heap 1 一樣,在處理對齊的時候,由於可能 ucHeap 初始的地址就沒對齊,所以這裏真正可以對齊分配的內存的 SIZE 就要做一些調整和妥協,由於是 8 字節對齊,所以最多妥協的大小就是 8 字節,也就是真正被管理的內存大小隻有 configADJUSTED_HEAP_SIZE,這裏可能造成幾個字節的浪費(浪費多少,取決於ucHeap 初始地址 ),不過爲了對齊,也就忽略了;
/* A few bytes might be lost to byte aligning the heap start address. */
#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
3、內存塊
與 heap 1 不同,heap 2 可以支持分配和釋放,那麼管理內存的手段勢必比 heap 1 複雜一些,heap 2 對內存進行分塊管理,將每塊內存通過一個表徵該內存塊的的數據結構表示,以單向鏈表串在一起;
3.1、數據結構
表達一個內存塊的數據結構是 BlockLink_t,它的定義是:
/* Define the linked list structure. This is used to link free blocks in order
of their size. */
typedef struct A_BLOCK_LINK
{
struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */
size_t xBlockSize; /*<< The size of the free block. */
} BlockLink_t;
pxNextFreeBlock 指向下一個內存塊的 BlockLink_t 結構;
xBlockSize 代表本內存塊的大小;
3.2、數據結構對齊
當然內存塊也需要對齊:
static const uint16_t heapSTRUCT_SIZE = ( ( sizeof ( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK );
heapSTRUCT_SIZE 代表了一個內存塊對齊後大小(爲了對齊,先加上了最大可能消耗的字節數,這裏可能有一點點直接損失)
3.3、內存塊 Marker
FreeRTOS 爲內存管理,定義了兩個 BlockLink_t 結構體,xStart 和 xEnd:
/* Create a couple of list links to mark the start and end of the list. */
static BlockLink_t xStart, xEnd;
xStart 和 xEnd 僅僅作爲 mark,標記內存塊的起始和結束;
3.4、可用內存
在 heap2 中定義了 xFreeBytesRemaining 來代表當前可用於分配的內存,每當內存被分配出去,這個值會減,內存被free 後,該值增加:
/* Keeps track of the number of free bytes remaining, but says nothing about
fragmentation. */
static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
4、分配內存
和 heap 1 一樣,內存分配使用 pvPortMalloc 函數,傳入的是希望拿到的內存,返回值拿到的內存起始地址,如果分配失敗返回 NULL;
/*-----------------------------------------------------------*/
void *pvPortMalloc( size_t xWantedSize )
{
BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
static BaseType_t xHeapHasBeenInitialised = pdFALSE;
void *pvReturn = NULL;
vTaskSuspendAll();
{
/* If this is the first call to malloc then the heap will require
initialisation to setup the list of free blocks. */
if( xHeapHasBeenInitialised == pdFALSE )
{
prvHeapInit();
xHeapHasBeenInitialised = pdTRUE;
}
/* The wanted size is increased so it can contain a BlockLink_t
structure in addition to the requested amount of bytes. */
if( xWantedSize > 0 )
{
xWantedSize += heapSTRUCT_SIZE;
/* Ensure that blocks are always aligned to the required number of bytes. */
if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0 )
{
/* Byte alignment required. */
xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
}
}
if( ( xWantedSize > 0 ) && ( xWantedSize < configADJUSTED_HEAP_SIZE ) )
{
/* Blocks are stored in byte order - traverse the list from the start
(smallest) block until one of adequate size is found. */
pxPreviousBlock = &xStart;
pxBlock = xStart.pxNextFreeBlock;
while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
{
pxPreviousBlock = pxBlock;
pxBlock = pxBlock->pxNextFreeBlock;
}
/* If we found the end marker then a block of adequate size was not found. */
if( pxBlock != &xEnd )
{
/* Return the memory space - jumping over the BlockLink_t structure
at its start. */
pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );
/* This block is being returned for use so must be taken out of the
list of free blocks. */
pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
/* If the block is larger than required it can be split into two. */
if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
{
/* This block is to be split into two. Create a new block
following the number of bytes requested. The void cast is
used to prevent byte alignment warnings from the compiler. */
pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
/* Calculate the sizes of two blocks split from the single
block. */
pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
pxBlock->xBlockSize = xWantedSize;
/* Insert the new block into the list of free blocks. */
prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
}
xFreeBytesRemaining -= pxBlock->xBlockSize;
}
}
traceMALLOC( pvReturn, xWantedSize );
}
( void ) xTaskResumeAll();
#if( configUSE_MALLOC_FAILED_HOOK == 1 )
{
if( pvReturn == NULL )
{
extern void vApplicationMallocFailedHook( void );
vApplicationMallocFailedHook();
}
}
#endif
return pvReturn;
}
/*-----------------------------------------------------------*/
首先調用 vTaskSuspendAll(); 來掛起所有任務,不允許進程調度;
接着調用 prvHeapInit(); 來初始化相關的內存管理的鏈表結構:
static void prvHeapInit( void )
{
BlockLink_t *pxFirstFreeBlock;
uint8_t *pucAlignedHeap;
/* Ensure the heap starts on a correctly aligned boundary. */
pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
/* xStart is used to hold a pointer to the first item in the list of free
blocks. The void cast is used to prevent compiler warnings. */
xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
xStart.xBlockSize = ( size_t ) 0;
/* xEnd is used to mark the end of the list of free blocks. */
xEnd.xBlockSize = configADJUSTED_HEAP_SIZE;
xEnd.pxNextFreeBlock = NULL;
/* To start with there is a single free block that is sized to take up the
entire heap space. */
pxFirstFreeBlock = ( void * ) pucAlignedHeap;
pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE;
pxFirstFreeBlock->pxNextFreeBlock = &xEnd;
}
在初始化內存相關的結構的時候,首先將 ucHeap 的地址進行對齊操作,得到可以對齊後用於真實的內存管理的起始地址爲:
pucAlignedHeap
然後初始化 xStart 和 xEnd,這兩個 marker,然後將整個可用的內存視爲一塊,可用的內存的開始地方,放置了一個 BlockLink_t 結構體並初始化它的 xBlockSize 爲之前調整過的 configADJUSTED_HEAP_SIZE;
我們在回到 pvPortMalloc 的地方,繼續分析;
prvHeapInit() 初始化完成後,便可用分配內存了;分配內存的時候,需要對每一個內存塊分配一個標誌它的描述符,也就是 BlockLink_t 結構體,所以如果要分配 xWantedSize,那麼就要分配 :
xWantedSize += heapSTRUCT_SIZE;
然後,對 xWantedSize 進行字節對齊操作;
接下來便進行鏈表搜尋,找到 Size 合適的地方,將其分配出來;
值得注意的是,內存塊鏈表是有排序的,開始是 xStart 後面跟的內存塊,內存塊由小到大,最後是 xEnd;
/*
* Insert a block into the list of free blocks - which is ordered by size of
* the block. Small blocks at the start of the list and large blocks at the end
* of the list.
*/
#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \
{ \
BlockLink_t *pxIterator; \
size_t xBlockSize; \
\
xBlockSize = pxBlockToInsert->xBlockSize; \
\
/* Iterate through the list until a block is found that has a larger size */ \
/* than the block we are inserting. */ \
for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \
{ \
/* There is nothing to do here - just iterate to the correct position. */ \
} \
\
/* Update the list to include the block being inserted in the correct */ \
/* position. */ \
pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \
pxIterator->pxNextFreeBlock = pxBlockToInsert; \
}
繼續看代碼;
如果 pxBlock 不是 xEnd 的話,那麼說明找到有 Size 大於期望分配的 Size 的 Block 了;
那麼就將返回值:
/* Return the memory space - jumping over the BlockLink_t structure at its start. */
pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );
這裏,分配內存,能夠實際給調用這個 API 接口使用的內存要從起始的 Block 地址加上 heapSTRUCT_SIZE 開始算,因爲 heapSTRUCT_SIZE 已經用來表示這個 Block 的信息了;
然後判斷剩餘的 SIZE 是否大於最小的可用的空間分配的閾值 heapMINIMUM_BLOCK_SIZE :
#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) )
如果剩餘的內存空間還足夠那麼:
/* If the block is larger than required it can be split into two. */
if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
{
/* This block is to be split into two. Create a new block
following the number of bytes requested. The void cast is
used to prevent byte alignment warnings from the compiler. */
pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
/* Calculate the sizes of two blocks split from the single block. */
pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
pxBlock->xBlockSize = xWantedSize;
/* Insert the new block into the list of free blocks. */
prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
}
使用新的 pxNewBlockLink 結構表示摘除 pxBlock 內存塊後的下一個內存塊,並將其初始化,然後按照排序(從小到大的順序)插入到以 xStart 開始的地方;
所以,被初始化後的內存
分配一次的結果是:
5、釋放內存
heap2 支持釋放內存:
void vPortFree( void *pv )
{
uint8_t *puc = ( uint8_t * ) pv;
BlockLink_t *pxLink;
if( pv != NULL )
{
/* The memory being freed will have an BlockLink_t structure immediately
before it. */
puc -= heapSTRUCT_SIZE;
/* This unexpected casting is to keep some compilers from issuing
byte alignment warnings. */
pxLink = ( void * ) puc;
vTaskSuspendAll();
{
/* Add this block to the list of free blocks. */
prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
xFreeBytesRemaining += pxLink->xBlockSize;
traceFREE( pv, pxLink->xBlockSize );
}
( void ) xTaskResumeAll();
}
}
來自用戶釋放的指針 pv 是實際的數據指針,代表這個內存的結構體在他前面 heapSTRUCT_SIZE 的位置,所以該 pv 的 BlockLink_t 結構體指針 pxLink = ( void * )(puc - heapSTRUCT_SIZE);
調用 prvInsertBlockIntoFreeList 將其插入到鏈表中;並且更新當前剩餘的內存量;
釋放後的內存如下所示: