【 uC/OS II 】uC/OS II 源代码阅读(os_mem.c)内存管理

前言

这个文件是关于内存管理的,非常简单,主要是二级指针与一级指针之间的转换。至于核心结构体如下:

typedef struct os_mem {                     /* MEMORY CONTROL BLOCK                                    */
    void   *OSMemAddr;                      /* Pointer to beginning of memory partition                */
    void   *OSMemFreeList;                  /* Pointer to list of free memory blocks                   */
    INT32U  OSMemBlkSize;                   /* Size (in bytes) of each block of memory                 */
    INT32U  OSMemNBlks;                     /* Total number of blocks in this partition                */
    INT32U  OSMemNFree;                     /* Number of memory blocks remaining in this partition     */
#if OS_MEM_NAME_EN > 0u
    INT8U  *OSMemName;                      /* Memory partition name                                   */
#endif
} OS_MEM;
/*内存管理(已看)
*********************************************************************************************************
*                                                uC/OS-II
*                                          The Real-Time Kernel
*                                            MEMORY MANAGEMENT
*
*                           (c) Copyright 1992-2017; Micrium, Inc.; Weston; FL
*                                           All Rights Reserved
*
* File    : OS_MEM.C
* By      : Jean J. Labrosse
* Version : V2.92.13
*
* LICENSING TERMS:
* ---------------
*   uC/OS-II is provided in source form for FREE evaluation, for educational use or for peaceful research.
* If you plan on using  uC/OS-II  in a commercial product you need to contact Micrium to properly license
* its use in your product. We provide ALL the source code for your convenience and to help you experience
* uC/OS-II.   The fact that the  source is provided does  NOT  mean that you can use it without  paying a
* licensing fee.
*
* Knowledge of the source code may NOT be used to develop a similar product.
*
* Please help us continue to provide the embedded community with the finest software available.
* Your honesty is greatly appreciated.
*
* You can find our product's user manual, API reference, release notes and
* more information at https://doc.micrium.com.
* You can contact us at www.micrium.com.
*********************************************************************************************************
*/

#define  MICRIUM_SOURCE

#ifndef  OS_MASTER_FILE
#include <ucos_ii.h>//导入头文件
#endif

//检查是否允许内存管理
//#define OS_MAX_MEM_PART           5u   /* Max. number of memory partitions                             */
#if (OS_MEM_EN > 0u) && (OS_MAX_MEM_PART > 0u)
/*
*********************************************************************************************************
*                                      CREATE A MEMORY PARTITION(创建一个内存分区)
*
* Description : Create a fixed-sized memory partition that will be managed by uC/OS-II.
*创建一个固定大小的内存分区,这个分区将会被uC/OS-II管理
* Arguments   : addr     is the starting address of the memory partition
*内存分区的起始地址
*               nblks    is the number of memory blocks to create from the partition.
*创建内存分区所需要的内存块
*               blksize  is the size (in bytes) of each block in the memory partition.
*内存分区中的每一个内存块的大小,以字节为单位
*               perr     is a pointer to a variable containing an error message which will be set by
*                        this function to either:
*
*                        OS_ERR_NONE                     if the memory partition has been created correctly.
*                        OS_ERR_ILLEGAL_CREATE_RUN_TIME  if you tried to create a memory partition after
*                                                        safety critical operation started.
*                        OS_ERR_MEM_INVALID_ADDR         if you are specifying an invalid address for the memory
*                                                        storage of the partition or, the block does not align
*                                                        on a pointer boundary
*                        OS_ERR_MEM_INVALID_PART         no free partitions available
*                        OS_ERR_MEM_INVALID_BLKS         user specified an invalid number of blocks (must be >= 2)
*                        OS_ERR_MEM_INVALID_SIZE         user specified an invalid block size
*                                                          - must be greater than the size of a pointer(必须大于一个指针的大小)
*                                                          - must be able to hold an integral number of pointers(必须能够容纳下一个整数指针)
* Returns    : != (OS_MEM *)0  is the partition was created(如果分区被成功创建,那么返回非0值)
*              == (OS_MEM *)0  if the partition was not created because of invalid arguments or, no
*                              free partition is available.(如果因为传入了错误的参数,或者没有空余的内存分区控制块来创建分区,则创建失败,返回0指针)
*********************************************************************************************************
*/

OS_MEM  *OSMemCreate (void   *addr,
                      INT32U  nblks,
                      INT32U  blksize,
                      INT8U  *perr)
{
    OS_MEM    *pmem;
    INT8U     *pblk;
    void     **plink;
    INT32U     loops;
    INT32U     i;
#if OS_CRITICAL_METHOD == 3u                          /* Allocate storage for CPU status register      */
    OS_CPU_SR  cpu_sr = 0u;
#endif



#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return ((OS_MEM *)0);
    }
#endif

#ifdef OS_SAFETY_CRITICAL_IEC61508
    if (OSSafetyCriticalStartFlag == OS_TRUE) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        *perr = OS_ERR_ILLEGAL_CREATE_RUN_TIME;
        return ((OS_MEM *)0);
    }
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    //传入0指针
    if (addr == (void *)0) {                          /* Must pass a valid address for the memory part.*/
        *perr = OS_ERR_MEM_INVALID_ADDR;
        return ((OS_MEM *)0);
    }
    //????
    if (((INT32U)addr & (sizeof(void *) - 1u)) != 0u){  /* Must be pointer size aligned                */
        *perr = OS_ERR_MEM_INVALID_ADDR;
        return ((OS_MEM *)0);
    }
    //分区中必须至少含有两个内存块
    if (nblks < 2u) {                                 /* Must have at least 2 blocks per partition     */
        *perr = OS_ERR_MEM_INVALID_BLKS;
        return ((OS_MEM *)0);
    }
    //blksize以字节为单位,即每一块内存块的大小,必须可以容纳下一个指针
    if (blksize < sizeof(void *)) {                   /* Must contain space for at least a pointer     */
        *perr = OS_ERR_MEM_INVALID_SIZE;
        return ((OS_MEM *)0);
    }
#endif
    OS_ENTER_CRITICAL();//关中断,进入临界区
    //获取一个空闲的内存分区控制块MCB
    pmem = OSMemFreeList;                             /* Get next free memory partition                */
    if (OSMemFreeList != (OS_MEM *)0) {               /* See if pool of free partitions was empty      */
        OSMemFreeList = (OS_MEM *)OSMemFreeList->OSMemFreeList;
    }
    OS_EXIT_CRITICAL();//开中断,退出临界区
    if (pmem == (OS_MEM *)0) {                        /* See if we have a memory partition             */
        *perr = OS_ERR_MEM_INVALID_PART;
        return ((OS_MEM *)0);//如果没有空闲的内存分区控制块MCB
    }
    //对内存分区进行链接操作,使之成为具有一定数据结构的区域
    //plink是指向内存分区起始处的二级指针,采用*操作后可以进入指向的内存内
    plink = (void **)addr;                            /* Create linked list of free memory blocks      */
    pblk  = (INT8U *)addr;
    loops  = nblks - 1u;//内存块之间建立指针链接,故只需要nblks-1个链接
    for (i = 0u; i < loops; i++) {
        //blksize以字节为单位,而且每个地址指向1B内容,所以加上blksize就可以获得下一个内存块的地址
        pblk +=  blksize;                             /* Point to the FOLLOWING block                  */
        //plink进入内存块后,现在里面是一个一级指针,此一级指针指向下一个内存块
       *plink = (void  *)pblk;                        /* Save pointer to NEXT block in CURRENT block   */
        //对当前内存块进行操作之后,二级指针再次指向下一个内存块
        plink = (void **)pblk;                        /* Position to  NEXT      block                  */
    }//上面的操作就是一级指针每次都指向下一个内存块,然后需要一个指向当前内存块的二级指针,来将一级指针存入当前内存块中,如此实现内存块之间的链接
    
    //此时pblk和plink都指向了最后一个内存块
    *plink              = (void *)0;                  /* Last memory block points to NULL              */
    //将对应的内存分区的信息填入内存分区控制块中
    pmem->OSMemAddr     = addr;                       /* Store start address of memory partition       */
    pmem->OSMemFreeList = addr;                       /* Initialize pointer to pool of free blocks     */
    pmem->OSMemNFree    = nblks;                      /* Store number of free blocks in MCB            */
    pmem->OSMemNBlks    = nblks;
    pmem->OSMemBlkSize  = blksize;                    /* Store block size of each memory blocks        */
    
    OS_TRACE_MEM_CREATE(pmem);
    
    *perr               = OS_ERR_NONE;
    return (pmem);
}


/*
*********************************************************************************************************
*                                         GET A MEMORY BLOCK(获取一个内存块)
*
* Description : Get a memory block from a partition
*从内存分区中获取一个内存块
* Arguments   : pmem    is a pointer to the memory partition control block
*指向内存分区控制块的指针
*               perr    is a pointer to a variable containing an error message which will be set by this
*                       function to either:
*
*                       OS_ERR_NONE             if the memory partition has been created correctly.
*                       OS_ERR_MEM_NO_FREE_BLKS if there are no more free memory blocks to allocate to caller
*                       OS_ERR_MEM_INVALID_PMEM if you passed a NULL pointer for 'pmem'
*
* Returns     : A pointer to a memory block if no error is detected(如果没有发生任何错误,则返回一个指向内存块的指针)
*               A pointer to NULL if an error is detected(如果发生了错误,则返回空指针)
*********************************************************************************************************
*/

void  *OSMemGet (OS_MEM  *pmem,
                 INT8U   *perr)
{
    void      *pblk;
#if OS_CRITICAL_METHOD == 3u                          /* Allocate storage for CPU status register      */
    OS_CPU_SR  cpu_sr = 0u;
#endif


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return ((void *)0);
    }
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pmem == (OS_MEM *)0) {                        /* Must point to a valid memory partition        */
        *perr = OS_ERR_MEM_INVALID_PMEM;
        return ((void *)0);
    }
#endif

    OS_TRACE_MEM_GET_ENTER(pmem);

    OS_ENTER_CRITICAL();//关中断,进入临界区
    //检查是否还有空闲的内存块
    if (pmem->OSMemNFree > 0u) {                      /* See if there are any free memory blocks       */
        pblk                = pmem->OSMemFreeList;    /* Yes, point to next free memory block          */
        //将空闲链表指向下一个内存块
        pmem->OSMemFreeList = *(void **)pblk;         /*      Adjust pointer to new free list          */
        //可用数减1
        pmem->OSMemNFree--;                           /*      One less memory block in this partition  */
        OS_EXIT_CRITICAL();
        *perr = OS_ERR_NONE;                          /*      No error                                 */
        OS_TRACE_MEM_GET_EXIT(*perr);
        return (pblk);                                /*      Return memory block to caller            */
    }
    OS_EXIT_CRITICAL();
    *perr = OS_ERR_MEM_NO_FREE_BLKS;                  /* No,  Notify caller of empty memory partition  */
    OS_TRACE_MEM_GET_EXIT(*perr);
    return ((void *)0);                               /*      Return NULL pointer to caller            */
}


/*
*********************************************************************************************************
*                                 GET THE NAME OF A MEMORY PARTITION(获取内存分区的名字)
*
* Description: This function is used to obtain the name assigned to a memory partition.
*这个函数被用来获取内存分区的名字
* Arguments  : pmem      is a pointer to the memory partition
*指向内存分区控制块的指针
*              pname     is a pointer to a pointer to an ASCII string that will receive the name of the memory partition.
*指向一个ASCII类型的字符串的指针,这个指针会接收内存分区控制块的名字
*              perr      is a pointer to an error code that can contain one of the following values:
*
*                        OS_ERR_NONE                if the name was copied to 'pname'
*                        OS_ERR_MEM_INVALID_PMEM    if you passed a NULL pointer for 'pmem'
*                        OS_ERR_PNAME_NULL          You passed a NULL pointer for 'pname'
*                        OS_ERR_NAME_GET_ISR        You called this function from an ISR
*
* Returns    : The length of the string or 0 if 'pmem' is a NULL pointer.(返回字符串的长度,如果传入的pmem是一个空指针的话,则返回0值)
*********************************************************************************************************
*/

//检查内存控制块是否允许使用名字
#if OS_MEM_NAME_EN > 0u
INT8U  OSMemNameGet (OS_MEM   *pmem,
                     INT8U   **pname,
                     INT8U    *perr)
{
    INT8U      len;
#if OS_CRITICAL_METHOD == 3u                     /* Allocate storage for CPU status register           */
    OS_CPU_SR  cpu_sr = 0u;
#endif



#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (0u);
    }
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pmem == (OS_MEM *)0) {                   /* Is 'pmem' a NULL pointer?                          */
        *perr = OS_ERR_MEM_INVALID_PMEM;
        return (0u);
    }
    if (pname == (INT8U **)0) {                  /* Is 'pname' a NULL pointer?                         */
        *perr = OS_ERR_PNAME_NULL;
        return (0u);
    }
#endif
    //ISR中禁止调用此函数
    if (OSIntNesting > 0u) {                     /* See if trying to call from an ISR                  */
        *perr = OS_ERR_NAME_GET_ISR;
        return (0u);
    }
    OS_ENTER_CRITICAL();//关中断,进入临界区
    *pname = pmem->OSMemName;//获取名字
    len    = OS_StrLen(*pname);
    OS_EXIT_CRITICAL();//开中断,退出临界区
    *perr  = OS_ERR_NONE;
    return (len);
}
#endif


/*
*********************************************************************************************************
*                                 ASSIGN A NAME TO A MEMORY PARTITION(给内存分区控制块指定一个名字)
*
* Description: This function assigns a name to a memory partition.
*这个函数用来给内存分区控制块指定一个名字
* Arguments  : pmem      is a pointer to the memory partition
*指向内存分区控制块的指针
*              pname     is a pointer to an ASCII string that contains the name of the memory partition.
*指向string类型的名字的指针
*              perr      is a pointer to an error code that can contain one of the following values:
*
*                        OS_ERR_NONE                if the name was copied to 'pname'
*                        OS_ERR_MEM_INVALID_PMEM    if you passed a NULL pointer for 'pmem'
*                        OS_ERR_PNAME_NULL          You passed a NULL pointer for 'pname'
*                        OS_ERR_MEM_NAME_TOO_LONG   if the name doesn't fit in the storage area(如果名字并不适合存储名字的空间大小)
*                        OS_ERR_NAME_SET_ISR        if you called this function from an ISR
*
* Returns    : None
*********************************************************************************************************
*/

//检查是否允许内存控制块使用名字
#if OS_MEM_NAME_EN > 0u
void  OSMemNameSet (OS_MEM  *pmem,
                    INT8U   *pname,
                    INT8U   *perr)
{
#if OS_CRITICAL_METHOD == 3u                     /* Allocate storage for CPU status register           */
    OS_CPU_SR  cpu_sr = 0u;
#endif



#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return;
    }
#endif
//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pmem == (OS_MEM *)0) {                   /* Is 'pmem' a NULL pointer?                          */
        *perr = OS_ERR_MEM_INVALID_PMEM;
        return;
    }
    if (pname == (INT8U *)0) {                   /* Is 'pname' a NULL pointer?                         */
        *perr = OS_ERR_PNAME_NULL;
        return;
    }
#endif
    //ISR中禁止调用此函数
    if (OSIntNesting > 0u) {                     /* See if trying to call from an ISR                  */
        *perr = OS_ERR_NAME_SET_ISR;
        return;
    }
    OS_ENTER_CRITICAL();
    pmem->OSMemName = pname;
    OS_EXIT_CRITICAL();
    OS_TRACE_EVENT_NAME_SET(pmem, pname);
    *perr           = OS_ERR_NONE;
}
#endif


/*
*********************************************************************************************************
*                                       RELEASE A MEMORY BLOCK(释放一个内存控制块)
*
* Description : Returns a memory block to a partition
*释放一个内存控制块到内存分区
* Arguments   : pmem    is a pointer to the memory partition control block
*指向内存分区控制块的指针
*               pblk    is a pointer to the memory block being released.
*指向即将被释放的内存块的指针
* Returns     : OS_ERR_NONE              if the memory block was inserted into the partition
*               OS_ERR_MEM_FULL          if you are returning a memory block to an already FULL memory
*                                        partition (You freed more blocks than you allocated!)
*               OS_ERR_MEM_INVALID_PMEM  if you passed a NULL pointer for 'pmem'
*               OS_ERR_MEM_INVALID_PBLK  if you passed a NULL pointer for the block to release.
*********************************************************************************************************
*/


//每次释放只释放一个
INT8U  OSMemPut (OS_MEM  *pmem,
                 void    *pblk)
{
#if OS_CRITICAL_METHOD == 3u                     /* Allocate storage for CPU status register           */
    OS_CPU_SR  cpu_sr = 0u;
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pmem == (OS_MEM *)0) {                   /* Must point to a valid memory partition             */
        return (OS_ERR_MEM_INVALID_PMEM);
    }
    if (pblk == (void *)0) {                     /* Must release a valid block                         */
        return (OS_ERR_MEM_INVALID_PBLK);
    }
#endif

    OS_TRACE_MEM_PUT_ENTER(pmem, pblk);
    //关中断,进入临界区
    OS_ENTER_CRITICAL();
    //如果内存空间已满,则返回,并置错误信息
    if (pmem->OSMemNFree >= pmem->OSMemNBlks) {  /* Make sure all blocks not already returned          */
        OS_EXIT_CRITICAL();
        OS_TRACE_MEM_PUT_EXIT(OS_ERR_MEM_FULL);
        return (OS_ERR_MEM_FULL);
    }
    //如果允许释放内存块
    //采用头插法,将内存块插入到空闲链表中
    *(void **)pblk      = pmem->OSMemFreeList;   /* Insert released block into free block list         */
    pmem->OSMemFreeList = pblk;
    pmem->OSMemNFree++;                          /* One more memory block in this partition            */
    OS_EXIT_CRITICAL();
    OS_TRACE_MEM_PUT_EXIT(OS_ERR_NONE);
    return (OS_ERR_NONE);                        /* Notify caller that memory block was released       */
}


/*
*********************************************************************************************************
*                                       QUERY MEMORY PARTITION(查询内存分区控制块的信息)
*
* Description : This function is used to determine the number of free memory blocks and the number of
*               used memory blocks from a memory partition.
*这个函数是用来查看内存控制块中的空闲内存块的数量和已用内存块的数量
* Arguments   : pmem        is a pointer to the memory partition control block
*指向内存控制块的指针
*               p_mem_data  is a pointer to a structure that will contain information about the memory
*                           partition.
*指向用来保存内存分区控制块信息的结构体的指针
* Returns     : OS_ERR_NONE               if no errors were found.
*               OS_ERR_MEM_INVALID_PMEM   if you passed a NULL pointer for 'pmem'
*               OS_ERR_MEM_INVALID_PDATA  if you passed a NULL pointer to the data recipient.
*********************************************************************************************************
*/

//检查是否允许内存控制块信息查询
#if OS_MEM_QUERY_EN > 0u
INT8U  OSMemQuery (OS_MEM       *pmem,
                   OS_MEM_DATA  *p_mem_data)
{
#if OS_CRITICAL_METHOD == 3u                     /* Allocate storage for CPU status register           */
    OS_CPU_SR  cpu_sr = 0u;
#endif


//参数查询
#if OS_ARG_CHK_EN > 0u
    if (pmem == (OS_MEM *)0) {                   /* Must point to a valid memory partition             */
        return (OS_ERR_MEM_INVALID_PMEM);
    }
    if (p_mem_data == (OS_MEM_DATA *)0) {        /* Must release a valid storage area for the data     */
        return (OS_ERR_MEM_INVALID_PDATA);
    }
#endif
    OS_ENTER_CRITICAL();//关中断,进入临界区
    p_mem_data->OSAddr     = pmem->OSMemAddr;
    p_mem_data->OSFreeList = pmem->OSMemFreeList;
    p_mem_data->OSBlkSize  = pmem->OSMemBlkSize;
    p_mem_data->OSNBlks    = pmem->OSMemNBlks;
    p_mem_data->OSNFree    = pmem->OSMemNFree;
    //除了名字之外全部获取了
    OS_EXIT_CRITICAL();//开中断,退出临界区
    p_mem_data->OSNUsed    = p_mem_data->OSNBlks - p_mem_data->OSNFree;
    return (OS_ERR_NONE);
}
#endif                                           /* OS_MEM_QUERY_EN                                    */


/*
*********************************************************************************************************
*                                 INITIALIZE MEMORY PARTITION MANAGER(初始化内存分区控制块管理器)
*
* Description : This function is called by uC/OS-II to initialize the memory partition manager.  Your
*               application MUST NOT call this function.
*这个函数被系统调用,来初始化内存分区控制块管理器,你的应用程序不能调用此函数
* Arguments   : none
*
* Returns     : none
*
* Note(s)    : This function is INTERNAL to uC/OS-II and your application should not call it.
这个函数是系统内部函数,你的应用程序不能调用它
*********************************************************************************************************
*/

void  OS_MemInit (void)
{
    //如果内存分区控制块只有一个
#if OS_MAX_MEM_PART == 1u
    //按字节清空内存控制块的空间
    OS_MemClr((INT8U *)&OSMemTbl[0], sizeof(OSMemTbl));   /* Clear the memory partition table          */
    OSMemFreeList               = (OS_MEM *)&OSMemTbl[0]; /* Point to beginning of free list           */
#if OS_MEM_NAME_EN > 0u
    OSMemFreeList->OSMemName    = (INT8U *)"?";           /* Unknown name                              */
#endif
#endif

//如果内存分区控制块的数量大于1个
#if OS_MAX_MEM_PART >= 2u
    OS_MEM  *pmem;
    INT16U   i;

    //按字节清空内存空间
    OS_MemClr((INT8U *)&OSMemTbl[0], sizeof(OSMemTbl));   /* Clear the memory partition table          */
    //处理前N-1个,第N个单独处理
    for (i = 0u; i < (OS_MAX_MEM_PART - 1u); i++) {       /* Init. list of free memory partitions      */
        pmem                = &OSMemTbl[i];               /* Point to memory control block (MCB)       */
        pmem->OSMemFreeList = (void *)&OSMemTbl[i + 1u];  /* Chain list of free partitions             */
#if OS_MEM_NAME_EN > 0u
        pmem->OSMemName  = (INT8U *)(void *)"?";
#endif
    }
    //单独处理最后一个内存分区控制块
    pmem                = &OSMemTbl[i];
    pmem->OSMemFreeList = (void *)0;                      /* Initialize last node                      */
#if OS_MEM_NAME_EN > 0u
    pmem->OSMemName = (INT8U *)(void *)"?";
#endif

    OSMemFreeList   = &OSMemTbl[0];                       /* Point to beginning of free list           */
#endif
}
#endif                                                    /* OS_MEM_EN                                 */

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值