最近一段时间在阅读Linux的源代码,想把看到的东西写出来,觉得内存这一部分最简单,就先写了出来。请指正!
内存最低4K的地址是一张页目录(page_dir),页目录共1024项,每项4字节。目录项的结构如下:
____________________________________
|32-12位为页框地址 | |U|R|p|
| | |S|W| |
|_________________|______ |_|_ |_|
随后的16K,用来做了4张页表,页表项结构和页目录项结构一样。页表的每一项指向一个物理页面,也就是指向内存中的一个4K大小的空间。有了这4张页表,已经能寻址16M的内存了。下面就是在系统初始化的时候在head.s程序中设置一张页目录和四张页表的代码。此时页目录中仅前4项有效,正是指向位于其下面的4张页表,而这4张页表寻址了内存的最低16M。
198 setup_paging:
199 movl 24*5,%ecx /* 5 pages - pg_dir+4 page tables */
200 xorl %eax,%eax
201 xorl %edi,%edi /* pg_dir is at 0x000 */
202 cld;rep;stosl
203 movl $pg0+7,_pg_dir /* set present bit/user r/w */
204 movl $pg1+7,_pg_dir+4 /* --------- " " --------- */
205 movl $pg2+7,_pg_dir+8 /* --------- " " --------- */
206 movl $pg3+7,_pg_dir+12 /* --------- " " --------- */
207 movl $pg3+4092,%edi
208 movl xfff007,%eax /* 16Mb - 4096 + 7 (r/w user,p) */
209 std
210 1: stosl /* fill pages backwards - more efficient :-) */
211 subl x1000,%eax
212 jge 1b
以后每次有fork新进程,都要为新进程分配内存。但具体是怎么做的呢,我也想知道,一起看吧。当执行fork时,它使用int0x80调用sys_fork函数,sys_fork的代码位于system_call.s中,很短如下:
208 _sys_fork:
209 call _find_empty_process
210 testl %eax,%eax
211 js 1f
212 push %gs
213 pushl %esi
214 pushl %edi
215 pushl %ebp
216 pushl %eax
217 call _copy_process
218 addl ,%esp
219 1: ret
![]() |

