Linux虛擬內存管理 - Page Table的作用

虛擬內存的作用:

1. 擴展實際有限的物理內存,當然這種擴展是虛擬的,比如物理內存512M,對於一個需要1G空間的進程來說,照樣可以運行。這增加了操作系統是應用範圍。 

2. 使得進程中的數據空間增大,增大到多少與硬件有關,對於一個32位的芯片,進程中的數據空間可以爲4G[2^32],對於64位的芯片則支持2^64大小 的空間。這一點使得進程自身可操作的空間大大增加。

通俗來講,虛擬內存的管理的核心是解決如何在小的物理內存中運行更大程序的問題

在Linux中,解決這個問題的關鍵是一個叫做page table[PT頁面轉換表]的結構。Linux把物理內存分爲了固定統一大小的塊,稱爲page[頁],一般爲4KB,並且每個頁都有一個編號 [page frame number]。這樣一個512M大小的內存將包括128K個頁。這種方式稱爲paging,使得操作系統對內存的管理更方便。page table的作用就是將進程操作的地址[虛擬地址]轉換成物理地址。

其原理很簡單,如下:

用一個32位芯片的系統爲例[64位同理],運行的每個進程的可操作數據空間爲2^32,即2^20個頁,設其物理內存爲512M,則物理頁有 2^17個,現在就說明如何將2^20個頁放入2^17個頁中運行。我們把進程操作的地址分爲兩部分,第一部分爲地址的高20位,第二部分爲後12位,這 樣很容易將第一部分理解爲虛擬頁標號,第二部分理解爲在頁中的offset。那麼現在我們只需將虛擬頁標號對應到物理頁號即可,這個對應就是page table的工作,在這個例子中page table包括了2^20個記錄,每個記錄有兩部分組成:20位的虛擬標號和17位的物理標號,這樣CPU用進程地址的第一部分作爲索引找到對應的17位 物理標號,與地址的第二部分一起便組成一個29位的地址,這個地址就是要找的物理地址。因爲物理頁少於虛擬頁,所以page table中的有些記錄的後17位是空的或無效的。

利用這個方法,使得運行的進程無需知道自己操作的地址是虛擬的,和運行在一個真實的大物理內存中效果是一樣的。

可以看出,在進程的運行過程中,page table必須一直保存在內存中,在上面的例子中,我們把虛擬地址分了2層,page table有2^20個記錄,需要1M左右的空間,爲了節省空間我們可以將地址分爲3層,第一層10位,需要1K左右的空間,第二層10位,需要1K左右 的空間,第三層12位,這樣在一段時間內只需要2K的空間保存page table。實際上,Alpha的芯片採用的就是這種3層的分法,Intel的芯片採用的2層的分法。

鏈接:http://hi.baidu.com/daniel_cn/blog/item/315034388a5f9dc5d56225f1.html


Linux Page Tables : www.linux-tutorial.info/modules.php?name=MContent&pageid=307


Figure: Three Level Page Tables

Linux assumes that there are three levels of page tables. Each Page Table contains the page frame number of the next level of Page Table. The Figure above shows how a virtual address can be broken into a number of fields; each field providing an offset into a particular Page Table. To translate a virtual address into a physical one, the processor must take the contents of each level field, convert it into an offset into the physical page containing the Page Table and read the page frame number of the next level of Page Table. This is repeated three times until the page frame number of the physical page containing the virtual address is found. Now the final field in the virtual address, the byte offset, is used to find the data inside the page.

Each platform that Linux runs on must provide translation macros that allow the kernel to traverse the page tables for a particular process. This way, the kernel does not need to know the format of the page table entries or how they are arranged.

This is so successful that Linux uses the same page table manipulation code for the Alpha processor, which has three levels of page tables, and for Intel x86 processors, which have two levels of page tables. 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章