Rtthread 堆内存管理
#define HEAP_MAGIC 0x1ea0
struct heap_mem
{/* magic and used flag */rt_uint16_t magic; //魔数,固定值rt_uint16_t used; //使用标记,1为该内存已经被使用rt_size_t next, prev; //双向链表偏移
};
#define MIN_SIZE 12 //一次申请的存size不能低于MIN_SIZE
#define MIN_SIZE_ALIGNED RT_ALIGN(MIN_SIZE, RT_ALIGN_SIZE) //最小值4对齐,依然为12
#define SIZEOF_STRUCT_MEM RT_ALIGN(sizeof(struct heap_mem), RT_ALIGN_SIZE)//mem数据结构对齐后的大小(12)/** pointer to the heap: for alignment, heap_ptr is now a pointer instead of an array */
static rt_uint8_t *heap_ptr; //4对齐的堆的首地址
/** the last entry, always unused! */
static struct heap_mem *heap_end; //堆的结尾
static struct heap_mem *lfree; /* pointer to the lowest free block 当前堆空闲内存块指针*/static struct rt_semaphore heap_sem; //条件变量
static rt_size_t mem_size_aligned; //堆总内存大小(对齐后)#ifdef RT_MEM_STATS
static rt_size_t used_mem, max_mem; //debug信息
#endif
堆内存初始化
/*** @ingroup SystemInit** This function will initialize system heap memory.** @param begin_addr the beginning address of system heap memory.* @param end_addr the end address of system heap memory.*/
void rt_system_heap_init(void *begin_addr, void *end_addr)
{struct heap_mem *mem;rt_ubase_t begin_align = RT_ALIGN((rt_ubase_t)begin_addr, RT_ALIGN_SIZE);//向上4字节对齐rt_ubase_t end_align = RT_ALIGN_DOWN((rt_ubase_t)end_addr, RT_ALIGN_SIZE);//向下4字节对齐RT_DEBUG_NOT_IN_INTERRUPT;//不允许在中断处理函数中调用/* alignment addr 内存总量至少为2个SIZEOF_STRUCT_MEM大小(12*2=24 byte)*/if ((end_align > (2 * SIZEOF_STRUCT_MEM)) &&((end_align - 2 * SIZEOF_STRUCT_MEM) >= begin_align)){/* calculate the aligned memory size 计算对齐后总的mem_size*/mem_size_aligned = end_align - begin_align - 2 * SIZEOF_STRUCT_MEM;}else{rt_kprintf("mem init, error begin address 0x%x, and end address 0x%x\n",(rt_ubase_t)begin_addr, (rt_ubase_t)end_addr);return;}/* point to begin address of heap */heap_ptr = (rt_uint8_t *)begin_align;//保存堆内存首地址RT_DEBUG_LOG(RT_DEBUG_MEM, ("mem init, heap begin address 0x%x, size %d\n",(rt_ubase_t)heap_ptr, mem_size_aligned));/* initialize the start of the heap */mem = (struct heap_mem *)heap_ptr;mem->magic = HEAP_MAGIC;mem->next = mem_size_aligned + SIZEOF_STRUCT_MEM;mem->prev = 0;mem->used = 0;/* initialize the end of the heap */heap_end = (struct heap_mem *)&heap_ptr[mem->next];heap_end->magic = HEAP_MAGIC;heap_end->used = 1;heap_end->next = mem_size_aligned + SIZEOF_STRUCT_MEM;heap_end->prev = mem_size_aligned + SIZEOF_STRUCT_MEM;//互斥信号量初始化rt_sem_init(&heap_sem, "heap", 1, RT_IPC_FLAG_FIFO);/* initialize the lowest-free pointer to the start of the heap */lfree = (struct heap_mem *)heap_ptr;
}
rt_malloc实现
/*** @addtogroup MM*//**@{*//*** Allocate a block of memory with a minimum of 'size' bytes.** @param size is the minimum size of the requested block in bytes.** @return pointer to allocated memory or NULL if no free memory was found.*/
void *rt_malloc(rt_size_t size)
{rt_size_t ptr, ptr2;struct heap_mem *mem, *mem2;if (size == 0)return RT_NULL;//禁止中断处理函数调用rt_mallocRT_DEBUG_NOT_IN_INTERRUPT;if (size != RT_ALIGN(size, RT_ALIGN_SIZE))RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d, but align to %d\n",size, RT_ALIGN(size, RT_ALIGN_SIZE)));elseRT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d\n", size));/* alignment size */size = RT_ALIGN(size, RT_ALIGN_SIZE);if (size > mem_size_aligned){RT_DEBUG_LOG(RT_DEBUG_MEM, ("no memory\n"));return RT_NULL;}/* every data block must be at least MIN_SIZE_ALIGNED long */if (size < MIN_SIZE_ALIGNED)size = MIN_SIZE_ALIGNED;/* take memory semaphore */rt_sem_take(&heap_sem, RT_WAITING_FOREVER);//遍历堆内存,寻找满足size大小要求的//lfree - heap_ptr获取到第一块空闲内存相对于堆首地址的偏移//ptr + size < mem_size_aligned等价于://ptr + (size + SIZEOF_STRUCT_MEM) < mem_size_aligned + SIZEOF_STRUCT_MEMfor (ptr = (rt_uint8_t *)lfree - heap_ptr;ptr < mem_size_aligned - size; ptr = ((struct heap_mem *)&heap_ptr[ptr])->next){//取出空闲内存的信息块mem = (struct heap_mem *)&heap_ptr[ptr];//内存未被使用,并且该内存块的大小完全满足size的需求if ((!mem->used) && (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size){/* mem is not used and at least perfect fit is possible:* mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem *///该内存块空间大于size + (SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED),那么需要对该内存块分割//也就是说,该内存块在分出size大小的空间后,至少还有SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED//大小的内存空间,就需要对该内存块进行分割。if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >=(size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)){/* (in addition to the above, we test if another struct heap_mem (SIZEOF_STRUCT_MEM) containing* at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')* -> split large block, create empty remainder,* remainder must be large enough to contain MIN_SIZE_ALIGNED data: if* mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,* struct heap_mem would fit in but no data between mem2 and mem2->next* @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty* region that couldn't hold data, but when mem->next gets freed,* the 2 regions would be combined, resulting in more free memory*///分割准备,计算要分割的地址ptr2 = ptr + SIZEOF_STRUCT_MEM + size;/* create mem2 struct */mem2 = (struct heap_mem *)&heap_ptr[ptr2];mem2->magic = HEAP_MAGIC;mem2->used = 0;mem2->next = mem->next;//插入链表mem2->prev = ptr;/* and insert it between mem and mem->next */mem->next = ptr2;mem->used = 1;//标记mem内存已经使用//切割的内存的下一个内存块不是最后一个内存块,就将下一个内存块的prev指向//当前切割出来的内存块if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM){((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;}
#ifdef RT_MEM_STATSused_mem += (size + SIZEOF_STRUCT_MEM);if (max_mem < used_mem)max_mem = used_mem;
#endif}else{/* (a mem2 struct does no fit into the user data space of mem and mem->next will always* be used at this point: if not we have 2 unused structs in a row, plug_holes should have* take care of this).* -> near fit or excact fit: do not split, no mem2 creation* also can't move mem->next directly behind mem, since mem->next* will always be used at this point!*///如果该内存块不满足分割条件,则直接返回该内存mem->used = 1;
#ifdef RT_MEM_STATSused_mem += mem->next - ((rt_uint8_t *)mem - heap_ptr);if (max_mem < used_mem)max_mem = used_mem;
#endif}/* set memory block magic */mem->magic = HEAP_MAGIC;if (mem == lfree)//只有在使用lfree指向的内存块后才更新lfree{/* Find next free block after mem and update lowest free pointer */while (lfree->used && lfree != heap_end)lfree = (struct heap_mem *)&heap_ptr[lfree->next];RT_ASSERT(((lfree == heap_end) || (!lfree->used)));}rt_sem_release(&heap_sem);//释放互斥信号量RT_ASSERT((rt_ubase_t)mem + SIZEOF_STRUCT_MEM + size <= (rt_ubase_t)heap_end);RT_ASSERT((rt_ubase_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM) % RT_ALIGN_SIZE == 0);RT_ASSERT((((rt_ubase_t)mem) & (RT_ALIGN_SIZE - 1)) == 0);RT_DEBUG_LOG(RT_DEBUG_MEM,("allocate memory at 0x%x, size: %d\n",(rt_ubase_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM),(rt_ubase_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));RT_OBJECT_HOOK_CALL(rt_malloc_hook,(((void *)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM)), size));/* return the memory data except mem struct */return (rt_uint8_t *)mem + SIZEOF_STRUCT_MEM;}}rt_sem_release(&heap_sem);return RT_NULL;
}
总结一下rt_malloc的流程:
1.检查申请内存size大小是否向上4对齐,没有的话先做对齐。
2.检查对齐后的申请的内存大小是否超过堆总内存大小。
3.检查对齐后申请的内存是否小于最小size。
4.计算出空闲地址相对于首地址的偏移量,并开始循环查找满足size内存申请的内存块。
5.找到尚未使用,并且满足size大小条件的内存块。
6.判断该内存块是否大于size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED,大于则对其进行分割
否则直接将整块内存分给申请者。
rt_realloc
/*** This function will change the previously allocated memory block.** @param rmem pointer to memory allocated by rt_malloc* @param newsize the required new size** @return the changed memory block address*/
void *rt_realloc(void *rmem, rt_size_t newsize)
{rt_size_t size;rt_size_t ptr, ptr2;struct heap_mem *mem, *mem2;void *nmem;RT_DEBUG_NOT_IN_INTERRUPT;/* alignment size */newsize = RT_ALIGN(newsize, RT_ALIGN_SIZE);if (newsize > mem_size_aligned){RT_DEBUG_LOG(RT_DEBUG_MEM, ("realloc: out of memory\n"));return RT_NULL;}else if (newsize == 0){rt_free(rmem);return RT_NULL;}/* allocate a new memory block */if (rmem == RT_NULL)return rt_malloc(newsize);rt_sem_take(&heap_sem, RT_WAITING_FOREVER);if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr ||(rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end){/* illegal memory */rt_sem_release(&heap_sem);return rmem;}//获取内存的头信息mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);//获取当前内存块相对于堆首地址的偏移ptr = (rt_uint8_t *)mem - heap_ptr;size = mem->next - ptr - SIZEOF_STRUCT_MEM;//计算当前内存块拥有的内存sizeif (size == newsize){/* the size is the same as */rt_sem_release(&heap_sem);return rmem;}//如果size满足newsize的大小需求,则进行分割if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE < size){/* split memory block */
#ifdef RT_MEM_STATSused_mem -= (size - newsize);
#endifptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;mem2 = (struct heap_mem *)&heap_ptr[ptr2];mem2->magic = HEAP_MAGIC;mem2->used = 0;mem2->next = mem->next;mem2->prev = ptr;
#ifdef RT_USING_MEMTRACErt_mem_setname(mem2, " ");
#endifmem->next = ptr2;if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM){((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;}if (mem2 < lfree){/* the splited struct is now the lowest */lfree = mem2;}plug_holes(mem2);rt_sem_release(&heap_sem);return rmem;}rt_sem_release(&heap_sem);/* expand memory *///当前内存块不满足new size,将重新申请内存nmem = rt_malloc(newsize);if (nmem != RT_NULL) /* check memory */{rt_memcpy(nmem, rmem, size < newsize ? size : newsize);rt_free(rmem);}return nmem;
}
rt_free
/*** This function will release the previously allocated memory block by* rt_malloc. The released memory block is taken back to system heap.** @param rmem the address of memory which will be released*/
void rt_free(void *rmem)
{struct heap_mem *mem;if (rmem == RT_NULL)return;//禁止在中断处理函数中调用该函数RT_DEBUG_NOT_IN_INTERRUPT;RT_ASSERT((((rt_ubase_t)rmem) & (RT_ALIGN_SIZE - 1)) == 0);RT_ASSERT((rt_uint8_t *)rmem >= (rt_uint8_t *)heap_ptr &&(rt_uint8_t *)rmem < (rt_uint8_t *)heap_end);RT_OBJECT_HOOK_CALL(rt_free_hook, (rmem));if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr ||(rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end){RT_DEBUG_LOG(RT_DEBUG_MEM, ("illegal memory\n"));return;}/* Get the corresponding struct heap_mem ... *///获取要free的内存的头信息mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);RT_DEBUG_LOG(RT_DEBUG_MEM,("release memory 0x%x, size: %d\n",(rt_ubase_t)rmem,(rt_ubase_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));/* protect the heap from concurrent access */rt_sem_take(&heap_sem, RT_WAITING_FOREVER);//check 状态/* ... which has to be in a used state ... */if (!mem->used || mem->magic != HEAP_MAGIC){rt_kprintf("to free a bad data block:\n");rt_kprintf("mem: 0x%08x, used flag: %d, magic code: 0x%04x\n", mem, mem->used, mem->magic);}RT_ASSERT(mem->used);RT_ASSERT(mem->magic == HEAP_MAGIC);/* ... and is now unused. */mem->used = 0;mem->magic = HEAP_MAGIC;//当前释放的内存小于空闲内存的地址,就更新空闲内存的地址if (mem < lfree){/* the newly freed struct is now the lowest */lfree = mem;}#ifdef RT_MEM_STATSused_mem -= (mem->next - ((rt_uint8_t *)mem - heap_ptr));
#endif/* finally, see if prev or next are free also *///合并空闲内存plug_holes(mem);rt_sem_release(&heap_sem);
}static void plug_holes(struct heap_mem *mem)
{struct heap_mem *nmem;struct heap_mem *pmem;RT_ASSERT((rt_uint8_t *)mem >= heap_ptr);RT_ASSERT((rt_uint8_t *)mem < (rt_uint8_t *)heap_end);RT_ASSERT(mem->used == 0);/* plug hole forward *///获取Next内存块nmem = (struct heap_mem *)&heap_ptr[mem->next];if (mem != nmem &&nmem->used == 0 &&(rt_uint8_t *)nmem != (rt_uint8_t *)heap_end){/* if mem->next is unused and not end of heap_ptr,* combine mem and mem->next*/if (lfree == nmem){lfree = mem;}//删除NEXT链表节点mem->next = nmem->next;((struct heap_mem *)&heap_ptr[nmem->next])->prev = (rt_uint8_t *)mem - heap_ptr;}/* plug hole backward */pmem = (struct heap_mem *)&heap_ptr[mem->prev];if (pmem != mem && pmem->used == 0){/* if mem->prev is unused, combine mem and mem->prev */if (lfree == mem){lfree = pmem;}pmem->next = mem->next;((struct heap_mem *)&heap_ptr[mem->next])->prev = (rt_uint8_t *)pmem - heap_ptr;}
}