caching and virtual memory

28
Caching and Virtual Memory 20 조 OX 20010110 조조조 20010362 조조조

Upload: natara

Post on 04-Jan-2016

45 views

Category:

Documents


3 download

DESCRIPTION

Caching and Virtual Memory. 20 조 OX 20010110 김정현 20010362 이영재. Assignment #1 software-management of the TLB. TLB 는 가장 최근에 메모리에 기억된 가상페이지들이 실제 메모리 주소를 빠르게 변환하기 위해 만든 것으로 , OS 에서는 Kernel 에서 하나의 TLB 를 제공하며 , 나쵸스에서의 TLB 는 4 개의 Entry 를 가지고 있다 . - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Caching and Virtual Memory

Caching and Virtual Memory

20 조 OX 20010110 김정현20010362 이영재

Page 2: Caching and Virtual Memory

Assignment #1 software-management of the TLB

TLB 는 가장 최근에 메모리에 기억된 가상페이지들이 실제 메모리 주소를 빠르게 변환하기 위해 만든 것으로 , OS에서는 Kernel 에서 하나의 TLB 를 제공하며 , 나쵸스에서의 TLB 는 4 개의 Entry 를 가지고 있다 .

TranslationEntry class 에 TLB 가 정의되어 있다 .

우리가 해야 할 일은 nachos 가 제공하는 hardware 적인 simulated TLB 를 software 적으로 관리하는 일이다 . 이러한 상황은 , nachos 에서 TLB 를 사용하여 주소 변환을 하다가 TLB 에 원하는 entry 가 없을 때 , exception 이 발생하고 , 현재 실행중인 process 가 이를 감지하여 exception 을 해결해 주는 것이다 .

Page 3: Caching and Virtual Memory

TLB 를 통한 주소 변환translate() method in Processor.java

for (int i=0; i<tlbSize; i++) {

if (translations[i].valid && translations[i].vpn == vpn) {

entry = translations[i];

break;

}

}

if (entry == null) {

privilege.stats.numTLBMisses++;

Lib.debug(dbgProcessor, "\t\tTLB miss");

throw new MipsException(exceptionTLBMiss, vaddr);

}

Page 4: Caching and Virtual Memory

exceptionTLBMiss 의 처리 handleException() method in VMProcess.java

public void handleException(int cause) { Processor processor = Machine.processor(); switch (cause) {

case Processor.exceptionTLBMiss: /** TLB miss handling **/

default: super.handleException(cause);

break; }

}

Page 5: Caching and Virtual Memory

TLBMissing handling

1. TLB 에는 없으나 Kernel 의 page table 에는 변환정보가 있는 경우 .- 메모리에 기억되어 있지만 그 페이지가 최근에 접근되지 않은 경우 - 이 페이지의 관한 정보가 TLB 에 기록된다 .

2. TLB 에도 없고 Kernel 의 page table 에도 변환정보가 없는 경우 .- page fault!- Assignement #2 에서의 구현으로 원하는 page 를 메모리로 가져온다 . (demand page)- 이 페이지의 translation 정보를 kernel 의 page table 에 기록한다 .- 이 translation 의 정보 역시 TLB 에 기록한다 .

Page 6: Caching and Virtual Memory

Pseudo code

case Processor.exceptionTLBMiss: int vaddr = processor.readRegister(Processor.regBadVAddr);/* TLB Miss 를 낸 virtual address 를 읽는다 . *//* Kernel 을 invoke 시 켜 서 , 현 재 동 작 중 인 프 로 세 스 의 , address vaddr 을

포함하는 Entry 를 얻는다 . */ Page = VMKernel.findPage (getId (), Processor.pageFromAddress (vaddr)); Processor.writeTLBEntry (TLBcount, page);

/* 저장할 값을 가져와서 TLB 에 쓴다 . */ TLBcount = (TLBcount + 1) % processor.getTLBSize ();/* TLB count 조정 - FIFO */

break;

Page 7: Caching and Virtual Memory

TLB invalidate

TLB 에는 process id 에 대한 정보가 없다 .-> process 가 다른 process 의 정보를 access 할 수 도 있음 !

Context Switching 이 일어날 때 현재 쓰던 페이지 정보에 대해서는 invalidate 시켜주어야 한다 .

Implement saveState() method in VMProcess class

Page 8: Caching and Virtual Memory

Pseudo code

public void saveState() {

for( all TLB ){

TLBEntry,valid = false // invalidate

if( TLBEntry.dirty bit or TLBEntry.used bit is true ){ VMKernel.findPage( getId() , dummyEntry.vpn ).dirty = dummyEntry.dirty; VMKernel.findPage( getId() , dummyEntry.vpn ).used = dummyEntry.used; }

Machine.processor().writeTLBEntry( i , TLBEntry);

} return;}

Page 9: Caching and Virtual Memory

Inverted Page Table

프로젝트 3 에서는 2 번과는 달리 page table 을 각 프로세스 마다 갖지 않고 , 커널에 하나만이 존재한다 . (Inverted Page Table)

이를 위해서는 Page Table 에 PID,VPN,PPN 이 함께 들어가야 한다

커널의 Page Table 을 검사하는 시간을 줄이기 위해 Hash table 을 이용한다 . Hash table 은 java.util 을 이용하며 Key 값은 PID 가 된다 .

Page 10: Caching and Virtual Memory

Load, Unload Section

프로젝트 2 에서는 UserProcess class 의 생성자에서 page table 을 새로 만들고 , vpn-ppn 의 정보를 이 page table 에 넣었다

이번 프로젝트 3 에서는 이 대신 Kernel 에서 만든 하나의 Inverted page table 에 pid-vpn-ppn 의 정보를 저장한다 .

각 process 의 vpn 에 ppn 을 대응시키는 작업은 Kernel 에서 해준다

Unload 역시 마찬가지로 inverted page table 에서 vpn 에 맞는 ppn을 찾아서 없애주고 , page table 내에서도 그 정보를 지워준다 .

이 작업들은 커널 안의 한 data(inverted page table) 을 다루므로 atomic 하게 수행하기 위해 lock 을 사용한다 .

Page 11: Caching and Virtual Memory

Assignment #2 Demand paging of virtual memory

Process 실행에 필요한 page 만을 physical memory 에 올려서 실제 메모리보다 더 큰 메모리를 필요로 하는 프로그램을 실행 가능하게 한다 .

Page fault 가 일어났을 때 , physical memory 가 full 이라면 , 다음의 알고리즘들을 이용하여 , momory 상의 한 페이지를 disk 로 back-up 하고 , 그 자리에 새 page 를 load 한다 .

FIFO, RANDOM, LRU 등

TLB 와 Kernel 의 inverted page table 을 update 한다 .

Page 12: Caching and Virtual Memory

loadSection() , findPage()

loadSection()

findPage()1. 원하는 page 가 inverted page table 에 있으면 반환한다 .

2. 원하는 page 가 없을 경우 - 메모리가 꽉 차지 않았을 경우

swap file 에 있을 경우 : swap file 에서 page 로 copy 후 page return swap file 에 없을 경우 : assignment #3 “lazy loading”

- 메모리가 꽉 찼을 경우 handlePageFault() 를 이용해서 physical memory 하나를 비운 후 page 를 load 하고 return

Page 13: Caching and Virtual Memory

findPage() - Pseudo code

public static TranslationEntry findPage( int pid, int vpn) {

// 찾으려는 페이지가 메모리에 있으면 , inverted page Table 에서 entry 를 찾아서 반환한다 . TranslationEntry temp = invfindPage( pid , vpn );if ( temp != null ) return temp;

// 메모리가 꽉 차 있지 않은 상태에서 page fault 가 발생했을때int j = virMem.getNewVirpage();

// 메모리가 꽉 차 있는 상태에서 page fault 가 발생했을때handlePageFault(); int j = virMem.getNewVirPage();

“Read from Swap file” or “Lazy Loading” to physical Memory

return dumEntry = new TranslationEntry( vpn, j, , , , );

Page 14: Caching and Virtual Memory

handlePageFault - Pseudo code

public static void handlePageFault() { ppn = getFP(); if (ppn != -1){ // 그 사이 free physical page 가 생겼다면

return; } Replacement Algorithm 을 이용 , (ex : Clock algorithm) physical memroy 에서 내려질 page 를 찾는다 .

read only 일 경우 : page 를 지우고 return 한다 .dirty bit 이 set 된 경우 : swap file 에 저장한 후 , page 를 지우고 return

한다 .}

Page 15: Caching and Virtual Memory

Swap file

Memory 가 부족할 때 , page 를 disk 에 back up 하게 되는데 , 이때 Swap file 을 사용한다 .

Swap file 은 모든 process 들이 공유하는 하나의 file 이다 . Swap file 에 씌여있는 page 들의 정보들은 SwapList 라는 linked li

st 를 이용하여 저장한다 . SwapList 는 SwapNode 라는 Data Structure 들의 linked list 이며 ,

pid, vpn, offset, NextNode 로 이루어져 있다 . pid 와 vpn 을 이용하여 , SwapList 를 검색하게 되고 offset 을

이용하여 Swap file 의 어디에 이 page 가 back up 되어 있는지 알 수 있다 .

SwapList 역시 kernel 에 만들어지는 단 하나의 DS 이며 , atomic한 수행을 위해 lock 을 이용한다 .

Page 16: Caching and Virtual Memory

Swap list

Page 17: Caching and Virtual Memory

Swap list (cont’)

public static void addSwap( ) public static swapNode findLastNodeSwap( ) public static boolean isInThisListSwap( ) public static int findOffsetSwap( ) public static swapNode findNodeSwap( ) public static void deleteSwap( )

Page 18: Caching and Virtual Memory

Initialize swap file and list - Pseudo code

public void initialize(String[] args) {super.initialize(args);

// 사용할 swap file 의 이름을 얻어서 , swap file 을 열어 본다swapFileName = new String("VM_SWAP_FILE");swapFile = fileSystem.open( swapFileName , false );

// 만약 swapFile 이 존재하면 nachos 가 비정상적으로 종료된 것이므로 swapfile 을 지운다 .

if ( swapFile != null ) fileSystem.remove(swapFileName);

//swap file 을 열고 , SwapList 를 하나 생성한다 .swapFile = fileSyste.open( swapFileName, true);swapList = new SwatList();

}

Page 19: Caching and Virtual Memory

Assignment #3 Lazy loading

시작 시에 모든 code 와 data 를 읽어 들이지 않고 , page table entry 들만을 설정해서 , page fault 가 일어날 때마다 executable 에서 page 를 읽어서 memory 에 loading

page fault 가 일어나면• set up page table entries

• read the pages from the executable into memory on demand

Modify loadSection(), findPage()

Page 20: Caching and Virtual Memory

loadSection()

Process 가 initialize 될 때의 loadSection() method 를 수정하여 , 시작시에는 아무 페이지도 load 되지 않도록 한다 .

대신 시작 시 , Field 라는 형태의 data structure 배열에서 테이블의 정보를 기억해두고 , Page Fault 가 났을 때 , 이 정보를 이용하여 excutable 에서 page 를 읽어서 memory 에 load 한다 .

static class sectionField{

public int secNum;

public int offset;

}

SectionNum Offset

Page 21: Caching and Virtual Memory

loadSection() (cont’)

protected boolean loadSections() {secfield = new sectionField[pageSize];

int vpn = -1;

Don’t load Section, Instead…

for ( int s=0; s<coff.getNumSections(); s++){ CoffSection section = coff.getSection(s);

for (int i=0; i<section.getLength(); i++) { vpn = section.getFirstVPN()+i;

secfield[vpn] = new sectionField();secfield[vpn].secNum = s;secfield[vpn].offset = i;

} }

return true;}

Page 22: Caching and Virtual Memory

findPage()

Project #2 에서는 findPage() 메소드를 호출하면 , 그 Page 만 반환하면 되었으나 , lazy loading 에서는 그 Page 가 Coff section 의 page 이면 , 첨부터 페이지 테이블을 안 만들어 놓았으므로 , 이를 load 한 다음 return 해야 한다 .

현재 프로세스가 실행중일 때 , vpn 을 찾으려는 요청이 들어오고 , 그것이 참조하는 페이지가 coff Section 안에 들어있는 경우

: 그 section 을 physical memory 에 load 한다 .

section 이 Read-Only 일 경우 :: Entry 에 Read-Only 임을 Check 해 준다 .

Page 23: Caching and Virtual Memory

findPage() (cont’)

public static TranslationEntry findPage( int pid, int vpn) {……

if(swap file 에도 없다면 )j= 현재 비어있는 ppnpro = (VMProcess)currentProcess();

if ( pro != null && pro.secfield[vpn] != null){ CoffSection section = pro.coff.getSection(pro.secfield[vpn].secNum); section.loadPage( pro.secfield[vpn].offset , j );

if ( section.isReadOnly() ){ 위 페이지의 readOnly = true;

}}……

}

Page 24: Caching and Virtual Memory

Assignment #4 mmap syscall

In syscall.h Map the file referenced by fileDescriptor into memory at address. To maintain consistency, further calls to read() and write() on this fil

e descriptor will fail (returning -1) until the file descriptor is closed. -> file descriptor 에 mmap 이라는 flag 를 추가해서 read 나 write할때 flag 를 검사한다 .

When the file descriptor is closed, all remaining dirty pages of the map will be flushed to disk and the map will be removed -> mmap 된 file 이름과 address 를 같이 갖고 있는 list 를 만든다 .

Returns the length of the file on success, or -1 if an error occurred.

Page 25: Caching and Virtual Memory

Pseudo code

SyscallMmap = 10;Int handleMmap(int fdNum, int address){

mmapfilelist.add(fds[fdNum].name, address)fds[fdNum].Mmap=true;filesize=fds[fdNum].OpenFile.length;byte[] temp = new byte[filesize];fds[fdNum].OpenFile.read(temp, 0, filesize);writeVirtualMemory(address, temp, 0, filesize);return 1;

}

Page 26: Caching and Virtual Memory

Pseudo code

int handleRead(int fdNum, int bf, int count){…if(fds[fdNum].mmap==true)

return -1;…

} int handleWrite(int fdNum, int bf, int count){

…if(fds[fdNum].mmap==true)

return -1;…

}

Page 27: Caching and Virtual Memory

Pseudo code

Int handleClose(int fdNum){…if(fds[fdNum].mmap){mmapfilelist 에서 해당되는 file 이 mmap 되있는 address 를 찾는다 . String temp=readVirtualMemoryString(address, MaxLength); length=temp.Length(); while(length!=0){

address+length 범위의 vpn 들에 해당되는 ppn 들을 찾고 수정 된 page 들이 있으면 실제 file 에 기록해준다 .

}}

…}

Page 28: Caching and Virtual Memory

Pseudo code

- In cp.c int main(int argc, char *argv[]){

char orig[MaxLength]; char des[MaxLength];int fd1=fopen(argv[1]); int fd2=fopen(argv[2]);mmap(fd1, orig);mmap(fd2, des);strcpy(orig, des);close(fd1); close(fd2);

}