Useful Link
Credit goes to:
https://blog.csdn.net/gfgdsg/article/details/42709943
Notice: page-granularity
All memory in virtual memory address space are page-based. It is the smallest unit of granularity, including the Heap segment in the following.
Virtual Memory Allocation (2 ways):
brk()
on Heap segmentmmap()
mapped_file segment, between Heap and Stack
Usually user process calls malloc()
to invoke kernel
system calls brk()
or mmap()
to get a virtual memory. Which one will be executed depends on requesting memory size(128KB is the line)
- size<128KB, kernel calls
brk()
to assign virtual memory on Heap to user process- BAD: only be sequentially assign and free, like Stack
- GOOD: can be used as cache ()
- size>128KB, kerel calls
mmap()
to get a piece of memory between Heap and Stack to user process- GOOD: can independently assign and free (flexible)
- BAD: repeately causing page_fault to involve physical memory (CPU costly)
System API:do_brk( )
1 | int do_brk(void *addr, void **ret) |
- 如果 addr == NULL,返回当前 brk
- 判断 addr 的合法性:与 proc_start_brk比较,不能比他还小
- 处理 addr 与 proc_brk 在 page_not_aligned 的情况;并获得old proc_brk所在 virtual area 的最后一页 end_page
- addr : newvfn (new virtual frame number)
- curproc->p_brk: oldvma->vma_end
- if(newvfn > oldvma->vma_end): 对应于
malloc()
- if(newvfn < oldvma->vma_end): 对应于
free()
- 最后更新两个量:
- oldvma->vma_end = newvfn;
- curproc->p_brk = addr;