Skip to content

Commit cba4d81

Browse files
authored
Create 任务空间管理.md
1 parent a0849bc commit cba4d81

File tree

1 file changed

+329
-0
lines changed

1 file changed

+329
-0
lines changed

Diff for: 文章/任务空间管理.md

+329
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,329 @@
1+
## 一. 前言
2+
3+
  从本文开始,我们进入内存部分的学习。首先会接着前面的任务task_struct讲解任务空间管理结构体mm_struct,并简单介绍物理内存和虚拟内存的相关知识,关于详细的基础知识和概念可以参照CSAPP一书,这里不会做过多的赘述,而是默认在已了解其映射关系的基础上进行的学习。在后文中,会继续介绍物理内存的管理以及用户态和内核态的内存映射。
4+
5+
## 二. 基本概念梳理
6+
7+
* CPU、缓存、内存、主存的架构是源于越快的设备越贵,因此出于节约(qiong)考虑设计了多层架构,CPU中有了MMU
8+
* 物理内存有限,多进程共享物理内存存在安全问题,因此出现了虚拟内存的设计
9+
* 虚拟内存根据ELF的结构进行了相应的设计,存在堆、映射区、栈、数据段等部分
10+
* 考虑到虚拟内存的结构,出现了堆的申请即动态内存
11+
* 虚拟内存为每个进程分配单独的地址空间,映射到物理内存上执行,因此有了物理内存和虚拟内存的映射方法:页
12+
* 为了管理虚拟内存,出现了页表和多级页表
13+
* 为了加速映射,出现了CPU中的TLB
14+
* 为了满足共享的需求,出现了内存映射中的共享内存
15+
* 由于内存碎片的存在,出现了碎片管理的设计以及垃圾回收器
16+
17+
## 三. 进程内存管理
18+
  
19+
对于一个进程来说,需要考虑用户态和内核态两部分需要存储在内核内的各个结构
20+
21+
  用户态包括
22+
23+
* 代码段
24+
* 全局变量
25+
* 常量字符串
26+
* 函数栈,包括函数调用,局部变量,函数参数等
27+
* 堆:malloc 分配的内存等
28+
* 内存映射,如 glibc 的调用, glibc 的代码是以 so 文件的形式存在的,也需要放在内存里面。
29+
30+
  内核态包括
31+
32+
* 内核部分的代码
33+
* 内核中全局变量
34+
* task_struct
35+
* 内核栈
36+
* 在内核里面也有动态分配的内存
37+
* 虚拟地址到物理地址的映射表
38+
39+
  进程在内核态中通过task_struct管理,而task_struct中关于内存有如下成员变量
40+
41+
```c
42+
struct mm_struct *mm;
43+
struct mm_struct *active_mm;
44+
/* Per-thread vma caching: */
45+
struct vmacache vmacache;
46+
```
47+
  其中mm_struct结构体也较为复杂,我们将分步介绍。首先我们来看看内核态和用户态的地址划分。这里highest_vm_end存储当前虚拟内存地址的最大地址,而task_size则是用户态的大小。
48+
```c
49+
struct mm_struct {
50+
......
51+
unsigned long task_size; /* size of task vm space */
52+
unsigned long highest_vm_end; /* highest vma end address */
53+
......
54+
}
55+
```
56+
  task_size定义如下,从注释可见用户态分配了4G虚拟内存中的3G空间,而64位因为空间巨大因此在内核态和用户态中间还保留了空闲区域进行隔离,用户态仅使用47位,即128TB。内核态同样分配128TB,位于最高位。
57+
```c
58+
#ifdef CONFIG_X86_32
59+
/*
60+
* User space process size: 3GB (default).
61+
*/
62+
#define TASK_SIZE PAGE_OFFSET
63+
#define TASK_SIZE_MAX TASK_SIZE
64+
/*
65+
config PAGE_OFFSET
66+
hex
67+
default 0xC0000000
68+
depends on X86_32
69+
*/
70+
#else
71+
/*
72+
* User space process size. 47bits minus one guard page.
73+
*/
74+
#define TASK_SIZE_MAX ((1UL << 47) - PAGE_SIZE)
75+
#define TASK_SIZE (test_thread_flag(TIF_ADDR32) ? \
76+
IA32_PAGE_OFFSET : TASK_SIZE_MAX)
77+
......
78+
```
79+
### 3.1 用户态内存结构
80+
81+
  在用户态,mm_struct有着以下成员变量
82+
83+
* mmap_base:内存映射的起始地址
84+
* mmap_legacy_base:表示映射的基址,在32位中为固定的TASK_UNMAPPED_BASE,而在64位中,存在一个虚拟地址随机映射机制,因此为TASK_UNMAPPED_BASE + mmap_rnd()
85+
* hiwater_rss:RSS的高水位使用情况
86+
* hiwater_vm:高水位虚拟内存使用情况
87+
* total_vm:映射的总页数
88+
* locked_vm:被锁定不能换出的页数
89+
* pinned_vm:不能换出也不能移动的页数
90+
* data_vm:存放数据的页数
91+
* exec_vm:存放可执行文件的页数
92+
* stack_vm:存放栈的页数
93+
* arg_lock:引入spin_lock用于保护对下面区域变量们的并行访问
94+
* start_code 和 end_code: 可执行代码的开始和结束位置
95+
* start_data 和 end_data :已初始化数据的开始位置和结束位置
96+
* start_brk :堆的起始位置
97+
* brk :堆当前的结束位置
98+
* start_stack :栈的起始位置,栈的结束位置在寄存器的栈顶指针中
99+
* arg_start 和 arg_end :参数列表的位置,位于栈中最高地址的地方。
100+
* env_start 和 env_end :环境变量的位置,位于栈中最高地址的地方。
101+
102+
```c
103+
struct mm_struct {
104+
......
105+
unsigned long mmap_base; /* base of mmap area */
106+
unsigned long mmap_legacy_base; /* base of mmap area in bottom-up allocations */
107+
......
108+
unsigned long hiwater_rss; /* High-watermark of RSS usage */
109+
unsigned long hiwater_vm; /* High-water virtual memory usage */
110+
unsigned long total_vm; /* Total pages mapped */
111+
unsigned long locked_vm; /* Pages that have PG_mlocked set */
112+
atomic64_t pinned_vm; /* Refcount permanently increased */
113+
unsigned long data_vm; /* VM_WRITE & ~VM_SHARED & ~VM_STACK */
114+
unsigned long exec_vm; /* VM_EXEC & ~VM_WRITE & ~VM_STACK */
115+
unsigned long stack_vm; /* VM_STACK */
116+
spinlock_t arg_lock; /* protect the below fields */
117+
unsigned long start_code, end_code, start_data, end_data;
118+
unsigned long start_brk, brk, start_stack;
119+
unsigned long arg_start, arg_end, env_start, env_end;
120+
unsigned long saved_auxv[AT_VECTOR_SIZE]; /* for /proc/PID/auxv */
121+
......
122+
}
123+
```
124+
  根据这些成员变量,我们可以规划出用户态中各个部分的位置,但是我们还需要一个结构体描述这些区域的属性,即vm_area_struct
125+
```c
126+
struct mm_struct {
127+
......
128+
struct vm_area_struct *mmap; /* list of VMAs */
129+
struct rb_root mm_rb;
130+
......
131+
}
132+
```
133+
  vm_area_struct的具体结构体定义如下所示,实际是通过vm_next和vm_prev组合而成的双向链表,即通过一系列的vm_area_struct来表述一个进程在用户态分配的各个区域的内容。
134+
135+
* vm_start和vm_end表述该块区域的开始和结束为止
136+
* vm_rb对应一颗红黑树,这颗红黑树将所有vm_area_struct组合起来,便于增删查找。
137+
* rb_subtree_gap存储当前区域和上个区域之间的间隔,用于后续分配使用。
138+
* vm_mm指向该结构体所属的vm_struct
139+
* vm_page_prot管理该页的接入权限,vm_flags为标记位
140+
* rb和rb_subtree_last:有空余位置的区间树结构
141+
* ano_vma 和 ano_vma_chain:匿名映射。虚拟内存区域可以映射到物理内存,也可以映射到文件,映射到物理内存的时候称为匿名映射,映射到文件需要vm_file指定被映射文件,vm_pgoff存储偏移量。
142+
* vm_opts:指向该结构体的函数指针,用于处理该结构体
143+
* vm_private_data:私有数据存储
144+
145+
```c
146+
/*
147+
* This struct defines a memory VMM memory area. There is one of these
148+
* per VM-area/task. A VM area is any part of the process virtual memory
149+
* space that has a special rule for the page-fault handlers (ie a shared
150+
* library, the executable area etc).
151+
*/
152+
struct vm_area_struct {
153+
/* The first cache line has the info for VMA tree walking. */
154+
unsigned long vm_start; /* Our start address within vm_mm. */
155+
unsigned long vm_end; /* The first byte after our end address
156+
within vm_mm. */
157+
/* linked list of VM areas per task, sorted by address */
158+
struct vm_area_struct *vm_next, *vm_prev;
159+
struct rb_node vm_rb;
160+
/*
161+
* Largest free memory gap in bytes to the left of this VMA.
162+
* Either between this VMA and vma->vm_prev, or between one of the
163+
* VMAs below us in the VMA rbtree and its ->vm_prev. This helps
164+
* get_unmapped_area find a free area of the right size.
165+
*/
166+
unsigned long rb_subtree_gap;
167+
/* Second cache line starts here. */
168+
struct mm_struct *vm_mm; /* The address space we belong to. */
169+
pgprot_t vm_page_prot; /* Access permissions of this VMA. */
170+
unsigned long vm_flags; /* Flags, see mm.h. */
171+
/*
172+
* For areas with an address space and backing store,
173+
* linkage into the address_space->i_mmap interval tree.
174+
*/
175+
struct {
176+
struct rb_node rb;
177+
unsigned long rb_subtree_last;
178+
} shared;
179+
/*
180+
* A file's MAP_PRIVATE vma can be in both i_mmap tree and anon_vma
181+
* list, after a COW of one of the file pages. A MAP_SHARED vma
182+
* can only be in the i_mmap tree. An anonymous MAP_PRIVATE, stack
183+
* or brk vma (with NULL file) can only be in an anon_vma list.
184+
*/
185+
struct list_head anon_vma_chain; /* Serialized by mmap_sem & page_table_lock */
186+
struct anon_vma *anon_vma; /* Serialized by page_table_lock */
187+
/* Function pointers to deal with this struct. */
188+
const struct vm_operations_struct *vm_ops;
189+
/* Information about our backing store: */
190+
unsigned long vm_pgoff; /* Offset (within vm_file) in PAGE_SIZE
191+
units */
192+
struct file * vm_file; /* File we map to (can be NULL). */
193+
void * vm_private_data; /* was vm_pte (shared mem) */
194+
atomic_long_t swap_readahead_info;
195+
#ifndef CONFIG_MMU
196+
struct vm_region *vm_region; /* NOMMU mapping region */
197+
#endif
198+
#ifdef CONFIG_NUMA
199+
struct mempolicy *vm_policy; /* NUMA policy for the VMA */
200+
#endif
201+
struct vm_userfaultfd_ctx vm_userfaultfd_ctx;
202+
} __randomize_layout;
203+
```
204+
  对一个mm_struct来说,其众多的vm_area_struct会在ELF文件加载,即load_elf_binary()时构造。该函数在解析ELF文件格式后,就会进行内存映射的建立,主要包括
205+
206+
* 调用 setup_new_exec,设置内存映射区 mmap_base
207+
* 调用 setup_arg_pages,设置栈的 vm_area_struct,这里面设置了 mm->arg_start 是指向栈底的,current->mm->start_stack 就是栈底
208+
* elf_map 会将 ELF 文件中的代码部分映射到内存中来
209+
* set_brk 设置了堆的 vm_area_struct,这里面设置了 current->mm->start_brk = current->mm->brk,也即堆里面还是空的
210+
* load_elf_interp 将依赖的 so 映射到内存中的内存映射区域
211+
212+
```c
213+
static int load_elf_binary(struct linux_binprm *bprm)
214+
{
215+
......
216+
setup_new_exec(bprm);
217+
......
218+
/* Do this so that we can load the interpreter, if need be. We will
219+
change some of these later */
220+
retval = setup_arg_pages(bprm, randomize_stack_top(STACK_TOP),
221+
executable_stack);
222+
......
223+
error = elf_map(bprm->file, load_bias + vaddr, elf_ppnt,
224+
elf_prot, elf_flags, total_size);
225+
......
226+
/* Calling set_brk effectively mmaps the pages that we need
227+
* for the bss and break sections. We must do this before
228+
* mapping in the interpreter, to make sure it doesn't wind
229+
* up getting placed where the bss needs to go.
230+
*/
231+
retval = set_brk(elf_bss, elf_brk, bss_prot);
232+
......
233+
elf_entry = load_elf_interp(&loc->interp_elf_ex,
234+
interpreter,
235+
&interp_map_addr,
236+
load_bias, interp_elf_phdata);
237+
......
238+
current->mm->end_code = end_code;
239+
current->mm->start_code = start_code;
240+
current->mm->start_data = start_data;
241+
current->mm->end_data = end_data;
242+
current->mm->start_stack = bprm->p;
243+
......
244+
}
245+
```
246+
### 3.2 内核态结构
247+
248+
  由于32位和64位系统空间大小差距过大,因此结构上也有一些区别。我们这里分别讨论二者的结构。
249+
250+
#### 3.2.1 32位内核态结构
251+
252+
  内核态的虚拟空间和进程是无关的,即所有进程通过系统调用进入内核后,看到的虚拟地址空间是一样的。如下图所示为32位内核态虚拟空间分布图。
253+
254+
![image](https://user-images.githubusercontent.com/87457873/128136124-77efb3fa-d616-49a4-90e3-93f47a64eca3.png)
255+
256+
1、直接映射区
257+
258+
前896M为直接映射区,该区域用于和物理内存进行直接映射。虚拟内存地址减去 3G,就得到对应的物理内存的位置。在内核里面,有两个宏:
259+
260+
* __pa(vaddr) 返回与虚拟地址 vaddr 相关的物理地址;
261+
* __va(paddr) 则计算出对应于物理地址 paddr 的虚拟地址。
262+
263+
  对于该部分虚拟地址的访问,同样采取分页的方式进行,但是页表地址比较简单,直接一一对应即可。
264+
265+
  在系统启动的时候,物理内存的前 1M 已经被占用了,从 1M 开始加载内核代码段,然后就是内核的全局变量、BSS 等,也是 ELF 里面涵盖的。这样内核的代码段,全局变量,BSS 也就会被映射到 3G 后的虚拟地址空间里面。具体的物理内存布局可以查看 /proc/iomem,具体会因为每个人的系统、配置等产生区别。
266+
267+
2、high_memory<br>
268+
  高端内存的名字来源于x86架构中将物理地址空间划分三部分:ZONE_DMA、ZONE_NORMAL和ZONE_HIGHMEM。ZONE_HIGHMEM即为高端内存。
269+
270+
  高端内存是内存管理模块看待物理内存的称谓,指的也即896M直接映射区上面的区域。内核中除了内存管理模块外,其余均操作虚拟地址。而内存管理模块会直接操作物理地址,进行虚拟地址的分配和映射。其存在的意义是以32位系统有限的内核空间去访问无限的物理内存空间:借用这段逻辑地址空间,建立映射到想访问的那段物理内存(即填充内核页表),临时用一会,用完后归还。
271+
272+
3、内核动态映射空间(noncontiguous memory allocation)<br>
273+
  在VMALLOC_START和VMALLOC_END之间的区域称之为内核动态映射空间,对应于用户态进程malloc申请内存一样,在内核态可以通过vmalloc来申请。内核态有单独的页表管理,和用户态分开。
274+
275+
4、持久内核映射区(permanent kernel mapping)<br>
276+
  PKMAP_BASE 到 FIXADDR_START 的空间称为持久内核映射,这个地址范围是 4G-8M 到 4G-4M 之间。使用 alloc_pages() 函数的时候,在物理内存的高端内存得到 struct page 结构,可以调用 kmap() 将其映射到这个区域。因为允许永久映射的数量有限,当不再需要高端内存时,应该解除映射,这可以通过kunmap()函数来完成。
277+
278+
5、固定映射区<br>
279+
  FIXADDR_START 到 FIXADDR_TOP(0xFFFF F000) 的空间,称为固定映射区域,主要用于满足特殊需求。
280+
281+
6、临时映射区(temporary kernel mapping)<br>
282+
  临时内核映射通过kmap_atomic和kunmap_atomic实现,主要用于当需要写入物理内存或主存时的操作,如写入文件时使用。
283+
284+
#### 3.2.2 64位内核态结构
285+
286+
  64位内核态因为空间巨大,所以不需要像32位一样精打细算,直接分出很多的空闲区域做保护,结构如下图所示
287+
288+
![image](https://user-images.githubusercontent.com/87457873/128136164-88490bdb-e064-4fc3-bfcc-f2eadbbb5e73.png)
289+
290+
* 从 0xffff800000000000 开始就是内核的部分,只不过一开始有 8T 的空档区域。
291+
* 从 __PAGE_OFFSET_BASE(0xffff880000000000) 开始的 64T 的虚拟地址空间是直接映射区域,也就是减去 PAGE_OFFSET 就是物理地址。虚拟地址和物理地址之间的映射在大部分情况下还是会通过建立页表的方式进行映射。
292+
* 从 VMALLOC_START(0xffffc90000000000)开始到 VMALLOC_END(0xffffe90000000000)的 32T 的空间是给 vmalloc 的。
293+
* 从 VMEMMAP_START(0xffffea0000000000)开始的 1T 空间用于存放物理页面的描述结构 struct page 的。
294+
* 从 __START_KERNEL_map(0xffffffff80000000)开始的 512M 用于存放内核代码段、全局变量、BSS 等。这里对应到物理内存开始的位置,减去 __START_KERNEL_map 就能得到物理内存的地址。这里和直接映射区有点像,但是不矛盾,因为直接映射区之前有 8T 的空当区域,早就过了内核代码在物理内存中加载的位置。
295+
296+
## 总结
297+
298+
  本文比较详细的分析了内存在用户态和内核态的结构,以此为基础,后文可以开始分析内存的管理、映射了。
299+
300+
301+
302+
303+
304+
305+
306+
307+
308+
309+
310+
311+
312+
313+
314+
315+
316+
317+
318+
319+
320+
321+
322+
323+
324+
325+
326+
327+
328+
329+

0 commit comments

Comments
 (0)