Linux内核中的内存管理浅谈

转自jasonblog http://blog.csdn.net/jasonblog/article/details/4848977


1。基本框架(此处主要谈页式内存管理)

4G是一个比较敏感的字眼,早些日子,大多数机器(或者说操作系统)支持的内存上限都是这个数字。为什么呢?

之所以说是早些日子,因为现在64位的计算机已经很多了,而对于32位的计算机而言,页式管理是这么进行的,逻辑地址格式如下:

0 11位:页内偏移OFFSET

1221位:页面表偏移PT

2231位:页面目录偏移PGD

寻址过程如下:

    1)操作系统从寄存器CR3获得当前页面目录指针(基地址);

    2)基地址+页面目录偏移->页面表指针(基地址);

    3)页面表指针+页面表偏移->内存页基址;

    4)内存页基址+页内偏移->具体物理内存单元。

显然,12位的页内偏移可以寻址4K,所以一张内存页为4K;而总共可寻内存为4G2^10 * 2^10 * 2^12;因此在32位机器上内存上限一般为4G

 

而操作系统是需要支持不同的平台的,比如32位,比如64位等。所以,linux统一使用页式三层映射:PGDPMDPTOFFSET

PAE是地址扩充功能(Physical Address Extension)的缩写,如果将内存管理设置为PAE模式,这时候就需要三层映射了。

 

三层映射架构是如何实现双层映射的?linux在暗地里“弄虚作假”了一番,有点类似领导让linux给三层映射一个重要位置,但是在32位计算机的地盘里就“阳奉阴违”了,只给三层映射一个有名无权的虚职。那么这个虚职是怎么实现的呢?

首先,开启了PAE模式的计算机是真切需要三层映射的,所以它不会给三层映射虚职,而是需要三层映射机制去做实事的;而32位计算机如果没有开启PAE模式,那么它是不需要三层映射的,双层映射是它更喜欢的。所以,首先是判断什么情况下给三层映射虚职——

  1. 109/* 
  2. 110 * The Linux x86 paging architecture is ‘compile-time dual-mode’, it 
  3. 111 * implements both the traditional 2-level x86 page tables and the 
  4. 112 * newer 3-level PAE-mode page tables. 
  5. 113 */  
  6. 114#ifndef __ASSEMBLY__  
  7. 115#if CONFIG_X86_PAE  
  8. 116# include <asm/pgtable-3level.h>  
  9. 117  
  10. 118/* 
  11. 119 * Need to initialise the X86 PAE caches 
  12. 120 */  
  13. 121extern void pgtable_cache_init(void);  
  14. 122  
  15. 123#else  
  16. 124# include <asm/pgtable-2level.h>  

从第一段的注释说明我们可以知道Linux x86的页式映射机制在编译时可以选择使用传统的双层映射和新的 PAE 模式下的三层映射。而从接下来的代码可以知道,如果对 CONFIG_X86_PAE进行了预处理,即开启了 PAE 模式,那么就使用 pgtable-3level.h ,并且对 X86 PAE caches 进行初始化,而如果没有,则包含 pgtable-2level.h ,即使用双层映射。

 

pgtable-2level.h实现的双层映射:

  1. 4/* 
  2. 5 * traditional i386 two-level paging structure: 
  3. 6 */  
  4. 7  
  5. 8#define PGDIR_SHIFT 22  
  6. 9#define PTRS_PER_PGD 1024  
  7. 10  
  8. 11/* 
  9. 12 * the i386 is two-level, so we don’t really have any 
  10. 13 * PMD directory physically. 
  11. 14 */  
  12. 15#define PMD_SHIFT 22  
  13. 16#define PTRS_PER_PMD 1  

11行到14行的注释我们可以知道这里并没有让PMD实际存在。 PGDIR_SHIFT PGD 的偏移量——这里的偏移量是指位于 32 位中的几位,显然是 22 位,即第 23 位。而

PTRS_PER_PGDpointers per PGD,即每个PGD 位段能表示的指针。这里是 1024 ,显然需要 10 位,那么 PGD 就是从位 22 到位 31 ,即第 23 位到第 32 位。

于是很显然我们可以了解到PMD在这里是虚设的,挂了个虚职。因为 PTRS_PER_PMD 1 ,那么占用的是 0 位,因为 2^0 = 1

到这里,我们知道什么人的地盘上给三层映射挂虚职,怎么设置这个虚职的。而三层映射如果真干起了实事,本质其实和双层映射差不多,只不过多了几个位而已。

 

————————————–cut-line

 

1.数据结构和函数

众所周知,linux下有许多与 ANSI C 不同的数据类型,比如 pid_t ;这些类型实际上是通过一层或者若干层的 typedef 定义而实现的,这样做的一个主要原因是为了可移植性的实现,而这样做的影响是看类型即可以很直观地知道用于何处,比如pid_t 显然是一个进程 id 的类型;另外一个影响便是,编译内核需要使用相应的 gcc 编译器。

 

那么,在内存管理(1)中提到的 PGD PMD PT 等是什么呢?在 include/asm-i386/page.h 中有如下代码:

  1. 36/* 
  2. 37 * These are used to make use of C type-checking.. 
  3. 38 */  
  4. 39#if CONFIG_X86_PAE  
  5. 40typedef struct { unsigned long pte_low, pte_high; } pte_t;  
  6. 41typedef struct { unsigned long long pmd; } pmd_t;  
  7. 42typedef struct { unsigned long long pgd; } pgd_t;  
  8. 43#define pte_val(x) ((x).pte_low | ((unsigned long long)(x).pte_high << 32))  

在开启了PAE模式的情况下, pgd_t pmd_t 都是长整形变量,而 pte_t 分为 pte_low pte_high 两个部分。 PTE 是指 page table entry ,即某个具体的页表项,指向一张具体的内存页。但是一个内存页并不需要32位全部使用,因为每张内存页大小都为4KB ,所以从地址 0 开始,每间隔 4KB 为一张内存页。所以,内存页的首地址的低 12 位都为 0 ,我们只需要高 20 位来指向一个内存页基址,低 12 位用来设置页面状态和权限。另外,还有一个宏用来读取 pte_t 类型的成员。

而没有开启PAE模式的情况如下:

  1. 44#else  
  2. 45typedef struct { unsigned long pte_low; } pte_t;  
  3. 46typedef struct { unsigned long pmd; } pmd_t;  
  4. 47typedef struct { unsigned long pgd; } pgd_t;  
  5. 48#define pte_val(x) ((x).pte_low)  
  6. 49#endif  

 

有了PMD等结构后就有地方存储地址信息了,那么如何获取这些信息呢?见如下几个宏:

  1. 54#define pmd_val(x) ((x).pmd)  
  2. 55#define pgd_val(x) ((x).pgd)  
  3. 56#define pgprot_val(x) ((x).pgprot)  
  4. 57  
  5. 58#define __pte(x) ((pte_t) { (x) } )  
  6. 59#define __pmd(x) ((pmd_t) { (x) } )  
  7. 60#define __pgd(x) ((pgd_t) { (x) } )  
  8. 61#define __pgprot(x) ((pgprot_t) { (x) } )  

54 行到 56 行是读取成员变量的宏,而 58 行到 61 行则是进行类型转换。这里出现了一个 pgprot ,展开为 page protection ,页面保护。 pgprot 对应着上文提到的页面状态和权限,从而实现页面的保护机制:

  1. 52typedef struct { unsigned long pgprot; } pgprot_t;  

 

具体的pgprot_t /include/asm-i386/pgtable.h中定义:

  1. 187#define _PAGE_PRESENT 0×001  
  2. 188#define _PAGE_RW 0×002  
  3. 189#define _PAGE_USER 0×004  
  4. 190#define _PAGE_PWT 0×008  
  5. 191#define _PAGE_PCD 0×010  
  6. 192#define _PAGE_ACCESSED 0×020  
  7. 193#define _PAGE_DIRTY 0×040  
  8. 194#define _PAGE_PSE 0×080 /* 4 MB (or 2MB) page, Pentium+, if present.. */  
  9. 195#define _PAGE_GLOBAL 0×100 /* Global TLB entry PPro+ */  
  10. 196  
  11. 197#define _PAGE_PROTNONE 0×080 /* If not present */  

显然,pgprot_t的位设置都是在低 12 位,而 PTE 的指针部分是高 20 位,共同构成了 32 位。那么,二者是如何构成 32 位的页面表表项呢?我们自然而然想到了 20 位左移 12 位再与 pgprot_t 的低 12 位相或,在 pgtable.h 中是由宏 mk_pte 来完成的:

  1. 309#define mk_pte(page, pgprot) __mk_pte((page) - mem_map, (pgprot))  

而我们自然又遇到了__mk_pte。那么 __mk_pte 是什么呢?在 /include/asm-i386/pgtable-2level.h中它一个宏:

  1. 63#define __mk_pte(page_nr,pgprot) __pte(((page_nr) << PAGE_SHIFT) | pgprot_val(pgprot))  

以上为63行单行。而在/include/asm-i386/page.h中对 PAGE_SHIFT进行了宏定义:

  1. 5#define PAGE_SHIFT 12   

所以实现的是将内存页面编号左移12位再与保护字段pgprot相或得到了 pte 页面表项。另外在上述中出现了 __pte() ,它的原型为: 58#define __pte(x) ((pte_t) { (x) } ),即进行类型转换。而pgprot_val(pgprot) 的原型为: 56#define pgprot_val(x) ((x).pgprot),与52typedef struct { unsigned long pgprot; } pgprot_t;相对应则易知是获得某个pgprot_t 类型变量的成员变量 pgprot

最后就剩下一个mem_map了。我们先来了解一下 /include/linux/mm.h 中的 page 结构。

首先,先看一段前置说明:

  1. 139/* 
  2. 140 * Each physical page in the system has a struct page associated with 
  3. 141 * it to keep track of whatever it is we are using the page for at the 
  4. 142 * moment. Note that we have no way to track which tasks are using 
  5. 143 * a page. 
  6. 144 * 
  7. 145 * Try to keep the most commonly accessed fields in single cache lines 
  8. 146 * here (16 bytes or greater). This ordering should be particularly 
  9. 147 * beneficial on 32-bit processors. 
  10. 148 * 
  11. 149 * The first line is data used in page cache lookup, the second line 
  12. 150 * is used for linear searches (eg. clock algorithm scans). 
  13. 151 * 
  14. 152 * TODO: make this structure smaller, it could be as small as 32 bytes. 
  15. 153 */   

简略说下,就是page结构是与物理内存页相联系的,从而进行状态跟踪;其次,最经常访问的结构体内的成员字段应该保持在16 位或者更大的单条缓冲线上——显然,这样有利于高速访问。接着来看page结构体的定义:

  1. 154typedef struct page {  
  2. 155 struct list_head list; /* ->mapping has some page lists. */  
  3. 156 struct address_space *mapping; /* The inode (or …) we belong to. */  
  4. 157 unsigned long index; /* Our offset within mapping. */  
  5. 158 struct page *next_hash; /* Next page sharing our hash bucket in 
  6. 159 the pagecache hash table. */  
  7. 160 atomic_t count; /* Usage count, see below. */  
  8. 161 unsigned long flags; /* atomic flags, some possibly 
  9. 162 updated asynchronously */  
  10. 163 struct list_head lru; /* Pageout list, eg. active_list; 
  11. 164 protected by pagemap_lru_lock !! */  
  12. 165 struct page **pprev_hash; /* Complement to *next_hash. */  
  13. 166 struct buffer_head * buffers; /* Buffer maps us to a disk block. */  
  14. 167  
  15. 168 /* 
  16. 169 * On machines where all RAM is mapped into kernel address space, 
  17. 170 * we can simply calculate the virtual address. On machines with 
  18. 171 * highmem some memory is mapped into kernel virtual memory 
  19. 172 * dynamically, so we need a place to store that address. 
  20. 173 * Note that this field could be 16 bits on x86 … ;) 
  21. 174 * 
  22. 175 * Architectures with slow multiplication can define 
  23. 176 * WANT_PAGE_VIRTUAL in asm/page.h 
  24. 177 */  
  25. 178#if defined(CONFIG_HIGHMEM) || defined(WANT_PAGE_VIRTUAL)  
  26. 179 void *virtual/* Kernel virtual address (NULL if 
  27. 180 not kmapped, ie. highmem) */  
  28. 181#endif /* CONFIG_HIGMEM || WANT_PAGE_VIRTUAL */  
  29. 182} mem_map_t;   

当我们看到最后一行(182行)的时候会有种恍然大悟的感觉—— mem_map_t。于是我们就会联想 mem_map 是这么一个类型的变量。

实际上,mem_map是一个全局变量(目前为止是),而且是一个指向 page 结构数组的指针;系统在初始化时根据物理内存的大小创建该数组。每一个数组元素都对应一张物理内存页。从软件方面来讲,页面表项的高20 位是物理页面的编号,即mem_map 数组的索引下标,通过该下标可以访问到与物理页面对应的page 结构。而从硬件方面来讲,页面表项的高 20 位再与 12 0 结合则构成了 32 位,即每张物理页面的基址。

 

mem_map 映射着全部的物理内存页,而其本身则分为不同的区,比如 ZONE_DMAZONE_NORMALZONE_HIGHMEM等。其中ZONE_DMA 是供 DMA 使用的; ZONE_HIGHMEM 是用于处理物理地址超过 1G 的存储空间。

事实上,三个管理区是这么分配的:016MB分配给 ZONE_DMA 16 896MB分配给 ZONE_NORMAL ,最后, 896MB 以上的分配给 ZONE_HIGHMEM 。那么,为什么要这么分配呢?这是由于某些硬件只能特定地访问0 16MB来执行DMA 模式;有些机器的配置使得物理内存页面无法总是保持被内核地址映射,这时需要使用ZONE_HIGHMEM进行动态映射;而其余的就是可以被正常映射的。

那么,为什么这里是896MB呢,而不是上文提的 1GB ?这是由于内核不仅为 highmem 预留了空间,也为 fixmap vmalloc 预留了虚存空间。

OK ,那内核中的虚拟地址是什么?虚拟地址其实就是逻辑地址——与物理地址相对应。

我们不妨来看看物理地址和内核中虚拟地址在内核空间的关系:

  1. 128#define PAGE_OFFSET ((unsigned long)__PAGE_OFFSET)  
  2. …  
  3. 132#define __pa(x) ((unsigned long)(x)-PAGE_OFFSET)  
  4. 133#define __va(x) ((void *)((unsigned long)(x)+PAGE_OFFSET))   

pa 表示 physical address ,即物理地址,而 va 表示虚拟地址 virtual address 。这里,我们不得不去看看 __PAGE_OFFSET

  1. 68/* 
  2. 69 * This handles the memory map.. We could make this a config 
  3. 70 * option, but too many people screw it up, and too few need 
  4. 71 * it. 
  5. 72 * 
  6. 73 * A __PAGE_OFFSET of 0xC0000000 means that the kernel has 
  7. 74 * a virtual address space of one gigabyte, which limits the 
  8. 75 * amount of physical memory you can use to about 950MB. 
  9. 76 * 
  10. 77 * If you want more physical memory than this then see the CONFIG_HIGHMEM4G 
  11. 78 * and CONFIG_HIGHMEM64G options in the kernel configuration. 
  12. 79 */  
  13. 80  
  14. 81#define __PAGE_OFFSET (0xC0000000)   

前置注释有一堆,而宏定义只有一行。在32位机器上,通过linux内核的页式映射可以实现 4GB 的逻辑地址(虚拟地址)。而在 4G 字节中, 0xC0000000 0xFFFFFFFF 的这 1G 最高的逻辑地址用于内核本身,称之为“内核空间”;而较低的 3G 字节空间为用户空间。注意,这里的是虚的、逻辑地址。

于是我们知道了__PAGE_OFFSET是用户空间和内核空间在虚地址上的分界。然而,物理地址始终是从 0×00000000开始的;所以对于内核空间来说, pa va 就相差了一个 PAGE_OFFSET 。而同时, PAGE_OFFSET 也代表着用户空间的上限。

到这里,我们了解了内核空间只能“线性映射”1GB“的物理地址,如果没有 ZONE_HIGHMEM 来管理高于 1GB 的物理地址,那么这些内存就会浪费掉了。于是系统初始化时预留了128MB的虚存来用于将来可能的映射。以上是对于x86 体系结构而言,对于其它体系,物理内存可以全部被映射, ZONE_HIGHMEM为空。

 

现在回到内存管理区。/include/linux/mmzone.h中有如下数据结构用于管理区:

(代码有点长,分段来看)

  1. 39/* 
  2. 40 * On machines where it is needed (eg PCs) we divide physical memory 
  3. 41 * into multiple physical zones. On a PC we have 3 zones: 
  4. 42 * 
  5. 43 * ZONE_DMA < 16 MB ISA DMA capable memory 
  6. 44 * ZONE_NORMAL 16-896 MB direct mapped by the kernel 
  7. 45 * ZONE_HIGHMEM > 896 MB only page cache and user processes 
  8. 46 */   

这里的前置注释说明了三个管理区的分布。

  1. 47typedef struct zone_struct {  
  2. 48 /* 
  3. 49 * Commonly accessed fields: 
  4. 50 */  
  5. 51 spinlock_t lock;  
  6. 52 unsigned long free_pages;  
  7. 这里是经常访问的字段。这里遇到了spinlock_t这个数据类型,在/include/asm-i386/spinlock.h中有定义:  
  8. 22/* 
  9. 23 * Your basic SMP spinlocks, allowing only a single CPU anywhere 
  10. 24 */  
  11. 25  
  12. 26typedef struct {  
  13. 27 volatile unsigned int lock;  
  14. 28#if SPINLOCK_DEBUG  
  15. 29 unsigned magic;  
  16. 30#endif  
  17. 31} spinlock_t;   

由注释我们可以知道这是用来控制SMP使用的,仅允许单 CPU 工作。

free_pages表示着该区目前拥有的空闲页数。

  1. 53 /* 
  2. 54 * We don’t know if the memory that we’re going to allocate will be freeable 
  3. 55 * or/and it will be released eventually, so to avoid totally wasting several 
  4. 56 * GB of ram we must reserve some of the lower zone memory (otherwise we risk 
  5. 57 * to run OOM on the lower zones despite there’s tons of freeable ram 
  6. 58 * on the higher zones). 
  7. 59 */  
  8. 60 zone_watermarks_t watermarks[MAX_NR_ZONES];   

由前置注释可知这是为了保留一些低端内存。我们在这里又遇到了一个新的数据类型:

  1. 34typedef struct zone_watermarks_s {  
  2. 35 unsigned long min, low, high;  
  3. 36} zone_watermarks_t;  
  4. 62 /* 
  5. 63 * The below fields are protected by different locks (or by 
  6. 64 * no lock at all like need_balance), so they’re longs to 
  7. 65 * provide an atomic granularity against each other on 
  8. 66 * all architectures. 
  9. 67 */  
  10. 68 unsigned long need_balance;  
  11. 69 /* protected by the pagemap_lru_lock */  
  12. 70 unsigned long nr_active_pages, nr_inactive_pages;  
  13. 71 /* protected by the pagecache_lock */  
  14. 72 unsigned long nr_cache_pages;  
  15. 75 /* 
  16. 76 * free areas of different sizes 
  17. 77 */  
  18. 78 free_area_t free_area[MAX_ORDER];  
  19. 引入free_area_t:  
  20. 27typedef struct free_area_struct {  
  21. 28 struct list_head free_list;  
  22. 29 unsigned long *map;  
  23. 30} free_area_t;  

这里free_area[MAX_ORDER]是一组队列,用于分配不连续的内存块。队列的实现是通过 free_area_t类型中的成员 struct list_head free_list ,可参加 list.h

  1. 80 /* 
  2. 81 * wait_table — the array holding the hash table 
  3. 82 * wait_table_size — the size of the hash table array 
  4. 83 * wait_table_shift — wait_table_size 
  5. 84 * == BITS_PER_LONG (1 << wait_table_bits) 
  6. 85 * 
  7. 86 * The purpose of all these is to keep track of the people 
  8. 87 * waiting for a page to become available and make them 
  9. 88 * runnable again when possible. The trouble is that this 
  10. 89 * consumes a lot of space, especially when so few things 
  11. 90 * wait on pages at a given time. So instead of using 
  12. 91 * per-page waitqueues, we use a waitqueue hash table. 
  13. 92 * 
  14. 93 * The bucket discipline is to sleep on the same queue when 
  15. 94 * colliding and wake all in that wait queue when removing. 
  16. 95 * When something wakes, it must check to be sure its page is 
  17. 96 * truly available, a la thundering herd. The cost of a 
  18. 97 * collision is great, but given the expected load of the 
  19. 98 * table, they should be so rare as to be outweighed by the 
  20. 99 * benefits from the saved space. 
  21. 100 * 
  22. 101 * __wait_on_page() and unlock_page() in mm/filemap.c, are the 
  23. 102 * primary users of these fields, and in mm/page_alloc.c 
  24. 103 * free_area_init_core() performs the initialization of them. 
  25. 104 */  
  26. 105 wait_queue_head_t * wait_table;  
  27. 106 unsigned long wait_table_size;  
  28. 107 unsigned long wait_table_shift;   

一些管理区信息如下:

  1. 109 /* 
  2. 110 * Discontig memory support fields. 
  3. 111 */  
  4. 112 struct pglist_data *zone_pgdat;  
  5. 113 struct page *zone_mem_map;  
  6. 114 unsigned long zone_start_paddr;  
  7. 115 unsigned long zone_start_mapnr;   

112 表示的是该管理区所在的存储节点; 113 显然是一张内存映射表; 114 是该管理区的物理起始地址,而 115 表示的是在 mem_map 中的起始下标。显然这些都可以直接从变量名看出来。

  1. 117 /* 
  2. 118 * rarely used fields: 
  3. 119 */  
  4. 120 char *name;  
  5. 121 unsigned long size;  
  6. 122 unsigned long realsize;  
  7. 123} zone_t;   

120 表示的是管理区的名字, 121 表示的是管理区的大小, 122 表示的是管理区实用大小。

 

当多CPU引入之后, NUMA(Non-Uniform Memory Architecture)结构体系出现了,即非匀质存储结构。于是,每个CPU 都有自己的物理地址,并且有一个公共的物存模块。这样有时候会出现CPU请求的内存块无法在自己管辖的物理地址模块获得,也不能手伸太长去其它 CPU管理的模块,那么就需要到公共模块请求。同时,新的物理页面管理机制也进行了修正。

NUMA下,我们称 CPU 请求的一片连续物理内存页为 node (节点)。而且,此时的 mem_map 不再是全局变量,而是从属于具体节点;管理区也不再高高在上,也是被节点所拥有,每个存储节点至少有两个管理区。从而在zone_struct 上便有了 pglist_data 数据结构,在 /include/linux/mmzone.h 定义:

  1. 142/* 
  2. 143 * The pg_data_t structure is used in machines with CONFIG_DISCONTIGMEM 
  3. 144 * (mostly NUMA machines?) to denote a higher-level memory zone than the 
  4. 145 * zone_struct denotes. 
  5. 146 * 
  6. 147 * On NUMA machines, each NUMA node would have a pg_data_t to describe 
  7. 148 * it’s memory layout. 
  8. 149 * 
  9. 150 * XXX: we need to move the global memory statistics (active_list, …) 
  10. 151 * into the pg_data_t to properly support NUMA. 
  11. 152 */  
  12. 153struct bootmem_data;  
  13. 154typedef struct pglist_data {  
  14. 155 zone_t node_zones[MAX_NR_ZONES];  
  15. 156 zonelist_t node_zonelists[GFP_ZONEMASK+1];  
  16. 157 int nr_zones;  
  17. 158 struct page *node_mem_map;  
  18. 159 unsigned long *valid_addr_bitmap;  
  19. 160 struct bootmem_data *bdata;  
  20. 161 unsigned long node_start_paddr;  
  21. 162 unsigned long node_start_mapnr;  
  22. 163 unsigned long node_size;  
  23. 164 int node_id;  
  24. 165 struct pglist_data *node_next;  
  25. 166} pg_data_t;   

首先看看158 struct page *node_mem_map,由于每个节点有一片的内存页,这里的 node_mem_map 便是用来映射表示它们的( page 结构数组);接着看首行, 155 zone_t node_zones[MAX_NR_ZONES]是该节点所拥有的管理区,同时在zone_struct 也有一行 struct pglist_data *zone_pgdat,指向所属节点pglist_data数据结构。

 

————————————–cut-line –以上数据结构用于物理内存页面管理–2009-04-20

 

————————————–cut-line

 

(续)数据结构和函数

现在开始接触的是用于虚存管理的数据结构和函数。

通常,一个进程所需要使用的虚存空间是离散的各个区间,而区间的数据结构是/include/linux/mm.h中定义的:

  1. 38/* 
  2. 39 * This struct defines a memory VMM memory area. There is one of these 
  3. 40 * per VM-area/task. A VM area is any part of the process virtual memory 
  4. 41 * space that has a special rule for the page-fault handlers (ie a shared 
  5. 42 * library, the executable area etc). 
  6. 43 */  
  7. 44struct vm_area_struct {  
  8. 45 struct mm_struct * vm_mm; /* The address space we belong to. */  
  9. 46 unsigned long vm_start; /* Our start address within vm_mm. */  
  10. 47 unsigned long vm_end; /* The first byte after our end address 
  11. 48 within vm_mm. */  
  12. 49  
  13. 50 /* linked list of VM areas per task, sorted by address */  
  14. 51 struct vm_area_struct *vm_next;  
  15. 52  
  16. 53 pgprot_t vm_page_prot; /* Access permissions of this VMA. */  
  17. 54 unsigned long vm_flags; /* Flags, listed below. */  
  18. 55  
  19. 56 rb_node_t vm_rb;  
  20. 57  
  21. 58 /* 
  22. 59 * For areas with an address space and backing store, 
  23. 60 * one of the address_space->i_mmap{,shared} lists, 
  24. 61 * for shm areas, the list of attaches, otherwise unused. 
  25. 62 */  
  26. 63 struct vm_area_struct *vm_next_share;  
  27. 64 struct vm_area_struct **vm_pprev_share;  
  28. 65  
  29. 66 /* Function pointers to deal with this struct. */  
  30. 67 struct vm_operations_struct * vm_ops;  
  31. 68  
  32. 69 /* Information about our backing store: */  
  33. 70 unsigned long vm_pgoff; /* Offset (within vm_file) in PAGE_SIZE 
  34. 71 units, *not* PAGE_CACHE_SIZE */  
  35. 72 struct file * vm_file; /* File we map to (can be NULL). */  
  36. 73 unsigned long vm_raend; /* XXX: put full readahead info here. */  
  37. 74 void * vm_private_data; /* was vm_pte (shared mem) */  
  38. 75};   

45 行是定义了一个指向 mm_struct 结构体的指针,该结构体稍后了解。 vm_start vm_end 是这一段 vm_area 的开始和结束位置,然而 vm_end 是该 vm_area 之后的第一个地址,不属于本 vm_area

51 行定义了一个指向 vm_area_struct 结构体的指针 vm_next 。这是由于进程使用的区间是离散的,所以各个区间需要形成链表来保持联系,这里的 vm_next 便是指向下一片 vm_area 的;该链表是按地址排序的。

53 行的 pgprot_t vm_page_prot 显然是本 vm_area 的保护信息, pgprot_t 在之前有谈过。

54 行的 vm_flags 是本 vm_area 的标志,如下:

  1. 77/* 
  2. 78 * vm_flags.. 
  3. 79 */  
  4. 80#define VM_READ 0×00000001 /* currently active flags */  
  5. 81#define VM_WRITE 0×00000002  
  6. 82#define VM_EXEC 0×00000004  
  7. 83#define VM_SHARED 0×00000008  
  8. 84  
  9. 85#define VM_MAYREAD 0×00000010 /* limits for mprotect() etc */  
  10. 86#define VM_MAYWRITE 0×00000020  
  11. 87#define VM_MAYEXEC 0×00000040  
  12. 88#define VM_MAYSHARE 0×00000080  
  13. 89  
  14. 90#define VM_GROWSDOWN 0×00000100 /* general info on the segment */  
  15. 91#define VM_GROWSUP 0×00000200  
  16. 92#define VM_SHM 0×00000400 /* shared memory area, don’t swap out */  
  17. 93#define VM_DENYWRITE 0×00000800 /* ETXTBSY on write attempts.. */  
  18. 94  
  19. 95#define VM_EXECUTABLE 0×00001000  
  20. 96#define VM_LOCKED 0×00002000  
  21. 97#define VM_IO 0×00004000 /* Memory mapped I/O or similar */  
  22. 98  
  23. 99 /* Used by sys_madvise() */  
  24. 100#define VM_SEQ_READ 0×00008000 /* App will access data sequentially */  
  25. 101#define VM_RAND_READ 0×00010000 /* App will not benefit from clustered reads */  
  26. 102  
  27. 103#define VM_DONTCOPY 0×00020000 /* Do not copy this vma on fork */  
  28. 104#define VM_DONTEXPAND 0×00040000 /* Cannot expand with mremap() */  
  29. 105#define VM_RESERVED 0×00080000 /* Don’t unmap it from swap_out */  
  30. 106  
  31. 107#ifndef VM_STACK_FLAGS  
  32. 108#define VM_STACK_FLAGS 0×00000177  
  33. 109#endif   

80 83行分别表示页是否可以被读、写、执行和共享。

85 88行表示可以对 80 83行的标志进行设置。

95 行表示该页含可执行代码。

96 行表示该页被锁。

其它标志均有注释。

在这里一般会有个疑惑,一个vm_area可能包含很多个内存页,为什么只有一个vm_page_protvm_flags呢?这是因为同一片vm_area的所有页面都必须保持相同的保护信息和状态标志。

现在回到vm_area_struct

56 行是 rb_node_t vm_rb; rb_node_t 是红黑树 (red-black tree) 节点类型。红黑树的结构如下:

  1. 100typedef struct rb_node_s  
  2. 101{  
  3. 102 struct rb_node_s * rb_parent;  
  4. 103 int rb_color;  
  5. 104#define RB_RED 0  
  6. 105#define RB_BLACK 1  
  7. 106 struct rb_node_s * rb_right;  
  8. 107 struct rb_node_s * rb_left;  
  9. 108}  
  10. 109rb_node_t;   

之所以使用红黑树是因为使用链表搜索的话每次都要从头开始,会影响效率。

63 64行为共享内存中的前后区间:

  1. 58 /* 
  2. 59 * For areas with an address space and backing store, 
  3. 60 * one of the address_space->i_mmap{,shared} lists, 
  4. 61 * for shm areas, the list of attaches, otherwise unused. 
  5. 62 */  
  6. 63 struct vm_area_struct *vm_next_share;  
  7. 64 struct vm_area_struct **vm_pprev_share;  
  8. 67行定义了一个vm_ops,指向的是一个vm_oprations_struct结构体,该结构体在/include/linux/mm.h有定义:  
  9. 128/* 
  10. 129 * These are the virtual MM functions - opening of an area, closing and 
  11. 130 * unmapping it (needed to keep files on disk up-to-date etc), pointer 
  12. 131 * to the functions called when a no-page or a wp-page exception occurs. 
  13. 132 */  
  14. 133struct vm_operations_struct {  
  15. 134 void (*open)(struct vm_area_struct * area);  
  16. 135 void (*close)(struct vm_area_struct * area);  
  17. 136 struct page * (*nopage)(struct vm_area_struct * area, unsigned long address, int unused);  
  18. 137};   

显然可见vm_ops是一个指针,可以执行操作函数作用在该 vm_area 上。其中 open close 用于打开、关闭虚存空间。而当请求页面不在内存中调用 nopage

vm_area_struct后面的成员都有注释。

 

————————————–cut-line

 

在了解vm_area_struct的开始,我们提到了 mm_struct

  1. 206struct mm_struct {  
  2. 207 struct vm_area_struct * mmap; /* list of VMAs */  
  3. 208 rb_root_t mm_rb;  
  4. 209 struct vm_area_struct * mmap_cache; /* last find_vma result */  
  5. 210 pgd_t * pgd;  
  6. 211 atomic_t mm_users; /* How many users with user space? */  
  7. 212 atomic_t mm_count; /* How many references to “struct mm_struct” (users count as 1) */  
  8. 213 int map_count; /* number of VMAs */  
  9. 214 struct rw_semaphore mmap_sem;  
  10. 215 spinlock_t page_table_lock; /* Protects task page tables and mm->rss */  
  11. 216  
  12. 217 struct list_head mmlist; /* List of all active mm’s. These are globally strung 
  13. 218 * together off init_mm.mmlist, and are protected 
  14. 219 * by mmlist_lock 
  15. 220 */  
  16. 221  
  17. 222 unsigned long start_code, end_code, start_data, end_data;  
  18. 223 unsigned long start_brk, brk, start_stack;  
  19. 224 unsigned long arg_start, arg_end, env_start, env_end;  
  20. 225 unsigned long rss, total_vm, locked_vm;  
  21. 226 unsigned long def_flags;  
  22. 227 unsigned long cpu_vm_mask;  
  23. 228 unsigned long swap_address;  
  24. 229  
  25. 230 unsigned dumpable:1;  
  26. 231  
  27. 232 /* Architecture-specific MM context */  
  28. 233 mm_context_t context;  
  29. 234};   

207 行的 mmap 指向虚存区间链表。

208 行是指向红黑树。

209 行的 mmap_cache 指向最后一次使用的虚存区间,因为虚存区间有若干个内存页,下一次请求的内存页很可能还在该区间。

210 行的 pgd 显然是进程的页面目录,当内核调度一个进程运行时,将该指针转换为物理地址并写入控制寄存器 CR3

211 行的 mm_users 表示用户空间中有多少用户。而 212 行的 mm_count 表示该 mm_count 结构的被引用数。

213 map_count 表示 vm_area 的个数。

214 215 是一些状态控制,进行诸如锁定等状态控制。

217 行是 mm_struct 链表。

余下部分用途较显然。

 

mm_users mm_count我们可以知道一个 mm_struct 允许被多个进程引用,但是一个进程只能使用一个mm_struct结构。

至此,我们了解到以下几点。

1 。虚存方面是由 vm_area_struct mm_struct 进行处理的。 32 位的计算机可以形成 4G 的虚存空间,其中 3 4G 的虚存空间用作内核空间,其余用作用户空间。 mm_struct 是用户空间抽象,位于虚存管理的高层。而 vm_area_struct则是从属于mm_struct 。一个进程允许有多个 vma ,这些虚存区间构成链表以及红黑树,在 vma 个数较少的时候使用链表操作,个数多的时候使用红黑树操作。mm_struct中的 mmap指向 vma链表,而 map_count 则指示有多少个 vma 。当一个进程进入运行时,进程所对应的 mm_struct 中的 pgd (页面目录)被写入控制寄存器 CR3 ,于是页式映射机制的源头 CR3 就有内容了。

2 。在 CR3 被设置以后,便可以进行页式映射了。负责将虚拟地址映射为物理地址的内存管理单元从 CR3 读出数据,然后结合 pgd 等内容完成映射。

 

此外,如果要通过进程的虚拟地址找到所属区间以及相应的vma结构可以使用 find_vma

  1. 666/* Look up the first VMA which satisfies addr < vm_end, NULL if none. */  
  2. 667struct vm_area_struct * find_vma(struct mm_struct * mm, unsigned long addr)  
  3. 668{  
  4. 669 struct vm_area_struct *vma = NULL;  
  5. 670  
  6. 671 if (mm) {  
  7. 672 /* Check the cache first. */  
  8. 673 /* (Cache hit rate is typically around 35%.) */  
  9. 674 vma = mm->mmap_cache;  
  10. 675 if (!(vma && vma->vm_end > addr && vma->vm_start <= addr)) {  
  11. 676 rb_node_t * rb_node;  
  12. 677  
  13. 678 rb_node = mm->mm_rb.rb_node;  
  14. 679 vma = NULL;  
  15. 680  
  16. 681 while (rb_node) {  
  17. 682 struct vm_area_struct * vma_tmp;  
  18. 683  
  19. 684 vma_tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);  
  20. 685  
  21. 686 if (vma_tmp->vm_end > addr) {  
  22. 687 vma = vma_tmp;  
  23. 688 if (vma_tmp->vm_start <= addr)  
  24. 689 break;  
  25. 690 rb_node = rb_node->rb_left;  
  26. 691 } else  
  27. 692 rb_node = rb_node->rb_right;  
  28. 693 }  
  29. 694 if (vma)  
  30. 695 mm->mmap_cache = vma;  
  31. 696 }  
  32. 697 }  
  33. 698 return vma;  
  34. 699}   

首先通过查找mmap_cache,如果不是,则在链表中或者红黑树中搜索。如果返回 0 ,表示还没有创建 vma ,这时候就需要创建一个新的虚存区间结构。

 

————————————–cut-line

 

1。越界访问

页式映射将虚拟地址转换成物理地址,并不是每次映射都是成功的,以下是几种失败的情况:

1 )映射过程中遇到 pgd 或者 pte 等项为空,映射没有建立

2 )物理页面不在内存中

3 )权限不符

于是就有相应的错误处理程序/arch/i386/mm/fault.c中的 do_page_fault()

  1. 130/* 
  2. 131 * This routine handles page faults. It determines the address, 
  3. 132 * and the problem, and then passes it off to one of the appropriate 
  4. 133 * routines. 
  5. 134 * 
  6. 135 * error_code: 
  7. 136 * bit 0 == 0 means no page found, 1 means protection fault 
  8. 137 * bit 1 == 0 means read, 1 means write 
  9. 138 * bit 2 == 0 means kernel, 1 means user-mode 
  10. 139 */  
  11. 140asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long error_code)  
  12. 141{   

由前置注释可知,错误码第0位为0表示页面不存在,1表示权限不符;第1位为0表示为读访问引起的错误,1表示写访问引起错误;第2位为0表示错误发生在内核态,1表示在用户态。

该页面错误处理机制需要两个参数,一个是regs指向错误前现场, error_code 如上。

  1. 151 /* get the address */  
  2. 152 __asm__(”movl %%cr2,%0″:”=r” (address));   

这两行是获得导致映射失败的线性地址,它存储在CR2中,由汇编语言实现。

接着首先是处理在内核空间发生的非权限不符错误:

  1. 160 /* 
  2. 161 * We fault-in kernel-space virtual memory on-demand. The 
  3. 162 * ‘reference’ page table is init_mm.pgd. 
  4. 163 * 
  5. 164 * NOTE! We MUST NOT take any locks for this case. We may 
  6. 165 * be in an interrupt or a critical region, and should 
  7. 166 * only copy the information from the master page table, 
  8. 167 * nothing more. 
  9. 168 * 
  10. 169 * This verifies that the fault happens in kernel space 
  11. 170 * (error_code & 4) == 0, and that the fault was not a 
  12. 171 * protection error (error_code & 1) == 0. 
  13. 172 */  
  14. 173 if (address >= TASK_SIZE && !(error_code & 5))  
  15. 174 goto vmalloc_fault;  
  16. 175  
  17. 176 mm = tsk->mm;  
  18. 177 info.si_code = SEGV_MAPERR;   

由前置注释可知if条件的判断保证了错误发生在内核空间,而且不是权限不符错误。这种错误转向vmalloc_fault处理,该处理机制也在内部定义。

接着处理的是中断或者进程映射未建立的情况:

  1. 179 /* 
  2. 180 * If we’re in an interrupt or have no user 
  3. 181 * context, we must not take the fault.. 
  4. 182 */  
  5. 183 if (in_interrupt() || !mm)  
  6. 184 goto no_context;   

在这段代码之下是一段有关于堆栈越界的处理。当用尽了本进程的堆栈空间后,如果再执行进栈操作,由于堆栈是从上往下延伸的,所以一般情况下会把数据写到(%esp-4)位置,如果是 32 字节操作则是 (%esp-32) 了。

  1. 188 vma = find_vma(mm, address);   

查找虚存区间。

如果没有找到:

  1. 189 if (!vma)  
  2. 190 goto bad_area;   

转向bad_area处理。

如果找到,且地址大于vma起始地址(非堆栈)则转向:

  1. 191 if (vma->vm_start <= address)  
  2. 192 goto good_area;   

而如果是堆栈,那么VM_GROWSDOWN标记为 1 ,当向下越界时,如果超过 %esp-32 那么就转向 bad_area 否则扩充堆栈,调用 expand_stack()

  1. 193 if (!(vma->vm_flags & VM_GROWSDOWN))  
  2. 194 goto bad_area;  
  3. 195 if (error_code & 4) {  
  4. 196 /* 
  5. 197 * accessing the stack below %esp is always a bug. 
  6. 198 * The “+ 32″ is there due to some instructions (like 
  7. 199 * pusha) doing post-decrement on the stack and that 
  8. 200 * doesn’t show up until later.. 
  9. 201 */  
  10. 202 if (address + 32 < regs->esp)  
  11. 203 goto bad_area;  
  12. 204 }  
  13. 205 if (expand_stack(vma, address))  
  14. 206 goto bad_area;   

但是并不是无限制地扩充堆栈的,每个进程都有限制,如果超过就跳转到bad_area。如果允许扩充,转向 good_area 继续完成新增页面对物理内存的映射。

具体的处理机制见/arch/i386/mm/fault.c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值