Download - By Xuchao Zhang
By Xuchao Zhang
What happens in malloc()
-- in Linux Kernel’s Perspective
What’s malloc()
1. void* p = malloc(size);2. Function in c lib3. Where? Heap4. How?
(1) in kernel (2) algo for malloc
Heap in Linux Kernel
1. Process Address space Abstraction of memory for a process
task_struct -> mm_struct
2. memory region A resource to implement memory allocation (allocate page frame when use)
Heap in Linux Kernel
2. memory region (continue..) Q: what’s the relationship with page table? Example: file mapping. //TODO: file mapping
Heap in Linux Kernel
3. Heap in Process Address Space one of memory region.
Heap in Linux Kernel
4. brk(), sbrk() sys_brk(addr) – system call equals to:do_mmap(NULL, oldbrk, newbrk-oldbrk, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_FIXED|M
AP_PRIVATE, 0); malloc() call brk() to get new heap memory. So malloc()’s job is to organize the heap memory region. See Algo of malloc.
Question: malloc() call brk() to allocate new heap memory, so when to allocate physical memory?Let’s see what happens in following statement:int* p = (int*)malloc(4);*p = 4; // what happens here.
Page Fault Exception Handler
When happens?1) present = 0 2) read/write violation
Page Fault Exception Handler (continue)
1. demand pagepresent = 0
(1) pte = 1 never accessed before 1) vma->vm_ops->nopage != NULL : file mapping, call no page.
2) vma->vm_ops->nopage != NULL : get a new page frame by do_anonymous_page()
Do anonymouswrite request && read request
(2) pte = 0 swap out to disk//TODO
int* p = (int*)malloc(4);*p = 4; // what happens here.
2. copy on write*present = 1 Read/Write=0(write protection)
3. Noncontiguous memory area address*swap_pg_dir: kernel’s page directory
4. User mode stack*grow down
Page Fault Exception Handler (continue)
demand pagepresent = 0
(1) pte = 1 never accessed before 1) vma->vm_ops->nopage != NULL : file mapping, call no page. //TODO
2) vma->vm_ops->nopage != NULL : get a new page frame by do_anonymous_page()
do_anonymous_page()1. write requestalloc_page() memset to 0 //sample here.2. read requestuse zero page instead of allocating new page frame.
(2) pte = 0 swap out to disk//TODO
int* p = (int*)malloc(4);*p = 4; // what happens here.
Malloc Large chunk
Source CodeSource Code
address space
mmap()
File Mapping
1.
Swap out
1.
A very simple malloc() implementation
1
Doug Lea ’ s malloc()
http://book.csdn.net/bookfiles/228/
Comparison of memory allocation strategies
1