基于freertos的嵌入式系统开发(六)FreeRTOS的内存管理方法4

34 篇文章 2 订阅
33 篇文章 2 订阅

基于freertos的嵌入式系统开发(六)FreeRTOS的内存管理方法4

简介

freertos的内存分配第四种方法和前文介绍的第二种方法接近,增加了一个内存合并算法,通过将将相邻的小的空闲内存块合并成一个大块,一定程度上避免了内存泄露,提高内存使用效率。内存管理方法与方法1和2一样,仍然使用一个大数组,定义为:

static uint8_t ucHeap[ configTOTAL_HEAP_SIZE];

所以,配置项configTOTAL_HEAP_SIZE对方法3是有效的。同样,也使用链表结构管理自由内存区域,链表结构体定义也和方法2一样,为:

typedef struct A_BLOCK_LINK
{
    struct A_BLOCK_LINK *pxNextFreeBlock;   /*指向链表下一个空闲块*/
    size_t xBlockSize;                      /*当前空闲块的大小*/
} BlockLink_t;

内存分配函数void * pvPortMalloc( size_t xWantedSize )

方法4的pvPortMallo函数相对比较复杂,先看流程图:

在这里插入图片描述从流程图可以看出方法4的内存管理策略和方法2不同,方法2中,内存管理策略是空闲块链表以内存块大小为存储顺序,而方法3是以内存块起始地址大小为存储顺序,小的在前,大的在后。这主要是为了后面的内存块合并算法便于处理,下面看代码:

void * pvPortMalloc( size_t xWantedSize )
{
    BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink;
    void * pvReturn = NULL;

	 vTaskSuspendAll();  //将所有的task挂起
    {
    /* If this is the first call to malloc then the heap will require
     * initialisation to setup the list of free blocks. */
    if( pxEnd == NULL ) //判断是否进入始化
    {
        prvHeapInit();
    }
    else
    {
        mtCOVERAGE_TEST_MARKER();
    }

    /* Check the requested block size is not so large that the top bit is
     * set.  The top bit of the block size member of the BlockLink_t structure
     * is used to determine who owns the block - the application or the
     * kernel, so it must be free. 
     链表结构BlockLink_t、字节对齐 处理,需求内存会变大
     */
    if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
    {
        /* The wanted size must be increased so it can contain a BlockLink_t
         * structure in addition to the requested amount of bytes. */
        if( ( xWantedSize > 0 ) &&
            ( ( xWantedSize + xHeapStructSize ) >  xWantedSize ) ) /* Overflow check */
        {
            xWantedSize += xHeapStructSize;

            /* Ensure that blocks are always aligned. */
            if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
            {
                /* Byte alignment required. Check for overflow. */
                if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) )
                        > xWantedSize )
                {
                    xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
                    configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );
                }
                else
                {
                    xWantedSize = 0;
                }
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        else
        {
            xWantedSize = 0;
        }

        if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
        {   //自由空间足够分配。
            /* Traverse the list from the start (lowest address) 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 the end marker was reached then a block of adequate size
             * was not found. */
            if( pxBlock != pxEnd )
            { //找到了,修改空闲块的信息,记录用户可用的内存首地址
                /* Return the memory space pointed to - jumping over the
                 * BlockLink_t structure at its start. */
                pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );

                /* 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 )
                {//如果减去已经分配出去的部分,剩余空闲块大于heapMINIMUM_BLOCK_SIZE ,则将该空闲块进行分割,把剩余的重新添加到free链表中
                    /* 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 );
                    configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );

                    /* 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 );
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }

                xFreeBytesRemaining -= pxBlock->xBlockSize;
                 //标识仍然未分配内存堆空间
                if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
                {
                    xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }

                /* The block is being returned - it is allocated and owned
                 * by the application and has no "next" block. 
                 * 将已经分配的内存块标识为"已分配*/
                pxBlock->xBlockSize |= xBlockAllocatedBit;
                pxBlock->pxNextFreeBlock = NULL;
                xNumberOfSuccessfulAllocations++;
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        else
        {
            mtCOVERAGE_TEST_MARKER();
        }
    }
    else
    {
        mtCOVERAGE_TEST_MARKER();
    }

    traceMALLOC( pvReturn, xWantedSize );
}
( void ) xTaskResumeAll(); //恢复所有task

#if ( configUSE_MALLOC_FAILED_HOOK == 1 )  //分配失败,钩子函数处理
    {
        if( pvReturn == NULL )
        {
            extern void vApplicationMallocFailedHook( void );
            vApplicationMallocFailedHook();
        }
        else
        {
            mtCOVERAGE_TEST_MARKER();
        }
    }
#endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */

configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 );
return pvReturn;
}

在上面函数中,用到了函数
prvInsertBlockIntoFreeList( pxNewBlockLink );该函数在插入新的free块的同时,会判断前后的空闲块能否合并,解决内存碎片化的问题,后面介绍。

内存释放函数void vPortFree( void * pv )

内存释放函数相对来说比较简单,主要分以下几步:

  1. 检测待释放内存是否为已分配的非空内存块

  2. 变更内存已分配标识

  3. 挂起所以任务

  4. 将待释放内存块加入free内存链表

  5. 恢复所有任务

    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.
    * 待释放的内存之前会有一个BlockLink_t结构 */
    puc -= xHeapStructSize;

     /* This casting is to keep the compiler from issuing warnings. */
     pxLink = ( void * ) puc;
    
     /* Check the block is actually allocated. 检查块已经分配标识 */
     configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
     configASSERT( pxLink->pxNextFreeBlock == NULL );
     if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
     {
         if( pxLink->pxNextFreeBlock == NULL )
         {
             /* The block is being returned to the heap - it is no longer allocated. */
             pxLink->xBlockSize &= ~xBlockAllocatedBit; //取消已经分配标识
    
             vTaskSuspendAll(); //挂起所以task
             {
                 /* Add this block to the list of free blocks. 将释放内存块加入free内存链表 */
                 xFreeBytesRemaining += pxLink->xBlockSize;
                 traceFREE( pv, pxLink->xBlockSize );
                 prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
                 xNumberOfSuccessfulFrees++;
             }
             ( void ) xTaskResumeAll(); //恢复所有任务
         }
         else
         {
             mtCOVERAGE_TEST_MARKER();
         }
     }
     else
     {
         mtCOVERAGE_TEST_MARKER();
     }
     }
    }
    

内存自由空间管理函数static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert )

freertos的内存管理方法4的最大的特点是在回收内存后,有了相邻空闲块的合并的算法,该算法是通过prvInsertBlockIntoFreeList函数实现,下面看具体代码:

static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */
{
 BlockLink_t * pxIterator;
  uint8_t * puc;

/* Iterate through the list until a block is found that has a higher address
 * than the block being inserted. 
遍历空闲内存块链表,找出内存块插入点。因为方法4的内存块是按照地址从低到高排列的,
只要找到最接近且小于pxBlockToInsert的free 块就可以了   */
for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
{
    /* Nothing to do here, just iterate to the right position. */
}

/* Do the block being inserted, and the block it is being inserted after
 * make a contiguous block of memory?
 * 检查是否和前面的内存可以合并,如果可以则合并
 *  */
puc = ( uint8_t * ) pxIterator;  //找到的新插入指针

if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
{
    pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
    pxBlockToInsert = pxIterator;
}
else
{
    mtCOVERAGE_TEST_MARKER();
}

/* Do the block being inserted, and the block it is being inserted before
 * make a contiguous block of memory? 检查是否可以与后面的内存合并*/
puc = ( uint8_t * ) pxBlockToInsert;

if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
{
    if( pxIterator->pxNextFreeBlock != pxEnd )
    {
        /* Form one big block from the two blocks. */
        pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
        pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
    }
    else
    {
        pxBlockToInsert->pxNextFreeBlock = pxEnd;
    }
}
else
{
    pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
}

/* If the block being inserted plugged a gab, so was merged with the block
 * before and the block after, then it's pxNextFreeBlock pointer will have
 * already been set, and should not be set here as that would make it point
 * to itself. 
 * 前后都不能合并,就作为一个独立free内存块*/
if( pxIterator != pxBlockToInsert )
{
    pxIterator->pxNextFreeBlock = pxBlockToInsert;
}
else
{
    mtCOVERAGE_TEST_MARKER();
}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cyjbj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值