Memory Management in Linux Anand Sivasubramaniam
Two Parts <ul><li>Architecture Independent Memory </li></ul><ul><ul><li>Should be flexible and portable enough across plat...
Architecture Independent Memory Model <ul><li>Process virtual address space divided into pages </li></ul><ul><li>Page size...
<ul><li>put_user(), get_user(), memcpy_tofs(), memcpy_fromfs()  allow kernel to access user data (defined in asm/segment.h...
<ul><li>Segment + Offset = 4 GB Linear address (32 bits) </li></ul><ul><li>Of  this,  user space = 3 GB  (defined by  TASK...
Page Dir. And Middle Dir. Access Functions  (in  asm/page.h  and  asm/pgtable.h ) <ul><li>Structures  pgd_t  and  pmd_t  d...
Page Table Entry ( pte_t ) <ul><li>Attributes </li></ul><ul><li>Presence (is page present in VAS?) </li></ul><ul><li>Read,...
Page Table Functions <ul><li>mk_pte(), Pte_clear(), set_pte() </li></ul><ul><li>pte_mkclean(), pte_mkdirty(), pt_mkread(),...
Process Address Space (not to scale!) Kernel 0xC0000000 File name, Environment Arguments Stack bss _end _bss_start Data _e...
Address Space Descriptor <ul><li>mm_struct  defined in the process descriptor. (in  linux/sched.h ) </li></ul><ul><li>This...
Region Descriptors <ul><li>Why even allocate all of the VAS? Allocate only on demand. </li></ul><ul><li>Use region descrip...
<ul><li>If  vm_inode  is NULL (anonymous mapping), all PTEs for this region point to the same page.  </li></ul><ul><li>If ...
<ul><li>Struct vm_operations_struct { </li></ul><ul><ul><li>void (*open)(struct vm_area_struct *); </li></ul></ul><ul><ul>...
Traditional mmap() <ul><li>int do_mmap(struct file *, unsigned long addr, unsigned long len, unsigned long prot, unsigned ...
How is brk() implemented? <ul><li>Check whether to allocate (deny if not enough physical memory, exceeds its VA limits, or...
Kernel Segment <ul><li>On a sys call, CS points to kernel segment. DS and ES are set to kernel segment as well. </li></ul>...
Memory Allocn for Kernel Segment <ul><li>Static </li></ul><ul><ul><li>Memory_start = console_init(memory_start, memory_end...
kmalloc() data structures sizes[] bh bh bh bh bh bh Null Null page_descriptor size_descriptor 32 64 128 252 508 1020 2040 ...
vmalloc() <ul><li>Allocated virtually contiguous pages, but they do not need to be physically contiguous. </li></ul><ul><l...
vmalloc vs kmalloc <ul><li>Contiguous vs non-contiguous physical memory </li></ul><ul><li>kmalloc is faster but less flexi...
Paging <ul><li>All kernel segment pages are locked in memory (no swapping) </li></ul><ul><li>User  pages can be paged out:...
<ul><li>Inform swap space to kernel using  </li></ul><ul><li>int  sys_swapon(char * swapfile, int swapflags); </li></ul><u...
<ul><li>For each physical frame (mm.h): </li></ul><ul><ul><li>typedef struct page { </li></ul></ul><ul><ul><ul><li>struct ...
Finding a Physical Page <ul><li>unsigned long __get_free_pages(int priority, unsigned long  order, int dma)  in mm/page_al...
<ul><li>First tries to find a free frame using Buddy system. </li></ul><ul><li>Table  free_area[]  keeps appropriate data ...
<ul><li>If you cannot find a free page, </li></ul><ul><li>int try_to_free_page(int priority, int dma, int wait) { </li></u...
<ul><li>shrink_mmap()  tries to discard pages in page cache or buffer cache that have only one user currently, and have no...
<ul><li>kswapd  kernel thread running in background is activated each time the number of free pages falls below a critical...
Page Fault <ul><li>Error code written onto stack, and the VA is stored in register CR2 </li></ul><ul><li>do_page_fault(str...
<ul><li>void do_wp_page(struct task_struct *task, struct vm_area_struct *vma, unsigned long address, int write_access); </...
Upcoming SlideShare
Loading in...5
×

Memory

391

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
391
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
15
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Memory

  1. 1. Memory Management in Linux Anand Sivasubramaniam
  2. 2. Two Parts <ul><li>Architecture Independent Memory </li></ul><ul><ul><li>Should be flexible and portable enough across platforms </li></ul></ul><ul><li>Implementation for a specific architecture </li></ul>
  3. 3. Architecture Independent Memory Model <ul><li>Process virtual address space divided into pages </li></ul><ul><li>Page size given in PAGE_SIZE macro in asm/page.h </li></ul><ul><ul><li>(4K for x86 and 8K for Alpha) </li></ul></ul><ul><li>The pages are divided between 4 segments </li></ul><ul><li>User Code, User Data, Kernel Code, Kernel Data </li></ul><ul><li>In User mode, access only User Code and User Data </li></ul><ul><li>But in Kernel mode, access also needed for User Data </li></ul>
  4. 4. <ul><li>put_user(), get_user(), memcpy_tofs(), memcpy_fromfs() allow kernel to access user data (defined in asm/segment.h) </li></ul><ul><li>Registers cs and ds point to the code and data segments of the current mode </li></ul><ul><li>fs points to the data segment of the calling process in kernel mode. </li></ul><ul><li>Get_ds(), get_fs(), and set_fs() are defined in asm/segment.h </li></ul>
  5. 5. <ul><li>Segment + Offset = 4 GB Linear address (32 bits) </li></ul><ul><li>Of this, user space = 3 GB (defined by TASK_SIZE macro) and kernel space = 1GB </li></ul><ul><li>Linear Address converted to physical address using 3 levels </li></ul>Index into Page Dir. Index into Page Middle Dir. Index into Page Table Page Offset
  6. 6. Page Dir. And Middle Dir. Access Functions (in asm/page.h and asm/pgtable.h ) <ul><li>Structures pgd_t and pmd_t define an entry of these tables. </li></ul><ul><li>pgd_alloc_alloc()/pgd_free() to allocate and free a page for the page directory </li></ul><ul><li>pmd_alloc(),pmd_alloc_kernel()/pmd_free(),pmd_free_kernel() allocate and free a page middle directory in user and kernel segments. </li></ul><ul><li>pgd_set(),pgd_clear()/pmd_set(),pmd_clear() set and clear a entry of their tables. </li></ul><ul><li>pgd_present()/pmd_present() checks for presence of what the entries are pointing to. </li></ul><ul><li>pgd_page()/pmd_page() returns the base address of the page to which the entry is pointing </li></ul><ul><li>… .. </li></ul>
  7. 7. Page Table Entry ( pte_t ) <ul><li>Attributes </li></ul><ul><li>Presence (is page present in VAS?) </li></ul><ul><li>Read, Write and Execute </li></ul><ul><li>Accessed ? (age) </li></ul><ul><li>Dirty </li></ul><ul><li>Macros of Pgprot_type </li></ul><ul><ul><li>PAGE_NONE (invalid) </li></ul></ul><ul><ul><li>PAGE_SHARED (read-write) </li></ul></ul><ul><ul><li>PAGE_COPY/READ_ONLY (read only, used by copy-on-write) </li></ul></ul><ul><ul><li>PAGE_KERNEL (accessibe only by kernel) </li></ul></ul>
  8. 8. Page Table Functions <ul><li>mk_pte(), Pte_clear(), set_pte() </li></ul><ul><li>pte_mkclean(), pte_mkdirty(), pt_mkread(), …. </li></ul><ul><li>pte_none() (check whether entry is set) </li></ul><ul><li>pte_page() (returns address of page) </li></ul><ul><li>pte_dirty(), pte_present(), pte_young(), pte_read(), pte_write() </li></ul>
  9. 9. Process Address Space (not to scale!) Kernel 0xC0000000 File name, Environment Arguments Stack bss _end _bss_start Data _edata _etext Code Header 0x84000000 Shared Libs
  10. 10. Address Space Descriptor <ul><li>mm_struct defined in the process descriptor. (in linux/sched.h ) </li></ul><ul><li>This is duplicated if CLONE_VM is specified on forking. </li></ul><ul><li>struct mm_struct { </li></ul><ul><ul><li>int count; // no. of processes sharing this descriptor </li></ul></ul><ul><ul><li>pgd_t *pgd; //page directory ptr </li></ul></ul><ul><ul><li>unsigned long start_code, end_code; </li></ul></ul><ul><ul><li>unsigned long start_data, end_data; </li></ul></ul><ul><ul><li>unsigned long start_brk, brk; </li></ul></ul><ul><ul><li>unsigned long start_stack; </li></ul></ul><ul><ul><li>unsigned long arg_start, arg_end, env_start, env_end; </li></ul></ul><ul><ul><li>unsigned long rss; // no. of pages resident in memory </li></ul></ul><ul><ul><li>unsigned long total_vm; // total # of bytes in this address space </li></ul></ul><ul><ul><li>unsigned long locked_vm; // # of bytes locked in memory </li></ul></ul><ul><ul><li>unsigned long def_flags; // status to use when mem regions are created </li></ul></ul><ul><ul><li>struct vm_area_struct *mmap; // ptr to first region desc. </li></ul></ul><ul><ul><li>struct vm_area_struct *mmap_avl; // faster search of region desc. </li></ul></ul><ul><ul><li>} </li></ul></ul>
  11. 11. Region Descriptors <ul><li>Why even allocate all of the VAS? Allocate only on demand. </li></ul><ul><li>Use region descriptors for each allocated region of VAS </li></ul><ul><li>Map allocated but unused regions to same physical page to save space. </li></ul><ul><li>struct vm_area_struct { </li></ul><ul><ul><li>struct mm_struct *vm_mm; // descriptor of VAS </li></ul></ul><ul><ul><li>unsigned long vm_start, vm_end; // of this region </li></ul></ul><ul><ul><li>pgprot_t vm_page_prot; // protection attributes for this region </li></ul></ul><ul><ul><li>short vm_avl_height; </li></ul></ul><ul><ul><li>struct vm_avl_left; </li></ul></ul><ul><ul><li>vm_area_struct *vm_avl_permission; // right hand child </li></ul></ul><ul><ul><li>vm_area_struct * vm_next_share, *vm_prev_share; // doubly linked </li></ul></ul><ul><ul><li>vm_operations_struct *vm_ops; </li></ul></ul><ul><ul><li>struct inode *vm_inode; // of file mapped, or NULL = “anonymous mapping” </li></ul></ul><ul><ul><li>unsigned long vm_offset; // offset in file/device </li></ul></ul><ul><ul><li>} </li></ul></ul>
  12. 12. <ul><li>If vm_inode is NULL (anonymous mapping), all PTEs for this region point to the same page. </li></ul><ul><li>If the process does a write to any of these pages, the faulting mechanism creates a new physical page (copy-on-write). </li></ul><ul><li>This is used by the brk() system call. </li></ul><ul><li>Operations specific to this region (including fault handling) are specified in vm_operations_struct . </li></ul><ul><li>Hence, different regions can have different functions. </li></ul>
  13. 13. <ul><li>Struct vm_operations_struct { </li></ul><ul><ul><li>void (*open)(struct vm_area_struct *); </li></ul></ul><ul><ul><li>void (*close)(struct vm_area_struct *); </li></ul></ul><ul><ul><li>void (*unmap)(…); </li></ul></ul><ul><ul><li>void (*protect)(…) </li></ul></ul><ul><ul><li>void (*sync)(…); </li></ul></ul><ul><ul><li>unsigned long (*nopage)(struct vm_area_struct *, unsigned long address, unsigned long page, int write_access); </li></ul></ul><ul><ul><li>void (*swapout)(struct vm_area_struct *, unsigned long, pte_t *); </li></ul></ul><ul><ul><li>pte_t (*swapin)(struct vm_area_struct *, unsigned long, unsigned long); </li></ul></ul><ul><li>} </li></ul>
  14. 14. Traditional mmap() <ul><li>int do_mmap(struct file *, unsigned long addr, unsigned long len, unsigned long prot, unsigned long flags, unsigned long off); </li></ul><ul><li>Creates a new memory region </li></ul><ul><li>Creates the required PTEs </li></ul><ul><li>Sets the PTEs to fault later </li></ul><ul><li>The handler (nopage) will either copy-on-write if anonymous mapping, or will bring in the required page of file. </li></ul>
  15. 15. How is brk() implemented? <ul><li>Check whether to allocate (deny if not enough physical memory, exceeds its VA limits, or crosses stack). </li></ul><ul><li>Then call do_mmap() for anonymous mapping between the old and new values of brk (in process table). </li></ul><ul><li>Return the new brk value. </li></ul>
  16. 16. Kernel Segment <ul><li>On a sys call, CS points to kernel segment. DS and ES are set to kernel segment as well. </li></ul><ul><li>Next, FS is set to user data segment. </li></ul><ul><li>Put_user() and get_user() can then access user space if needed. </li></ul><ul><li>The address parameters to these functions cannot exceed 0xc0000000. </li></ul><ul><li>Violation of this should result in a trap, together with any writes to a read-only page (creates a problem on 386, while the problem does not exist in 486/Pentium) </li></ul><ul><li>Hence, verify_area() is typically called before performing such operations. </li></ul><ul><li>Physical and Virtual addresses are same except for those allocated using vmalloc(). </li></ul><ul><li>Kernel segment shared across processes (not switched!) </li></ul>
  17. 17. Memory Allocn for Kernel Segment <ul><li>Static </li></ul><ul><ul><li>Memory_start = console_init(memory_start, memory_end); </li></ul></ul><ul><ul><li>Typically done for drivers to reserve areas, and for some other kernel components. </li></ul></ul><ul><li>Dynamic </li></ul><ul><ul><li>Void *kmalloc(size, priority), Void kfree (void *) // in mm/kmalloc.c </li></ul></ul><ul><ul><li>Void *vmalloc(size), void *vmfree(void *) // in mm/vmalloc.c </li></ul></ul><ul><ul><li>Kmalloc is used for physically contiguous pages while vmalloc does not necessarily allocate physically contiguous pages </li></ul></ul><ul><ul><li>Memory allocated is not initialized (and is not paged out). </li></ul></ul>
  18. 18. kmalloc() data structures sizes[] bh bh bh bh bh bh Null Null page_descriptor size_descriptor 32 64 128 252 508 1020 2040 4080 8176 16368 32752 65520 131056
  19. 19. vmalloc() <ul><li>Allocated virtually contiguous pages, but they do not need to be physically contiguous. </li></ul><ul><li>Uses __get_free_page() to allocate physical frames. </li></ul><ul><li>Once all the required physical frames are found, the virtual addresses are created (and mappings set) at an unused part. </li></ul><ul><li>The virtual address search (for unused parts) on x86 begins at the next address after physical memory on an 8 MB boundary. </li></ul><ul><li>One (virtual) page is left free after each allocation for cushioning. </li></ul>addr size next addr size next vmlist vmstruct VAS
  20. 20. vmalloc vs kmalloc <ul><li>Contiguous vs non-contiguous physical memory </li></ul><ul><li>kmalloc is faster but less flexible </li></ul><ul><li>vmalloc involves __get_free_page() and may need to block to find a free physical page </li></ul><ul><li>DMA requires contiguous physical memory </li></ul>
  21. 21. Paging <ul><li>All kernel segment pages are locked in memory (no swapping) </li></ul><ul><li>User pages can be paged out: </li></ul><ul><ul><li>Complete block device </li></ul></ul><ul><ul><li>Fixed length files in a file system </li></ul></ul><ul><li>First 4096 bytes are a bitmap indicating that space for that page is available for paging. </li></ul><ul><li>At byte 4086, string “SWAP_SPACE” is stored. </li></ul><ul><li>Hence, max swap of 4086*8-1 = 32687 pages = 130784KB per device or file </li></ul><ul><li>MAX_SWAPFILES specifies number of swap files or devices </li></ul><ul><li>Swap device is more efficient than swap file. </li></ul>
  22. 22. <ul><li>Inform swap space to kernel using </li></ul><ul><li>int sys_swapon(char * swapfile, int swapflags); </li></ul><ul><li>Ceates an entry in swap_info table. </li></ul><ul><li>struct swap_info_struct { </li></ul><ul><ul><ul><li>unsigned int flags; </li></ul></ul></ul><ul><ul><ul><li>kdev_t swap_device; </li></ul></ul></ul><ul><ul><ul><li>struct indoe *swap_file; </li></ul></ul></ul><ul><ul><ul><li>unsigned char *swap_map; // ptr to table, with 1 byte for each page to indicate how many processes are referring to this page </li></ul></ul></ul><ul><ul><ul><li>unsigned char *swap_lockmap; // ptr to bitmap, bit indicating lock </li></ul></ul></ul><ul><ul><ul><li>int lowest_bit, highest_bit; // to calculate maximum page number </li></ul></ul></ul><ul><ul><ul><li>unsigned long max; // highest_bit + 1 </li></ul></ul></ul><ul><ul><ul><li>int prio; // priority for this swap space </li></ul></ul></ul><ul><ul><ul><li>int cluster_nr, cluster_next; // to cluster pages on storage device </li></ul></ul></ul><ul><ul><ul><li>int next; </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  23. 23. <ul><li>For each physical frame (mm.h): </li></ul><ul><ul><li>typedef struct page { </li></ul></ul><ul><ul><ul><li>struct page *prev, *next; // doubly linked </li></ul></ul></ul><ul><ul><ul><li>struct inode *inode; unsigned long offset; // where to swap </li></ul></ul></ul><ul><ul><ul><li>struct page *prev_hash, next_hash; // in hash list of pages in page cache </li></ul></ul></ul><ul><ul><ul><li>atomic_t count; // number of users of this page </li></ul></ul></ul><ul><ul><ul><li>unsigned dirty:16, age:8; </li></ul></ul></ul><ul><ul><ul><li>struct buffer_head * buffers; // if it is part of a block buffer </li></ul></ul></ul><ul><ul><ul><li>unsigned long map_nr; // frame # </li></ul></ul></ul><ul><ul><ul><li>struct wait_queue *wait; // Tasks waiting for page to be unlocked </li></ul></ul></ul><ul><ul><ul><li>unsigned flags; </li></ul></ul></ul><ul><ul><li>} mem_map_t; </li></ul></ul>
  24. 24. Finding a Physical Page <ul><li>unsigned long __get_free_pages(int priority, unsigned long order, int dma) in mm/page_alloc.c </li></ul><ul><li>Priority = </li></ul><ul><ul><li>GFP_BUFFER (free page returned only if available in physical memory) </li></ul></ul><ul><ul><li>GFP_ATOMIC (return page if possible, do not interrupt current process) </li></ul></ul><ul><ul><li>GFP_USER (current process can be interrupted) </li></ul></ul><ul><ul><li>GFP_KERNEL (kernel can be interrupted) </li></ul></ul><ul><ul><li>GFP_NOBUFFER (do not attempt to reduce buffer cache) </li></ul></ul><ul><li>order says give me 2^^order pages (max is 128KB) </li></ul><ul><li>dma specifies that it is for DMA purposes </li></ul>
  25. 25. <ul><li>First tries to find a free frame using Buddy system. </li></ul><ul><li>Table free_area[] keeps appropriate data structures. </li></ul>free_area_list[0 1 2] free_area_map 0 1 2
  26. 26. <ul><li>If you cannot find a free page, </li></ul><ul><li>int try_to_free_page(int priority, int dma, int wait) { </li></ul><ul><ul><li>static int state = 6; int I = 6; int stop; </li></ul></ul><ul><ul><li>stop = 3; if (wait) stop = 0; </li></ul></ul><ul><ul><li>switch (state) { </li></ul></ul><ul><ul><ul><li>do { </li></ul></ul></ul><ul><ul><ul><ul><li>Case 0: </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>if (shrink_mmap(i,dma)) return 1; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>state = 1; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>Case 1: </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>if (shm_swap(i,dma)) return 1; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>state = 2; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>Default: </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>if (swap_out(i,dma,wait)) return 1; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>state = 0; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>i--; </li></ul></ul></ul></ul><ul><ul><ul><li>} while ((i-stop) >= 0); </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>return 0; </li></ul></ul><ul><li>} </li></ul>
  27. 27. <ul><li>shrink_mmap() tries to discard pages in page cache or buffer cache that have only one user currently, and have not been references since the last cycle. The number of examined pages depends on priority. </li></ul><ul><li>shm_swap() tries pages allocated for shared memory. </li></ul><ul><li>swap_out() </li></ul><ul><ul><li>Uses swap_cnt to determine how many pages to swap out for current process before moving on to next. </li></ul></ul><ul><ul><li>Always start where you left off last time (Clock algorithm) </li></ul></ul><ul><ul><li>Uses swap_out_process() function, which then calls try_to_swap_out() for each possible page present in memory (and is not locked). </li></ul></ul><ul><ul><li>try_to_swap_out() checks the age attribute in mem_map data structure, and the page is selected if this is 0. </li></ul></ul><ul><ul><li>VM area’s swapout() operation is called. </li></ul></ul><ul><ul><li>Write back if the page is dirty </li></ul></ul><ul><ul><li>Invalidate page table entry. </li></ul></ul>
  28. 28. <ul><li>kswapd kernel thread running in background is activated each time the number of free pages falls below a critical level. </li></ul><ul><li>This thread calls the try_to_free_page() function. </li></ul><ul><li>A block of memory is released using free_pages(). When the number of users reaches 0, the frames are entered in free_area[]. </li></ul>
  29. 29. Page Fault <ul><li>Error code written onto stack, and the VA is stored in register CR2 </li></ul><ul><li>do_page_fault(struct pt_regs *regs, unsigned long error_code) is now called. </li></ul><ul><li>If faulting address is in kernel segment, alarm messages are printed out and the process is terminated. </li></ul><ul><li>If faulting address is not in a virtual memory area, check if VM_GROWSDOWN for the nexy virtual memory area is set (I.e. Stack). If so, expand VM. If error in expanding send SIGSEGV. </li></ul><ul><li>If faulting address is in a virtual memory area, check if protection bits are OK. If not legal, send SIGSEGV. Else, call do_no_page() or do_wp_page(). </li></ul>
  30. 30. <ul><li>void do_wp_page(struct task_struct *task, struct vm_area_struct *vma, unsigned long address, int write_access); </li></ul><ul><ul><li>Check if page is mapped in </li></ul></ul><ul><ul><li>If it is referenced only once, change permissions </li></ul></ul><ul><ul><li>Else, create a copy and entry in page table to this copy with write permissions on </li></ul></ul><ul><li>void do_no_page(struct task_struct *task, struct vm_area_struct *vma, unsigned long address, int write_access); </li></ul><ul><ul><li>If there is no nopage() handler, an empty page is mapped to this area </li></ul></ul><ul><ul><li>Else, do_swap_page(struct task_struct, struct vm_area_struct, unsigned long address, pte_t, int write_access) is called. </li></ul></ul><ul><ul><li>If no swap_in() handler is defined, swap_in(struct task_struct, struct vm_area_struct, pte_t *, unsigned long entry, int write_access) is called. </li></ul></ul><ul><ul><li>entry contains swap space and page number. </li></ul></ul><ul><ul><li>This calls swap_free() to release te page in swap space and the swap_map counter is decremented. </li></ul></ul>
  1. Gostou de algum slide específico?

    Recortar slides é uma maneira fácil de colecionar informações para acessar mais tarde.

×