virtual memory

58
Virtual Memory

Upload: veda-everett

Post on 02-Jan-2016

51 views

Category:

Documents


2 download

DESCRIPTION

Virtual Memory. Virtual Memory. Background Demand Paging Copy-on-Write Page Replacement Allocation of Frames Thrashing Memory-Mapped Files Allocating Kernel Memory Other Considerations Operating-System Examples. Objectives. To describe the benefits of a virtual memory system - PowerPoint PPT Presentation

TRANSCRIPT

No Slide Title

Virtual MemoryVirtual MemoryBackgroundDemand PagingCopy-on-WritePage ReplacementAllocation of Frames ThrashingMemory-Mapped FilesAllocating Kernel MemoryOther ConsiderationsOperating-System Examples2ObjectivesTo describe the benefits of a virtual memory system

To explain the concepts of demand paging, page-replacement algorithms, and allocation of page frames

To discuss the principle of the working-set model3BackgroundCode needs to be in memory to execute, but entire program rarely usedError code, unusual routines, large data structuresEntire program code not needed at same timeConsider ability to execute partially-loaded programProgram no longer constrained by limits of physical memoryProgram and programs could be larger than physical memory

4BackgroundVirtual memory separation of user logical memory from physical memoryOnly part of the program needs to be in memory for executionLogical address space can therefore be much larger than physical address spaceAllows address spaces to be shared by several processesAllows for more efficient process creationMore programs running concurrentlyLess I/O needed to load or swap processes

Virtual memory can be implemented via:Demand paging Demand segmentation5Virtual Memory That is Larger Than Physical Memory

6Virtual-address Space

7Virtual Address SpaceEnables sparse address spaces with holes left for growth, dynamically linked libraries, etcSystem libraries shared via mapping into virtual address spaceShared memory by mapping pages read-write into virtual address spacePages can be shared during fork(), speeding process creation

Shared Library Using Virtual Memory

9Demand PagingCould bring entire process into memory at load timeOr bring a page into memory only when it is neededLess I/O needed, no unnecessary I/OLess memory needed Faster responseMore users

Page is needed reference to itinvalid reference abortnot-in-memory bring to memory

Lazy swapper never swaps a page into memory unless page will be neededSwapper that deals with pages is a pager

10Transfer of a Paged Memory to Contiguous Disk Space

11Valid-Invalid BitWith each page table entry a validinvalid bit is associated(v in-memory memory resident, i not-in-memory)Initially validinvalid bit is set to i on all entriesExample of a page table snapshot:

During address translation, if validinvalid bit in page table entry is I page faultvvvviii.Frame #valid-invalid bitpage table12Page Table When Some Pages Are Not in Main Memory

13Page FaultIf there is a reference to a page, first reference to that page will trap to operating system: page faultOperating system looks at another table to decide:Invalid reference abortJust not in memoryGet empty frameSwap page into frame via scheduled disk operationReset tables to indicate page now in memorySet validation bit = vRestart the instruction that caused the page fault14Aspects of Demand PagingExtreme case start process with no pages in memoryOS sets instruction pointer to first instruction of process, non-memory-resident -> page faultAnd for every other process pages on first accessPure demand pagingActually, a given instruction could access multiple pages -> multiple page faultsPain decreased because of locality of referenceHardware support needed for demand pagingPage table with valid / invalid bitSecondary memory (swap device with swap space)Instruction restartInstruction RestartConsider an instruction that could access several different locationsblock move

auto increment/decrement locationRestart the whole operation?What if source and destination overlap?16Steps in Handling a Page Fault

17Performance of Demand PagingStages in Demand PagingTrap to the operating systemSave the user registers and process stateDetermine that the interrupt was a page faultCheck that the page reference was legal and determine the location of the page on the diskIssue a read from the disk to a free frame:Wait in a queue for this device until the read request is servicedWait for the device seek and/or latency timeBegin the transfer of the page to a free frameWhile waiting, allocate the CPU to some other userReceive an interrupt from the disk I/O subsystem (I/O completed)Save the registers and process state for the other userDetermine that the interrupt was from the diskCorrect the page table and other tables to show page is now in memoryWait for the CPU to be allocated to this process againRestore the user registers, process state, and new page table, and then resume the interrupted instruction

18Performance of Demand Paging (Cont.)Page Fault Rate 0 p 1if p = 0 no page faults if p = 1, every reference is a fault

Effective Access Time (EAT)EAT = (1 p) x memory access+ p (page fault overhead + swap page out + swap page in + restart overhead )19Demand Paging ExampleMemory access time = 200 nanosecondsAverage page-fault service time = 8 milliseconds

EAT = (1 p) x 200 + p (8 milliseconds) = (1 p x 200 + p x 8,000,000 = 200 + p x 7,999,800If one access out of 1,000 causes a page fault, then EAT = 8.2 microseconds. This is a slowdown by a factor of 40!!If want performance degradation < 10 percent220 > 200 + 7,999,800 x p20 > 7,999,800 x pp < .0000025< one page fault in every 400,000 memory accesses20Demand Paging OptimizationsCopy entire process image to swap space at process load timeThen page in and out of swap spaceUsed in older BSD Unix

Demand page in from program binary on disk, but discard rather than paging out when freeing frameUsed in Solaris and current BSDCopy-on-WriteCopy-on-Write (COW) allows both parent and child processes to initially share the same pages in memoryIf either process modifies a shared page, only then is the page copiedCOW allows more efficient process creation as only modified pages are copiedIn general, free pages are allocated from a pool of zero-fill-on-demand pagesWhy zero-out a page before allocating it?vfork() variation on fork() system call has parent suspend and child using copy-on-write address space of parentDesigned to have child call exec()Very efficient22Before Process 1 Modifies Page C

23After Process 1 Modifies Page C

24What Happens if There is no Free Frame?Used up by process pagesAlso in demand from the kernel, I/O buffers, etcHow much to allocate to each?

Page replacement find some page in memory, but not really in use, page it outAlgorithm terminate? swap out? replace the page?Performance want an algorithm which will result in minimum number of page faults

Same page may be brought into memory several times25Page ReplacementPrevent over-allocation of memory by modifying page-fault service routine to include page replacement

Use modify (dirty) bit to reduce overhead of page transfers only modified pages are written to disk

Page replacement completes separation between logical memory and physical memory large virtual memory can be provided on a smaller physical memory26Need For Page Replacement

27Basic Page ReplacementFind the location of the desired page on disk

Find a free frame: - If there is a free frame, use it - If there is no free frame, use a page replacement algorithm to select a victim frame- Write victim frame to disk if dirty

Bring the desired page into the (newly) free frame; update the page and frame tables

Continue the process by restarting the instruction that caused the trap

Note now potentially 2 page transfers for page fault increasing EAT28Page Replacement

29Page and Frame Replacement AlgorithmsFrame-allocation algorithm determines How many frames to give each processWhich frames to replacePage-replacement algorithmWant lowest page-fault rate on both first access and re-access

Evaluate algorithm by running it on a particular string of memory references (reference string) and computing the number of page faults on that stringString is just page numbers, not full addressesRepeated access to the same page does not cause a page faultIn all our examples, the reference string is 7,0,1,2,0,3,0,4,2,3,0,3,0,3,2,1,2,0,1,7,0,130Graph of Page Faults Versus The Number of Frames

31First-In-First-Out (FIFO) AlgorithmReference string: 7,0,1,2,0,3,0,4,2,3,0,3,0,3,2,1,2,0,1,7,0,13 frames (3 pages can be in memory at a time per process)

Can vary by reference string: consider 1,2,3,4,1,2,5,1,2,3,4,5Adding more frames can cause more page faults!Beladys Anomaly

How to track ages of pages? Just use a FIFO queue7011232304 0 72 1 03 2 115 page faults32FIFO Page Replacement

33FIFO Illustrating Beladys Anomaly

34Optimal AlgorithmReplace page that will not be used for longest period of time9 is optimal for the example on the next slideHow do you know this?Cant read the future

Used for measuring how well your algorithm performs35Optimal Page Replacement

36Least Recently Used (LRU) AlgorithmUse past knowledge rather than futureReplace page that has not been used in the most amount of timeAssociate time of last use with each page

12 faults better than FIFO but worse than OPTGenerally good algorithm and frequently usedBut how to implement?

37LRU Algorithm (Cont.)Counter implementationEvery page entry has a counter; every time page is referenced through this entry, copy the clock into the counterWhen a page needs to be changed, look at the counters to find smallest valueSearch through table neededStack implementationKeep a stack of page numbers in a double link form:Page referenced:move it to the toprequires 6 pointers to be changedBut each update more expensiveNo search for replacementLRU and OPT are cases of stack algorithms that dont have Beladys Anomaly38Use Of A Stack to Record The Most Recent Page References

39LRU Approximation AlgorithmsLRU needs special hardware and still slowReference bitWith each page associate a bit, initially = 0When page is referenced bit set to 1Replace any with reference bit = 0 (if one exists)We do not know the order, howeverSecond-chance algorithmGenerally FIFO, plus hardware-provided reference bitClock replacementIf page to be replaced has Reference bit = 0 -> replace itreference bit = 1 then:set reference bit 0, leave page in memoryreplace next page, subject to same rules40Second-Chance (clock) Page-Replacement Algorithm

41Counting AlgorithmsKeep a counter of the number of references that have been made to each pageNot common

LFU Algorithm: replaces page with smallest count

MFU Algorithm: based on the argument that the page with the smallest count was probably just brought in and has yet to be used42Page-Buffering AlgorithmsKeep a pool of free frames, alwaysThen frame available when needed, not found at fault timeRead page into free frame and select victim to evict and add to free poolWhen convenient, evict victimPossibly, keep list of modified pagesWhen backing store otherwise idle, write pages there and set to non-dirtyPossibly, keep free frame contents intact and note what is in themIf referenced again before reused, no need to load contents again from diskGenerally useful to reduce penalty if wrong victim frame selected Applications and Page ReplacementAll of these algorithms have OS guessing about future page accessSome applications have better knowledge i.e. databasesMemory intensive applications can cause double bufferingOS keeps copy of page in memory as I/O bufferApplication keeps page in memory for its own workOperating system can given direct access to the disk, getting out of the way of the applicationsRaw disk modeBypasses buffering, locking, etc

Allocation of FramesEach process needs minimum number of framesExample: IBM 370 6 pages to handle SS MOVE instruction:instruction is 6 bytes, might span 2 pages2 pages to handle from2 pages to handle toMaximum of course is total frames in the systemTwo major allocation schemesfixed allocationpriority allocationMany variations45Fixed AllocationEqual allocation For example, if there are 100 frames (after allocating frames for the OS) and 5 processes, give each process 20 framesKeep some as free frame buffer pool

Proportional allocation Allocate according to the size of processDynamic as degree of multiprogramming, process sizes change

46Priority AllocationUse a proportional allocation scheme using priorities rather than size

If process Pi generates a page fault,select for replacement one of its framesselect for replacement a frame from a process with lower priority number47Global vs. Local AllocationGlobal replacement process selects a replacement frame from the set of all frames; one process can take a frame from anotherBut then process execution time can vary greatlyBut greater throughput so more common

Local replacement each process selects from only its own set of allocated framesMore consistent per-process performanceBut possibly underutilized memory

48Non-Uniform Memory AccessSo far all memory accessed equallyMany systems are NUMA speed of access to memory variesConsider system boards containing CPUs and memory, interconnected over a system busOptimal performance comes from allocating memory close to the CPU on which the thread is scheduledAnd modifying the scheduler to schedule the thread on the same system board when possibleSolved by Solaris by creating lgroups Structure to track CPU / Memory low latency groupsUsed my schedule and pagerWhen possible schedule all threads of a process and allocate all memory for that process within the lgroup

ThrashingIf a process does not have enough pages, the page-fault rate is very highPage fault to get pageReplace existing frameBut quickly need replaced frame backThis leads to:Low CPU utilizationOperating system thinking that it needs to increase the degree of multiprogrammingAnother process added to the system

Thrashing a process is busy swapping pages in and out50Thrashing (Cont.)

51Demand Paging and Thrashing Why does demand paging work?Locality modelProcess migrates from one locality to anotherLocalities may overlap

Why does thrashing occur? size of locality > total memory sizeLimit effects by using local or priority page replacement52Locality In A Memory-Reference Pattern

53Working-Set Model working-set window a fixed number of page references Example: 10,000 instructions

WSSi (working set of Process Pi) =total number of pages referenced in the most recent (varies in time)if too small will not encompass entire localityif too large will encompass several localitiesif = will encompass entire program

D = WSSi total demand frames Approximation of locality

if D > m Thrashing

Policy if D > m, then suspend or swap out one of the processes54Working-set model

55Keeping Track of the Working SetApproximate with interval timer + a reference bit

Example: = 10,000Timer interrupts after every 5000 time unitsKeep in memory 2 bits for each pageWhenever a timer interrupts copy and sets the values of all reference bits to 0If one of the bits in memory = 1 page in working set

Why is this not completely accurate?

Improvement = 10 bits and interrupt every 1000 time units56Page-Fault FrequencyMore direct approach than WSSEstablish acceptable page-fault frequency rate and use local replacement policyIf actual rate too low, process loses frameIf actual rate too high, process gains frame

57Working Sets and Page Fault Rates