FreeRTOS内存管理
DSP所移植的Freerots使用的内存管理是heap4.c,以下对该源文件进行分析。
一、宏&变量解析
- heapMINIMUM_BLOCK_SIZE
/* Block sizes must not get too small.
* 内存块大小不能太小,最小值是堆结构体大小的2倍,DSP中堆结构体大小为4个字节,因此最小的内存块大小为8字节 */
#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
- heapBITS_PER_BYTE
/* Assumes 8bit bytes!
* 每个字节包含8位
*/
#define heapBITS_PER_BYTE ( ( size_t ) 8 )
- ucHeap
/* Allocate the memory for the heap.
* 为堆空间分配内存
* configTOTAL_HEAP_SIZE 指的是用户分配给Freerots管理的空间大小,Freerots实际管理的内存是一个大数组
*/
static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
- BlockLink_t
/* Define the linked list structure. This is used to link free blocks in order
of their memory address.
定义链表结构。这用于按照内存地址的大小顺序的链接空闲内存块 */
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;
- xHeapStructSize
/* The size of the structure placed at the beginning of each allocated memory
block must by correctly byte aligned.
放置在每个分配的内存块开头的结构体的地址大小必须正确对齐字节
也就是说每个内存块都包含两部分,结构体+内存*/
static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
- xStart & *pxEnd
/* Create a couple of list links to mark the start and end of the list.
* 创建几个列表链接来标记列表的开始和结束
*/
static BlockLink_t xStart, *pxEnd = NULL;
- xFreeBytesRemaining & xMinimumEverFreeBytesRemaining
/* Keeps track of the number of free bytes remaining, but says nothing about
* fragmentation.
* 跟踪剩余的可用字节数,但对碎片一无所知
*/
static size_t xFreeBytesRemaining = 0U; /* 当前剩余的空闲内存空间大小 */
static size_t xMinimumEverFreeBytesRemaining = 0U; /* 历史最小剩余的空闲内存空间大小 */
- xBlockAllocatedBit
/* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
* member of an BlockLink_t structure is set then the block belongs to the
* application. When the bit is free the block is still part of the free heap
* space.
获取设置为size_t类型的最高位的值。当BlockLink_t结构的xBlockSize成员中的此位被置1时,表示该内存块属于应用程序。当该位空闲时,表示该块仍然是空闲堆空间的一部分。 */
static size_t xBlockAllocatedBit = 0;
二、API函数解析
1. prvHeapInit
1.1 函数源码
/* 内存初始化 */
static void prvHeapInit( void )
{
BlockLink_t *pxFirstFreeBlock;
uint8_t *pucAlignedHeap;
size_t uxAddress;
size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; /* 获取内存堆的总大小 */
/* Ensure the heap starts on a correctly aligned boundary.
* 确保堆在正确对齐的边界上开始 */
uxAddress = ( size_t ) ucHeap; /* 获取内存堆的起始地址 */
//4字节对齐
if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
{
uxAddress += ( portBYTE_ALIGNMENT - 1 );
uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); /* 字节对齐后的起始地址 */
xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; /* 字节对齐后剩余的内存堆大小 */
}
pucAlignedHeap = ( uint8_t * ) uxAddress;
/* xStart is used to hold a pointer to the first item in the list of

最低0.47元/天 解锁文章
173

被折叠的 条评论
为什么被折叠?



