FreeRTOS代码剖析之2:内存管理Heap

在freertos8.0.1这个版本中,一共有四个内存堆模型。这一次讲的就是第二个模型heap_2.c。从一开始就可以看到注释中对heap_2的模型解释:这是对pvportmalloc()和vportfree()的简单实现,除了可以分配内存之外,还可以对已分配的内存进行回收,但相邻空闲块不会进行合并,因此会造成一定的内存碎片。(a sample implementation of pvportmalloc() and vportfree() that permits allocated blocks to be freed, but does not combine adjacent free blocks into a single larger block (and so will fragment memory).)
在heap_2中,由于开始支持对内存进行回收,因此freertos以空闲块对内存堆进行管理,并且使用了最佳适配算法(best fit algorithm)去进行内存的分配。
首先,还是由内存中开辟一个静态数组ucheap[ configtotal_heap_size ]作为freertos的内存堆。同样也会因为对齐的原因freertos对内存堆的可用空间进行了调整,并定义了常量configadjusted_heap_size。(具体已在上一篇《内存管理heap_1.c》中介绍)
接下来可以留意heap_2.c中最重要的结构struct a_block_link。由于freertos用空闲块对内存堆进行管理,于是用这一个结构来形成一条空闲块链表对空闲块进行组织和管理。
/* 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; /*pxnextfreeblock = &xend;
经过上面的初始化流程后,整个链表如下图所示。注意,xstart和xend是存在于静态存储区中,并不在freertos申请的内存堆数组中,但初始时第一个节点却在内存堆数组中。我用的编译器是keil mdk 5.11,并且将freertos移植到stm32上,因此一个a_block_link的大小为8个字节。
整个初始化的流程就完成了。接下来看看pvportmalloc()分配内存的流程。如heap_1一样,在真正开始分配内存时,用vtasksuspendall()挂起所有任务,防止分配内存的过程被中断,确保操作的原子性。紧接着,如果是第一次调用pvportmalloc(),则调用prvheapinit()对内存堆和空闲块链表进行初始化。由于在heap_2中将内存堆用空闲块处理,因此用户每申请一次内存,freertos都会在申请的空间前加上空闲块头部blocklink_t,用于记录分配出去的空间的大小。因此,真正要分配的内存空间大小就等于用户申请的内存空间大小加上空闲块头部的大小。加上头部之后,还要对整个大小进行对齐。因此,在真正分配空间之前,freertos都对用户申请的空间大小进行了调整。如下面的代码所示。
/* 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 ) );
}
}
在这一段代码里,有一个地方要注意的就是这里用到的空闲块头部并不是直接sizeof(blocklink_t),而是heapstruct_size,这个常量也定义在heap_2.c中,这是对空闲块头部的大小再进行了一次大小对齐。
接下来做了一个分配判断。xwantedsize0,还看得我很迷糊的。本来xwantedsize就是unsigned int,是大于等于0的,一下子没有留意到等于0是什么情况。等于0,就是加上空闲块头之后的大小变为0了?这是神马情况?!看来这个判断条件很另人费解啊。过了分配判断之后,接下来就是best fit algorithm的实现了。在这里,空闲块的大小是按从小到大的顺序排列的。因此,遍历链表,找到第一块比申请空间大的空闲块即为最合适的空闲块。然后返回这个空闲块头后的首地址。注意,一定是空闲块头后的首地址哦,要是直接将空闲块的首地址返回的话,那用户就会将空闲块头修改了。另一个要注意的地方是,要是分配出去的空闲块的剩余空间要是比两倍的空闲块头还要大,则将分配出去的这个空闲块分割剩余的空间出来,重新放到空闲块链表中。例如,初始化后只有一个空闲块,这个空闲块大小为17kb。经过调整后的用户申请空间大小为1kb,则freertos就从这个空闲块靠近块首的地方分割出1kb出来分配出去,剩余的16kb则重新放回空闲块链表里。以便下一次继续分配。这一个切割空闲块的代码如下。
/* 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 ) );
}
在上面的一段代码里,有一个值得注意的宏prvinsertblockintofreelist()。这个宏的作用是将空闲块重新添加到空闲块链表中。注意,并不能将分割出来的空闲块放到原空闲块的位置中,因为链表中的空闲块是按从小到大的顺序排列的,这个宏的作用就是将新空闲块插入到合适的链表位置中。这是一个简单的链表操作,非常简单,也不必详细说明了。这个宏的具体代码如下。
/*
* 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 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;
}
完成以上操作后,修改剩余空闲块空闲大小xfreebytesremaining,整个分配内存的工作就差不多结束了。接下来freertos调用一个调试信息用的宏tracemalloc(),恢复所有挂起的任务,再根据宏配置调用勾子函数vapplicationmallocfailedhook(),最后返回分配出来的空间地址pvreturn(成功时为空间地址,失败时为null)。这样整个pvportmalloc()就结束了。
接下来要继续剖析的是heap_1中所没有具体实现的vportfree()。这一个函数非常地短,首先判断要释放的内存是否为空。要是不为空,则寻找这个内存空间的空闲块头,然后挂起所有任务,按照空闲块头的信息把它重新插入到空闲块链表中,最后调用调试信息宏,恢复挂起的任务就结束了。其代码如下。
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 );
}
xtaskresumeall();
}
}
不过在仔细想想这一段代码,我觉得这一段代码是有点问题,就是判断要释放内存的有效性。这里它只是很简单地判断传进来的指针是否为空而已,但是要是这个指针不为空,但却在freertos申请的内存堆数组之外呢?这样的话就会修改到内存的其它部分了,非常危险的操作。因此我觉得,如果要修改的话,应该还要加上判断传入进来的地址是否在有效的地址范围内,如下面代码所示。至于我这一个想法是否有问题,希望大家能讨论一下,这样我也可以从大家的讨论中学习学习。
if( pv!=null)
{
if( pv >= &ucheap[ pucalignedheap ] && pv <= &ucheap[ pucalignedheap + configadjusted_heap_size ] )
{
/* the operation of adding the block to the list of free blocks */
}
}
到这里,heap_2的重点部分就已经剖析完了。剩下的xportgetfreeheapsize()只是返回剩余堆大小而已,vportinitialiseblocks()实际上啥也没实现,根据注释它的作用只是防止链接器放警告而已。
总结:heap_2比heap_1的代码更长,要剖析的知识点更多。一开始看的时候还觉得有点怕怕,怕剖着剖着就不知道怎么剖了。在剖的过程中还有很多知识点要翻翻课本,例如在看到最佳适配算法(best fit algorithm)时,要翻翻andrew s. tanenbaum写的《modern operating systems》。经过这样的实例剖析之后,我发觉对以前学的东西有了更深刻的理解。以前上课只是说说有这个算法而已,具体怎么实现却完全没有讲。直到现在,我才发觉原来这个算法的真实应用,真是另我大开眼界。以后学习的路还很长,剖析完freertos还有很长的一段距离。要继续加油加油!

微软在丹麦建立用于量子计算的材料实验室
ups电源能用多少个小时
华星光电实现满产高效运行 销售收入同比增长3.95倍
四方面因素,5G 时代异网漫游迎来最好时机
什么是视频采集卡以及怎样选择购买
FreeRTOS代码剖析之2:内存管理Heap
日经:九大芯片厂商库存创历史新高 供过于求风险持续增加
苹果降速门再起冲突 iPad也疑似性能降低
基于OPCUA与西门子PLC通信技术解析
小型UPS电源为我们提供了哪些便捷之处
三星拒绝向华为提供Exynos芯片,海思将包机运送芯片
什么是嵌入式编程
华大电子共三颗安全芯片产品通过身份认证获得ID²INSIDE商标授权
高智能农业土壤肥料养分分析系统的详细参数介绍及应用领域
Verizon在另外四个城市的部分地区点亮了其5G网络
微电子师资“芯火课堂”正式开班
废气净化处理塔 活性炭处理塔 酸性处理塔 碱性处理塔 昆山晟华
韩国成为全球首个5G商用国家,在商用化进程中占据先机
阿里云发布了新一代云计算操作系统“飞天2.0”
贴片电阻与贴片电感有什么区别