欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

【原创】(十三)Linux内存管理之vma/malloc/mmap

程序员文章站 2022-05-31 19:49:02
背景 By 鲁迅 By 高尔基 说明: 1. Kernel版本:4.14 2. ARM64处理器,Contex A53,双核 3. 使用工具:Source Insight 3.5, Visio 1. 概述 这篇文章,让我们来看看用户态进程的地址空间情况,主要会包括以下: ; ; ; 进程地址空间中, ......

背景

  • read the fucking source code! --by 鲁迅
  • a picture is worth a thousand words. --by 高尔基

说明:

  1. kernel版本:4.14
  2. arm64处理器,contex-a53,双核
  3. 使用工具:source insight 3.5, visio

1. 概述

这篇文章,让我们来看看用户态进程的地址空间情况,主要会包括以下:

  • vma;
  • malloc;
  • mmap;

进程地址空间中,我们常见的代码段,数据段,bss段等,实际上都是一段地址空间区域。linux将地址空间中的区域称为virtual memory area, 简称vma,使用struct vm_area_struct来描述。

在进行内存申请和映射时,都会去地址空间中申请一段虚拟地址区域,而这部分操作也与vma关系密切,因此本文将vma/malloc/mmap三个放到一块来进行分析。
开启探索之旅吧。

2. 数据结构

主要涉及两个结构体:struct mm_structstruct vm_area_struct

  • struct mm_struct
    用于描述与进程地址空间有关的全部信息,这个结构也包含在进程描述符中,关键字段的描述见注释。
struct mm_struct {
    struct vm_area_struct *mmap;        /* list of vmas */                              //指向vma对象的链表头
    struct rb_root mm_rb;                                                                     //指向vma对象的红黑树的根
    u64 vmacache_seqnum;                   /* per-thread vmacache */
#ifdef config_mmu
    unsigned long (*get_unmapped_area) (struct file *filp,
                unsigned long addr, unsigned long len,
                unsigned long pgoff, unsigned long flags);              // 在进程地址空间中搜索有效线性地址区间的方法
#endif
    unsigned long mmap_base;        /* base of mmap area */
    unsigned long mmap_legacy_base;         /* base of mmap area in bottom-up allocations */
#ifdef config_have_arch_compat_mmap_bases
    /* base adresses for compatible mmap() */
    unsigned long mmap_compat_base;
    unsigned long mmap_compat_legacy_base;
#endif
    unsigned long task_size;        /* size of task vm space */
    unsigned long highest_vm_end;       /* highest vma end address */
    pgd_t * pgd;        //指向页全局目录

    /**
     * @mm_users: the number of users including userspace.
     *
     * use mmget()/mmget_not_zero()/mmput() to modify. when this drops
     * to 0 (i.e. when the task exits and there are no other temporary
     * reference holders), we also release a reference on @mm_count
     * (which may then free the &struct mm_struct if @mm_count also
     * drops to 0).
     */
    atomic_t mm_users;      //使用计数器

    /**
     * @mm_count: the number of references to &struct mm_struct
     * (@mm_users count as 1).
     *
     * use mmgrab()/mmdrop() to modify. when this drops to 0, the
     * &struct mm_struct is freed.
     */
    atomic_t mm_count;      //使用计数器

    atomic_long_t nr_ptes;          /* pte page table pages */      //进程页表数
#if config_pgtable_levels > 2
    atomic_long_t nr_pmds;          /* pmd page table pages */
#endif
    int map_count;              /* number of vmas */        //vma的个数

    spinlock_t page_table_lock;     /* protects page tables and some counters */
    struct rw_semaphore mmap_sem;

    struct list_head mmlist;        /* list of maybe swapped mm's.  these are globally strung
                         * together off init_mm.mmlist, and are protected
                         * by mmlist_lock
                         */


    unsigned long hiwater_rss;  /* high-watermark of rss usage */
    unsigned long hiwater_vm;   /* high-water virtual memory usage */

    unsigned long total_vm;     /* total pages mapped */    //进程地址空间的页数
    unsigned long locked_vm;    /* pages that have pg_mlocked set */    //锁住的页数,不能换出
    unsigned long pinned_vm;    /* refcount permanently increased */
    unsigned long data_vm;      /* vm_write & ~vm_shared & ~vm_stack */     //数据段内存的页数
    unsigned long exec_vm;      /* vm_exec & ~vm_write & ~vm_stack */         //可执行内存映射的页数
    unsigned long stack_vm;     /* vm_stack */                                              //用户态堆栈的页数
    unsigned long def_flags;
    unsigned long start_code, end_code, start_data, end_data;       //代码段,数据段等的地址
    unsigned long start_brk, brk, start_stack;      //堆栈段的地址,start_stack表示用户态堆栈的起始地址,brk为堆的当前最后地址
    unsigned long arg_start, arg_end, env_start, env_end;  //命令行参数的地址,环境变量的地址

    unsigned long saved_auxv[at_vector_size]; /* for /proc/pid/auxv */

    /*
     * special counters, in some configurations protected by the
     * page_table_lock, in other configurations by being atomic.
     */
    struct mm_rss_stat rss_stat;

    struct linux_binfmt *binfmt;

    cpumask_var_t cpu_vm_mask_var;

    /* architecture-specific mm context */
    mm_context_t context;

    unsigned long flags; /* must use atomic bitops to access the bits */

    struct core_state *core_state; /* coredumping support */
#ifdef config_membarrier
    atomic_t membarrier_state;
#endif
#ifdef config_aio
    spinlock_t          ioctx_lock;
    struct kioctx_table __rcu   *ioctx_table;
#endif
#ifdef config_memcg
    /*
     * "owner" points to a task that is regarded as the canonical
     * user/owner of this mm. all of the following must be true in
     * order for it to be changed:
     *
     * current == mm->owner
     * current->mm != mm
     * new_owner->mm == mm
     * new_owner->alloc_lock is held
     */
    struct task_struct __rcu *owner;
#endif
    struct user_namespace *user_ns;

    /* store ref to file /proc/<pid>/exe symlink points to */
    struct file __rcu *exe_file;
#ifdef config_mmu_notifier
    struct mmu_notifier_mm *mmu_notifier_mm;
#endif
#if defined(config_transparent_hugepage) && !use_split_pmd_ptlocks
    pgtable_t pmd_huge_pte; /* protected by page_table_lock */
#endif
#ifdef config_cpumask_offstack
    struct cpumask cpumask_allocation;
#endif
#ifdef config_numa_balancing
    /*
     * numa_next_scan is the next time that the ptes will be marked
     * pte_numa. numa hinting faults will gather statistics and migrate
     * pages to new nodes if necessary.
     */
    unsigned long numa_next_scan;

    /* restart point for scanning and setting pte_numa */
    unsigned long numa_scan_offset;

    /* numa_scan_seq prevents two threads setting pte_numa */
    int numa_scan_seq;
#endif
    /*
     * an operation with batched tlb flushing is going on. anything that
     * can move process memory needs to flush the tlb when moving a
     * prot_none or prot_numa mapped page.
     */
    atomic_t tlb_flush_pending;
#ifdef config_arch_want_batched_unmap_tlb_flush
    /* see flush_tlb_batched_pending() */
    bool tlb_flush_batched;
#endif
    struct uprobes_state uprobes_state;
#ifdef config_hugetlb_page
    atomic_long_t hugetlb_usage;
#endif
    struct work_struct async_put_work;

#if is_enabled(config_hmm)
    /* hmm needs to track a few things per mm */
    struct hmm *hmm;
#endif
} __randomize_layout;
  • struct vm_area_struct
    用于描述进程地址空间中的一段虚拟区域,每一个vma都对应一个struct vm_area_struct
/*
 * this struct defines a memory vmm memory area. there is one of these
 * per vm-area/task.  a vm area is any part of the process virtual memory
 * space that has a special rule for the page-fault handlers (ie a shared
 * library, the executable area etc).
 */
struct vm_area_struct {
    /* the first cache line has the info for vma tree walking. */

    unsigned long vm_start;     /* our start address within vm_mm. */       //起始地址
    unsigned long vm_end;       /* the first byte after our end address
                       within vm_mm. */         //结束地址,区间中不包含结束地址

    /* linked list of vm areas per task, sorted by address */       //按起始地址排序的链表
    struct vm_area_struct *vm_next, *vm_prev;

    struct rb_node vm_rb;       //红黑树节点

    /*
     * largest free memory gap in bytes to the left of this vma.
     * either between this vma and vma->vm_prev, or between one of the
     * vmas below us in the vma rbtree and its ->vm_prev. this helps
     * get_unmapped_area find a free area of the right size.
     */
    unsigned long rb_subtree_gap;

    /* second cache line starts here. */

    struct mm_struct *vm_mm;    /* the address space we belong to. */
    pgprot_t vm_page_prot;      /* access permissions of this vma. */
    unsigned long vm_flags;     /* flags, see mm.h. */

    /*
     * for areas with an address space and backing store,
     * linkage into the address_space->i_mmap interval tree.
     */
    struct {
        struct rb_node rb;
        unsigned long rb_subtree_last;
    } shared;

    /*
     * a file's map_private vma can be in both i_mmap tree and anon_vma
     * list, after a cow of one of the file pages.  a map_shared vma
     * can only be in the i_mmap tree.  an anonymous map_private, stack
     * or brk vma (with null file) can only be in an anon_vma list.
     */
    struct list_head anon_vma_chain; /* serialized by mmap_sem &
                      * page_table_lock */
    struct anon_vma *anon_vma;  /* serialized by page_table_lock */

    /* function pointers to deal with this struct. */
    const struct vm_operations_struct *vm_ops;

    /* information about our backing store: */
    unsigned long vm_pgoff;     /* offset (within vm_file) in page_size
                       units */
    struct file * vm_file;      /* file we map to (can be null). */     //指向文件的一个打开实例
    void * vm_private_data;     /* was vm_pte (shared mem) */

    atomic_long_t swap_readahead_info;
#ifndef config_mmu
    struct vm_region *vm_region;    /* nommu mapping region */
#endif
#ifdef config_numa
    struct mempolicy *vm_policy;    /* numa policy for the vma */
#endif
    struct vm_userfaultfd_ctx vm_userfaultfd_ctx;
} __randomize_layout;

关系图来了:
【原创】(十三)Linux内存管理之vma/malloc/mmap

是不是有点眼熟?这个跟内核中的vmap机制很类似。

宏观的看一下进程地址空间中的各个vma
【原创】(十三)Linux内存管理之vma/malloc/mmap

针对vma的操作,有如下接口:

/*  vma的查找 */
/* look up the first vma which satisfies  addr < vm_end,  null if none. */
extern struct vm_area_struct * find_vma(struct mm_struct * mm, unsigned long addr); //查找第一个满足addr < vm_end的vma块
extern struct vm_area_struct * find_vma_prev(struct mm_struct * mm, unsigned long addr,
                         struct vm_area_struct **pprev); //与find_vma功能类似,不同之处在于还会返回vma链接的前一个vma;
 static inline struct vm_area_struct * find_vma_intersection(struct mm_struct * mm, unsigned long start_addr, unsigned long end_addr); //查找与start_addr~end_addr区域有交集的vma
 
 /* vma的插入 */
 extern int insert_vm_struct(struct mm_struct *, struct vm_area_struct *); //插入vma到红黑树中和链表中
 
 /* vma的合并 */
 extern struct vm_area_struct *vma_merge(struct mm_struct *,
    struct vm_area_struct *prev, unsigned long addr, unsigned long end,
    unsigned long vm_flags, struct anon_vma *, struct file *, pgoff_t,
    struct mempolicy *, struct vm_userfaultfd_ctx); //将vma与附近的vma进行融合操作
 
 /* vma的拆分 */
 extern int split_vma(struct mm_struct *, struct vm_area_struct *,
    unsigned long addr, int new_below); //将vma以addr为界线分成两个vma

上述的操作基本上也就是针对红黑树的操作。

3. malloc

malloc大家都很熟悉,那么它是怎么与底层去交互并申请到内存的呢?

图来了:
【原创】(十三)Linux内存管理之vma/malloc/mmap

如图所示,malloc最终会调到底层的sys_brk函数和sys_mmap函数,在分配小内存时调用sys_brk函数,动态的调整进程地址空间中的brk位置;在分配大块内存时,调用sys_mmap函数,在堆和栈之间找到一片区域进行映射处理。

先来看sys_brk函数,通过syscall_define1来定义,整体的函数调用流程如下:

【原创】(十三)Linux内存管理之vma/malloc/mmap

从函数的调用过程中可以看出有不少操作是针对vma的,那么结合起来的效果图如下:

【原创】(十三)Linux内存管理之vma/malloc/mmap

整个过程看起来就比较清晰和简单了,每个进程都用struct mm_struct来描述自身的进程地址空间,这些空间都是一些vma区域,通过一个红黑树和链表来管理。因此针对malloc的处理,会去动态的调整brk的位置,具体的大小则由struct vm_area_struct结构中的vm_start ~ vm_end来指定。在实际过程中,会根据请求分配区域是否与现有vma重叠的情况来进行处理,或者重新申请一个vma来描述这段区域,并最终插入到红黑树和链表中。

完成这段申请后,只是开辟了一段区域,通常还不会立马分配物理内存,物理内存的分配会发生在访问时出现缺页异常后再处理,这个后续也会有文章来进一步分析。

4. mmap

mmap用于内存映射,也就是将一段区域映射到自己的进程地址空间中,分为两种:

  • 文件映射: 将文件区域映射到进程空间,文件存放在存储设备上;
  • 匿名映射:没有文件对应的区域映射,内容存放在物理内存上;

同时,针对其他进程是否可见,又分为两种:

  • 私有映射:将数据源拷贝副本,不影响其他进程;
  • 共享映射:共享的进程都能看到;

根据排列组合,就存在以下几种情况了:

  1. 私有匿名映射: 通常分配大块内存时使用,堆,栈,bss段等;
  2. 共享匿名映射:常用于父子进程间通信,在内存文件系统中创建/dev/zero设备;
  3. 私有文件映射:常用的比如动态库加载,代码段,数据段等;
  4. 共享文件映射:常用于进程间通信,文件读写等;

常见的prot权限和flags如下:

#define prot_read   0x1     /* page can be read */
#define prot_write  0x2     /* page can be written */
#define prot_exec   0x4     /* page can be executed */
#define prot_sem    0x8     /* page may be used for atomic ops */
#define prot_none   0x0     /* page can not be accessed */
#define prot_growsdown  0x01000000  /* mprotect flag: extend change to start of growsdown vma */
#define prot_growsup    0x02000000  /* mprotect flag: extend change to end of growsup vma */

#define map_shared  0x01        /* share changes */
#define map_private 0x02        /* changes are private */
#define map_type    0x0f        /* mask for type of mapping */
#define map_fixed   0x10        /* interpret addr exactly */
#define map_anonymous   0x20        /* don't use a file */

#define map_growsdown   0x0100      /* stack-like segment */
#define map_denywrite   0x0800      /* etxtbsy */
#define map_executable  0x1000      /* mark it as an executable */
#define map_locked  0x2000      /* pages are locked */
#define map_noreserve   0x4000      /* don't check for reservations */
#define map_populate    0x8000      /* populate (prefault) pagetables */
#define map_nonblock    0x10000     /* do not block on io */
#define map_stack   0x20000     /* give out an address that is best suited for process/thread stacks */
#define map_hugetlb 0x40000     /* create a huge page mapping */

mmap的操作,最终会调用到do_mmap函数,最后来一张调用图:

【原创】(十三)Linux内存管理之vma/malloc/mmap

【原创】(十三)Linux内存管理之vma/malloc/mmap