150 likes | 280 Views
What happens in malloc(). -- in Linux Kernel’s Perspective. By Xuchao Zhang. void* p = malloc(size); Function in c lib Where? Heap How? (1) in kernel (2) algo for malloc. What’s malloc(). 1. Process Address space Abstraction of memory for a process task_struct -> mm_struct
E N D
What happens in malloc() -- in Linux Kernel’s Perspective By Xuchao Zhang
void* p = malloc(size); • Function in c lib • Where? Heap • How? • (1) in kernel (2) algo for malloc What’s malloc()
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|MAP_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. Heap in Linux Kernel 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.
When happens? • present = 0 • read/write violation Page Fault Exception Handler
1. demand page • present = 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 anonymous • write 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 page • present = 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 request • alloc_page() memset to 0 //sample here. • 2. read request • use 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. Page Fault Exception Handler (continue)
Source Code Source Code address space Malloc Large chunk mmap()
1. File Mapping
1. Swap out
1 A very simple malloc() implementation
http://book.csdn.net/bookfiles/228/ Doug Lea ’s malloc()
1 Comparison of memory allocation strategies