Linux - 内存管理

Linux 内存管理 本文详细的介绍了多种内存管理方式,同时详细介绍了Linux下的内存管理方式 阅读详情

 引用文章


一. 用户进程内存管理

1.1 进程的虚拟地址空间VMA

1.2 进程的pmap

1.3 VMA与程序的各个段以及库关系

1.4 VSS, RSS, PSS, USS的关系

1.5 page fault的几种可能性

1.6 进程内存泄漏的界定

1.7 内存泄漏的检查

二. 内核内存管理

2.1 内存分布

2.2 内存管理图

 

三. 用户空间和内核空间内存分配关系

3.1 内存总体关系图

3.2 Libc, Slab与buddy

3.3 kmalloc VS vmalloc/ioremap

四. 一个mmap的小实验

4.1 kernel driver

#include <linux/version.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mm.h>
#ifdef MODVERSIONS
#include <linux/modversions.h>
#endif
#include <asm/io.h>
#include <linux/device.h>

/* length of the two memory areas */
#define NPAGES 16

struct mmap_dev_info_st {
    /* char device */
    dev_t mmap_dev;
    struct cdev mmap_cdev;
    
    struct class *mmap_class;
    
    
    /* pointer to the vmalloc'd area - alway page aligned */
    int *vmalloc_area;

    /* pointer to the kmalloc'd area, rounded up to a page boundary */
    int *kmalloc_area;

    /* original pointer for kmalloc'd area as returned by kmalloc */
    void *kmalloc_ptr;
};

static struct mmap_dev_info_st mmap_dev_info;


static int mmap_open(struct inode *inode, struct file *filp)
{
    return 0;
}

static int mmap_release(struct inode *inode, struct file *filp)
{
    return 0;
}

/* mmap's the kmalloc'd area which is physically contiguous */
int mmap_kmem(struct file *filp, struct vm_area_struct *vma)
{
    int ret = 0;
    long length = vma->vm_end - vma->vm_start;
    int *kmalloc_area = mmap_dev_info.kmalloc_area;
    
    printk(KERN_ERR "%s: start\n", __func__);

    /* check length - do not allow larger mappings than the number of
       pages allocated */
    if (length > NPAGES * PAGE_SIZE) {
        ret = -EIO;
        printk(KERN_ERR "%s: length err.\n", __func__);
        goto err;
    }

    /* map the whole physically contiguous area in one piece */
    ret = remap_pfn_range(vma, vma->vm_start,
                    virt_to_phys((void *)kmalloc_area) >> PAGE_SHIFT,
                    length, vma->vm_page_prot);
    if (ret < 0) {
        printk(KERN_ERR "%s: ret:%d err.\n", __func__, ret);
        goto err;
    }
    
    return 0;

err:
    return ret;
}

/* mmap's the vmalloc'd area which is not physically contiguous */
int mmap_vmem(struct file *filp, struct vm_area_struct *vma)
{
    int ret = 0;
    long length = vma->vm_end - vma->vm_start;
    unsigned long start = vma->vm_start;
    char *vmalloc_area_ptr = (char *)mmap_dev_info.vmalloc_area;
    unsigned long pfn = 0;

    printk(KERN_ERR "%s: start\n", __func__);

    /* check length - do not allow larger mappings than the number of
       pages allocated */
    if (length > NPAGES * PAGE_SIZE) {
        ret = -EIO;
        printk(KERN_ERR "%s: length err.\n", __func__);
        goto err;
    }

    /* loop over all pages, map it page individually */
    while (length > 0) {
        pfn = vmalloc_to_pfn(vmalloc_area_ptr);
        ret = remap_pfn_range(vma, start, pfn, PAGE_SIZE, PAGE_SHARED);
        if (ret < 0) {
            printk(KERN_ERR "%s: remap_pfn_range err.\n", __func__);
            goto err;
        }

        start += PAGE_SIZE;
        vmalloc_area_ptr += PAGE_SIZE;
        length -= PAGE_SIZE;
    }

    return 0;

err:
    return ret;
}

/* character device mmap method */
static int mmap_mmap(struct file *filp, struct vm_area_struct *vma)
{
    int ret = 0;

    if (vma->vm_pgoff == 0) {
        /* at offset 0 we map the vmalloc'd area */
        ret =  mmap_vmem(filp, vma);  
    } else if (vma->vm_pgoff == NPAGES) {
        /* at offset NPAGES we map the kmalloc'd area */
        ret = mmap_kmem(filp, vma);
    } else {
        /* at any other offset we return an error */
        ret = -EIO;
    }
    
    return ret;
}

static struct file_operations mmap_fops = {
    .open = mmap_open,
    .release = mmap_release,
    .mmap = mmap_mmap,
    .owner = THIS_MODULE,
};

static int __init my_mmap_init(void)
{
    int ret = 0;
    int i = 0;

    printk(KERN_ERR "%s: start\n", __func__);
    
    /* allocate a memory area with kmalloc. Will be rounded up to a page boundary */
    if ((mmap_dev_info.kmalloc_ptr = kmalloc((NPAGES + 2) * PAGE_SIZE, GFP_KERNEL)) == NULL) {
        ret = -ENOMEM;
        goto out;
    }

    /* round it up to the page bondary,即找到页对齐的地址 */
    mmap_dev_info.kmalloc_area = (int *)PAGE_ALIGN((unsigned long)mmap_dev_info.kmalloc_ptr);

    /* allocate a memory area with vmalloc. */
    if ((mmap_dev_info.vmalloc_area = (int *)vmalloc(NPAGES * PAGE_SIZE)) == NULL) {
        ret = -ENOMEM;
        goto out_kfree;
    }

    /* get the major number of the character device */
    if ((ret = alloc_chrdev_region(&mmap_dev_info.mmap_dev, 0, 1, "mmap")) < 0) {
        printk(KERN_ERR "could not allocate major number for mmap\n");
        goto out_vfree;
    }

    /* initialize the device structure and register the device with the kernel */
    cdev_init(&mmap_dev_info.mmap_cdev, &mmap_fops);
    if ((ret = cdev_add(&mmap_dev_info.mmap_cdev, mmap_dev_info.mmap_dev, 1)) < 0) {
        printk(KERN_ERR "could not allocate chrdev for mmap\n");
        goto out_unalloc_region;
    }

    /* mark the pages reserved,即让申请的memory不被交换到磁盘。*/
    for (i = 0; i < NPAGES * PAGE_SIZE; i += PAGE_SIZE) {
        //mark_page_reserved(vmalloc_to_page((void *)(((unsigned long)(mmap_dev_info.vmalloc_area)) + i)));
        //mark_page_reserved(virt_to_page(((unsigned long)(mmap_dev_info.kmalloc_area)) + i));
        
        SetPageReserved(vmalloc_to_page((void *)(((unsigned long)(mmap_dev_info.vmalloc_area)) + i)));
        SetPageReserved(virt_to_page(((unsigned long)(mmap_dev_info.kmalloc_area)) + i));
    }

    /* store a pattern in the memory - the test application will check for it */
    for (i = 0; i < (NPAGES * PAGE_SIZE / sizeof(int)); i += 2) {
        mmap_dev_info.vmalloc_area[i] = (0xaffe << 16) + i;
        mmap_dev_info.vmalloc_area[i + 1] = (0xbeef << 16) + i;
        mmap_dev_info.kmalloc_area[i] = (0xdead << 16) + i;
        mmap_dev_info.kmalloc_area[i + 1] = (0xbeef << 16) + i;
    }

    /* create class */
    mmap_dev_info.mmap_class = class_create(THIS_MODULE, "mmap_class");
    if (IS_ERR(mmap_dev_info.mmap_class)) {
        printk(KERN_ERR "class_create failed.\n");
        ret = -1;
        goto out_unalloc_region;
    }
    
    /* create device */
    device_create(mmap_dev_info.mmap_class, NULL, mmap_dev_info.mmap_dev, NULL, "mmap_dev");

    printk(KERN_ERR "%s: end\n", __func__);

    return ret;
    
out_unalloc_region:
    unregister_chrdev_region(mmap_dev_info.mmap_dev, 1);

out_vfree:
    vfree(mmap_dev_info.vmalloc_area);
    mmap_dev_info.vmalloc_area = NULL;

out_kfree:
    kfree(mmap_dev_info.kmalloc_ptr);
    mmap_dev_info.kmalloc_ptr = NULL;

out:
    return ret;
}

static void __exit my_mmap_exit(void)
{
    int i = 0;

    /* unregister device */
    device_destroy(mmap_dev_info.mmap_class, mmap_dev_info.mmap_dev);

    /* remove the character deivce */
    cdev_del(&(mmap_dev_info.mmap_cdev));
    
    class_destroy(mmap_dev_info.mmap_class);
    unregister_chrdev_region(mmap_dev_info.mmap_dev, 1);

    /* unreserve the pages */
    for (i = 0; i < NPAGES * PAGE_SIZE; i += PAGE_SIZE) {
        //free_reserved_page(vmalloc_to_page((void *)(((unsigned long)(mmap_dev_info.vmalloc_area)) + i)));
        //free_reserved_page(virt_to_page(((unsigned long)(mmap_dev_info.kmalloc_area)) + i));
        ClearPageReserved(vmalloc_to_page((void *)(((unsigned long)(mmap_dev_info.vmalloc_area)) + i)));
        ClearPageReserved(virt_to_page(((unsigned long)(mmap_dev_info.kmalloc_area)) + i));
        
    }
    
    /* free the memory areas */
    if (mmap_dev_info.vmalloc_area) {
        vfree(mmap_dev_info.vmalloc_area);
        mmap_dev_info.vmalloc_area = NULL;
    }
    
    if (mmap_dev_info.kmalloc_ptr) {
        kfree(mmap_dev_info.kmalloc_ptr);
        mmap_dev_info.kmalloc_ptr = NULL;
    }
}

module_init(my_mmap_init);
module_exit(my_mmap_exit);

MODULE_DESCRIPTION("mmap demo driver");
MODULE_AUTHOR("vector");
MODULE_LICENSE("GPL");
ifneq ($(KERNELRELEASE),)                                                                                                                                                                               
    obj-m := map_driver.o
else
    PWD  := $(shell pwd)
KDIR := /lib/modules/$(shell uname -r)/build

all:
    $(MAKE) -C $(KDIR) M=$(PWD) modules

clean:
    rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions modules.order Module.symvers
endif

4.2 userspace test app

#include <stdio.h>                                                                                                                                                                                      
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>

#define LEN (16*4096)

int main(int argc, void **argv)
{
    int i = 0;
    int fd;
    unsigned int *vadr;

    fd = open("/dev/mmap_dev", O_RDWR);
    if (fd < 0) {
        perror("open");
        return -1;
    }

    vadr = mmap(0, LEN, PROT_READ, MAP_SHARED, fd, 0);

    if (vadr == MAP_FAILED) {
        perror("mmap");
        return -1;
    }

    printf("------------------------------------------------");
    for (i = 0; i < (LEN / 4); i++) {
        printf("0x%08x,", *(vadr + i));
        if ((i % 10) == 0)
            printf("\n");
    }

    close(fd);

    return(0);
}

4.3 测试结果

不会写GLSL?用Cesium 1.120 + Heatmap.js 2.0.5也能搞定动态洪水模拟(附完整源码) 本文介绍了一种无需GLSL编程的3D洪水动态模拟方案,结合Cesium 1.120和Heatmap.js 2.0.5实现高效可视化。通过数据层、可视化层和集成层的技术降级方案,开发者可以快速构建专业级洪水演进效果,适用于应急管理、水利工程等场景。文章包含完整源码和性能优化技巧。 阅读详情

相关推荐

AGI 之 【Dify】 之 Dify 在 Windows 端本地部署调用 Ollama 本地下载的大模型, API 形式 Python 调用 进行简单聊天接口测试

AGI,即通用人工智能(Artificial General Intelligence),是一种具备人类智能水平的人工智能系统。它不仅能够执行特定的任务,而且能够理解、学习和应用知识于广泛的问题解决中,具有较高的自主性和适应性。AGI的能力包括但不限于自我学习、自我改进、自我调整,并能在没有人为干预的情况下解决各种复杂问题。本节将介绍如何使用 Dify 平台调用 Ollama 部署的本地模型来创建一个聊天应用。通过 API 的方式发起聊天,可以让前端自由布置所需的聊天形式。

仙魁XAN 1万+

关于宏PageReserved

宏PageReserved用来检测是否是该页是否为内核代码所用或者该页根本就没有使用。 定义在include/linux/page-flags.h中 #define TESTPAGEFLAG(uname, lname)                                \ static inline int Page##uname(struct page *page)

adaptiver的专栏 5645

使用3d Slicer标注病灶并生成ROI掩膜

本篇博客给大家演示一下如何使用3d Slicer标注病灶并生成ROI掩膜,供深度学习模型训练使用。 关于3d Slicer和MRIcron的安装请看我的另一个帖子。 一、数据加载 你可以使用你手头的数据进行标注,这里为了示例方便,我是用的3d Slicer中给出的Sample Data中的MRBrainTumor1的数据。 二、病灶标注及保存 Modules选择Segment Editor: 然后点击Add按钮添加一个Segment,在下方便签上双击可以修改Segment的命名和颜色等。下方三个按钮

Su_Del的博客 1万+

linux内核源码分析之伙伴系统(一)

目录 一、重要结构体 二、数据结构之间的关系 1、分配数量 2、区域类型 3,备用区域列表 4、区域水位 5、min_free_kbytes 三、分配页面 1、ac参数获取值 2,快速分配 3,慢速分配 一、重要结构体 页 (page) 一个 page 结构表示一个物理内存页面。 区(zone) 因为硬件限制,Linux内核不能把所有的物理内存页统一对待,把属性相同的物理内存页面。归结到了一个区中。 节点 (pglist_data)...

2484

eICU数据库没有ventilation_event表

各位学友大家好,我是环湖医院神经外科的飞时过,很多外院的老师和我问,ventilation_event表的问题,哪怕用ChatGPT也无法正确生成,今天我给大家用SQL做一个拿来就能用的。

环湖数据科学知识共享平台 940

使用fluent计算流噪声_Fluent能够做的事

刚接触到fluent的同学们,应该会比较好奇,fluent能够做些什么事情,和你的研究有没有关联,能不能达到你的目的?如果不弄明白这样一点,前期可能会做很多无用功。 fluent是计算流体力学的软件,是一个工具。这样一个工具发展至今,可以用来模拟的绝不只有流体力学。下面我们依次来说明。首先是流动,fluent提供了非常丰富的流动模型,不仅可以模拟层流,同样还可以模拟...

weixin_28717647的博客 4861

Linux深入理解内存管理11

Linux深入理解内存管理11(基于Linux6.6)---CMA介绍

ListQ的博客 1686

华为OD机试真题2026双机位C卷 Python&JS 实现【明日之星选举】

给定一组选票votes。votes[i]代表第 i 张选票的内容,包含一个字符串"zhangsan,hanmei",表示推荐zhangsan为明日之星,反对 hanmei 称为明日之星。赞成或反对使用逗号(,)分割。 给定一个数组n,表示最后将筛选出赞成票最多的n个人,如果赞成票相同,则反对票越少,排序越靠前;如果赞成票和反对票都相同,则按照姓名字典序升序排序。

MISAYAONE的博客 325

linux内存源码分析 - 伙伴系统(初始化和申请页框)

之前的文章已经介绍了伙伴系统,这篇我们主要看看源码中是如何初始化伙伴系统、从伙伴系统中分配页框,返回页框于伙伴系统中的。   我们知道,每个管理区都有自己的伙伴系统管理属于这个管理区的页框,这也说明了,在伙伴系统初始化时,管理区必须要已经存在(初始化完成)了。在管理区描述符(struct zone)中,struct free_area就专门用于描述伙伴系统的。在一个管理区中,伙伴系统一共维护

华的专栏 1389

【数字IC刷题】华为海思数字IC笔试题(3)详细解析版

【数字IC刷题】华为海思数字IC笔试题(3)详细解析版

MoorePlus的博客 2375

Vue 前端导出页面A4大小pdf,Vue前端导出pdf自动切割换页不切割内容 Vue导出页面pdf自动分页和添加页码 导出的pdf提高清晰度

【代码】Vue 前端导出页面A4大小pdf,Vue前端导出pdf自动切割换页不切割内容 Vue导出页面pdf自动分页和添加页码 导出的pdf提高清晰度。

weixin_41346436的博客 1801

linux 内存管理---伙伴系统(六)

start_kernel()调用mm_init()进行伙伴系统的初始化。static void __init mm_init(void){    /*     * page_cgroup requires countinous pages as memmap     * and it's bigger than MAX_ORDER unless SPARSEMEM.     */    page_...

whuzm08的专栏 1087

Python 爬虫实战:就业市场趋势数据抓取与行业洞察

在当今竞争激烈的就业市场中,了解行业趋势和就业形势对于求职者、学生以及人力资源专业人士来说至关重要。通过获取和分析就业市场数据,我们可以深入了解不同行业的招聘需求、薪资水平、技能要求等关键信息,从而为职业规划和人才发展提供有力支持。

yansideyucsdn的博客 1407

linux内存管理

对于物理内存内存,linux对内存的组织逻辑从上到下依次是:node,zone,page,这些page是根据buddy分配算法组织的,看下面两张图:

wwwlyj123321的博客 4549

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

关于 Linux 内存管理

Linux 内存管理涵盖了分配、释放、映射、交换、压缩、保护和监控等操作。最大限度地利用内存;保证系统的稳定与可靠;为应用提供抽象且隔离的运行环境。内存管理是操作系统对硬件内存资源的抽象与管理。它通过虚拟内存机制将进程的地址空间与物理内存解耦,使得每个进程都“感觉”自己独占了整个内存空间。物理内存是计算机中的主存(DRAM),它是 CPU 运行程序的直接存储区域。速度快:比磁盘快,但比 CPU 缓存慢;容量有限:受硬件限制;寻址方式:通过物理地址直接访问。

m0_74258518的博客 1090

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Linux内核之内存管理

NUMA(Non-Uniform Memory Access,非统一内存访问)是一种多处理器系统的内存架构。内存被划分为多个节点(node),每个节点与一个或多个处理器核心相关联。处理器访问本地节点内存的延迟较低,访问远程节点内存的延迟较高。以上是我自己学习内存管理时所做的笔记,很多抽象的东西用了通俗的语言来解释清楚,方便在学习的过程中理解,如果你正好是在学习内存管理的相关内容,可以以我的笔记作为参考,如果你是需要突击内存管理相关的知识,也可以结合着大语言模型来进行学习。

qq_56187001的博客 1128

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Linux内存管理

Linux 是为多用户多任务设计的操作系统,所以存储资源要被多个进程有效共享;且由于程序规模的不断膨胀,要求的内存空间比从前大得多。Linux 内存管理的设计充分利用了 计算机系统所提供的虚拟存储技术,真正实现了虚拟存储器管理。第二章介绍的 Intel 386 的段机制和页机制是 Linux 实现虚拟存储管理的一种硬件平台。

qq_28576837的博客 1190

linux 内存管理

目录 1Linux内存管理概述 1.1 内存的层次结构 1.2 虚拟内存概述 1.2.1 虚拟内存基本思想 1.2.2 进程虚拟地址空间 1.3 内核空间到物理空间的映射 1.3.1 内核空间的线性映射 1.3.2 内核镜像的物理存储 1.4 虚拟内存实现机制 2进程用户空间管理 2.1 进程用户空间布局 2.2 进程用户空间的内核描述 2.2.1 概述 2.2.2 mm_struct 结构 2.2.3 vm_area_struct 结构 2.2.4 实例:内核态打印虚存..

5768

linux的内存管理

Linux的内存管理是操作系统中至关重要的组成部分之一。它负责管理系统中的物理内存,以便进程可以访问和使用它。

weixin_39512905的博客 884

【Linux内存管理】

解决内部内存碎片化。不连续页分配器提供分配内存的接口vmalloc和释放内存的接口vfree,在内存碎片化的时候,申请连续物理页的成功率很低,可以申请不连续的物理页,映射到连续的虚拟页,即虚拟地址连续页物理地址不连续,每处理器内存分配器用来为每处理器变量分司内存。为了使系统可以正确的访问页在对应页框中的映像,在把一个页映射到某个页框上的同时,就必须把页码和存放该页映像的页框码填入一个叫做页表的表项中,这个页表就是映射记录表。如果释放的块大小大于链表中的其他块,它可能会与相邻的块合并以形成一个更大的块。

weixin_40146547的博客 695

一文讲透Linux内存管理

Linux内存管理是指对系统内存的分配、释放、映射、管理、交换、压缩等一系列操作的管理。在Linux中,内存被划分为多个区域,每个区域有不同的作用,包括内核空间、用户空间、缓存、交换分区等。Linux内存管理的目标是最大限度地利用可用内存,同时保证系统的稳定和可靠性。内存管理是计算机系统中负责管理系统内存资源的一种机制,主要包括内存分配、内存释放、内存映射和虚拟内存管理等方面。它是计算机系统中非常重要的一个组成部分,能够有效地提高系统的资源利用率和应用程序的性能。

LinkSLA的博客 1875

Linux上的内存管理

 Linux上的内存管理 [ FAQ ]Q:什么是mm?A:这可不是meimei哦!指的是内存管理(memory management)。是内核中的一套软件机制,用于有效管理内存的使用。Q:内存管理的软件实现了什么功能?A:1) 进程的保护,即进程向内存管理请求的物理页,由内存管理系统负责,不会将同一物理页(共享页面除外)映射到不同进程的虚地址空间。?? 2) 虚存的实现,允许所有进程使用的内存总

hondrif82q的专栏 1756

linux内存管理概述

linux内存管理建立在基本的分页机制基础上,在linux内核中RAM的某些部分将会永久的分配给内核,并用来存放内核代码以及静态内核数据结构。RAM的其余部分称为动态内存,这不仅是进程所需的宝贵资源,也是内核本身所需的宝贵资源。实际上,整个系统的性能取决于如何有效地管理动态内存。因此,现在所有多任务操作系统都在经历优化对动态内存的使用,也就是说,尽可能做到当要时分配,不需要时释放。 内存管理是o

bullbat的专栏 4453
上一篇: 设备驱动模型--bus_type详解
下一篇: linux 系统内存监控和分析
Andre-S
博客等级 码龄12年 263粉丝 194原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值