by xuchao zhang

15
By Xuchao Zhang What happens in mallo c() -- in Linux Kernel’s Perspective

Upload: virote

Post on 30-Jan-2016

20 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: By Xuchao Zhang

By Xuchao Zhang

What happens in malloc()

-- in Linux Kernel’s Perspective

Page 4: By Xuchao Zhang

Heap in Linux Kernel

2. memory region (continue..) Q: what’s the relationship with page table? Example: file mapping. //TODO: file mapping

Page 5: By Xuchao Zhang

Heap in Linux Kernel

3. Heap in Process Address Space one of memory region.

Page 6: By Xuchao Zhang

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 7: By Xuchao Zhang

Page Fault Exception Handler

When happens?1) present = 0 2) read/write violation

Page 8: By Xuchao Zhang

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 9: By Xuchao Zhang

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.

Page 10: By Xuchao Zhang

Malloc Large chunk

Source CodeSource Code

address space

mmap()

Page 11: By Xuchao Zhang

File Mapping

1.

Page 12: By Xuchao Zhang

Swap out

1.

Page 13: By Xuchao Zhang

A very simple malloc() implementation

1

Page 14: By Xuchao Zhang

Doug Lea ’ s malloc()

http://book.csdn.net/bookfiles/228/

Page 15: By Xuchao Zhang

Comparison of memory allocation strategies

1