Presentation on theme: "Chapter 7: Main Memory Rev. by Kyungeun Park, 2015."— Presentation transcript:
1 Chapter 7: Main MemoryRev. by Kyungeun Park, 2015
2 Chapter 7: Memory Management BackgroundSwappingContiguous Memory AllocationPagingStructure of the Page TableSegmentationExample: The Intel 32 and 64-bit ArchitecturesExample: ARM Architecture
3 ObjectivesTo provide a detailed description of various ways of organizing memory hardwareTo discuss various memory-management techniques, including paging and segmentationTo provide a detailed description of the Intel Pentium, which supports both pure segmentation and segmentation with paging
4 BackgroundProgram must be brought (from disk) into memory and placed within a process for it to be runMain memory and registers are only storage CPU can access directlyMemory unit sees only a stream of memory addresses + read requests, or address + data and write requests.We are focusing on sequence of memory addresses generated by the running program.MotivationRegister are accessible within one cycle of the CPU clock.Whereas, main memory is accessed via a transaction on the memory bus.Completing a memory access may take many cycles of the CPU clock.Processor needs to stall, causing delay intolerable!Hardware-based Remedy: Cache, fast memory, between CPU and main memory on the CPU chip without any operating-system controlAdditional Remedy: Protection of memory required to ensure correct operation Base and Limit Registers provided by the hardware
5 Base and Limit Registers A pair of base (300040) and limit (120900) registers define the logical address spaceCPU hardware compares every address generated in user mode with the registers.Access to operating-system memory or other users’ memory results in a trap to the operating system.
6 Hardware Address Protection with Base and Limit Registers
7 Address BindingProcesses (actually programs) on disk, ready to be brought into memory to executefrom the input queueThe first address of the user process need not be 0000.Logical address and physical address mappingFurther, addresses are represented in different ways at different stages of a program’s lifeSource code addresses usually symbolicCompiled code addresses bind to relocatable addressesi.e. “14 bytes from beginning of this module”Linkage editor or loader will bind relocatable addresses to absolute addressesi.eEach binding maps one address space to another
8 Binding of Instructions and Data to Memory Address binding of instructions and data to memory addresses can happen at three different stagesCompile time: If memory location known a priori, absolute code can be generated; must recompile code if starting location changesLoad time: Must generate relocatable code if memory location is not known at compile timeExecution time: Binding delayed until run time if the process can be moved during its execution from one memory segment to anotherNeed hardware support for address mapping (e.g., base and limit registers)
10 Logical vs. Physical Address Space The concept of a logical address space that is bound to a separate physical address space is central to proper memory managementLogical address – generated by the CPU; also referred to as virtual addressPhysical address – address seen by the memory-management unitLogical and physical addresses are the same in compile-time and load-time address-binding schemesLogical (virtual) and physical addresses differ in execution-time address-binding schemeLogical address space is the set of all logical addresses generated by a programPhysical address space is the set of all physical addresses corresponding to the logical addresses
11 Memory-Management Unit (MMU) Hardware device that maps virtual to physical address at run timeMany methods possible, covered in the rest of this chapterTo start, consider simple scheme where the value in the relocation register is added to every address generated by a user process at the time it is sent to memoryBase register now called relocation registerMS-DOS on Intel 80x86 used 4 relocation registersThe user program deals with logical addresses; it never sees the real physical addressesExecution-time binding occurs when reference is made to location in memoryLogical address bound to physical addresses
12 Dynamic relocation using a relocation register (based register) Routine is not loaded until it is calledBetter memory-space utilization; unused routine is never loadedAll routines kept on disk in relocatable load formatUseful when large amounts of code are needed to handle infrequently occurring casesNo special support from the operating system is requiredImplemented through program designOS can help by providing libraries to implement dynamic loading
13 Dynamic LinkingStatic linking – system libraries and program code combined by the loader into the binary executable program imagewaste of disk space and main memoryDynamic linking – linking postponed until execution timeStub, a small piece of code, is included in the image for each library-routine referenceStub is used to locate the appropriate memory-resident library routineWhen the stub is executed, it checks if routine is in processes’ memory addressIf not in address space, the program loads the routine into memory address space.Stub replaces itself with the address of the routine, and executes the routineDynamic linking is particularly useful for language libraries only one copy of the library codeConsider applicability to patching system librariesVersion information is neededSystem also known as shared libraries
14 SwappingA process can be swapped temporarily out of memory to a backing store, and then brought back into memory for continued executionTotal physical memory space of processes can exceed physical memorye.g.) a multiprogramming environment with a RR CPU-schedulingWhen a quantum expires, swap starts and CPU-scheduling will be done.The quantum: large enough to allow reasonable amounts of computing to be done between swaps.Backing store – fast disk large enough to accommodate copies of all memory images for all users; must provide direct access to these memory imagesRoll out, roll in – swapping variant used for priority-based scheduling algorithms;lower-priority process is swapped out so higher-priority process can be loaded and executedSystem maintains a ready queue of ready-to-run processes which have memory images on diskDoes the swapped out process need to swap back into the same physical addresses?Depends on the address binding schemes : Plus pending I/O to/from process memory spaceAssembly or load-time binding : the process cannot be easily moved to a different location.Execution-time binding : the process can be swapped into a different memory space.Plus pending I/O to/from process memory space
15 Schematic View of Swapping Dispatcher checks to see whether the next process in the queue is in memory.If it is not, and if no free memory regionThe dispatcher swaps out a process and swaps in target process.Then, reloads registers and transfers control to the selected process
16 Context Switch Time including Swapping Context switch time can then be very high100MB process swapping to hard disk with transfer rate of 50MB/se100 MB/50 MB per second = 2 secondsSwap out time of 2000 ms (2 seconds)Plus swap in of same sized process : 2000 ms (2 seconds)Total context switch swapping component time of 4000 ms (4 seconds)Major part of swap time is transfer time; total transfer time is directly proportional to the amount of memory swappedCan reduce swap time by swapping out small size of memory by knowing how much memory really being usedUser must keep the system informed of any changes in memory requirements.A process with dynamic memory requirements need to issue system calls to inform OS of changing memory needs via request_memory() and release_memory().
17 Context Switch Time including Swapping (cont.) Make sure to swap out an idle processPlus consider pending I/OSwap out process P1 and swap in process P2 : I/O operation of process P1 might attempt to use memory now belonging to process P2 Two main solutions to this problem1. never swap a process with pending I/O2. execute I/O operations only into operating-system buffers (kernel space), then transfer between operating-system buffers to process memory then the process is swapped in.Modified versions of swapping are found on many systems (i.e., UNIX, Linux, and Windows)Swapping is normally disabledSwapping will start if more than threshold amount of memory allocatedSwapping is disabled again once memory demand reduced below threshold
18 Swapping on Mobile Systems Not typically supportedFlash memory basedSmall amount of spaceLimited number of write cyclesPoor throughput between flash memory and CPU on mobile platformInstead use other methods to free memory if lowiOS asks apps to voluntarily relinquish allocated memoryRead-only data thrown out and reloaded from flash if neededFailure to free can result in terminationAndroid terminates apps if low free memory, but first writes application state to flash for fast restartBoth OSes support paging
19 Contiguous Allocation Main memory must support both OS and user processesLimited resource, must allocate efficientlyMain memory usually divided into two partitions:Resident operating system, usually held in low memory with interrupt vectorUser processes then held in high memoryIn contiguous memory allocation, each process contained in single contiguous section of memoryRelocation registers with limit register used to protect user processes from each other, and from changing operating-system code and dataBase relocation register contains value of smallest physical addressLimit register contains range of logical addresses – each logical address must be less than the limit registerMMU maps logical address dynamicallyRelocation-register scheme provides an effective way to allow OS’s size to change dynamically Flexibilitytransient operating-system code (uncommon device driver) removed from memoryUsing transient code changes the size of the OS during program execution
20 Hardware Support for Relocation and Limit Registers
21 Contiguous Allocation (Cont.) Multiple-partition allocationThe simplest method is to divide memory into several fixed-sized partitionsEach partition may contain exactly one process.Degree of multiprogramming limited by number of partitionsIn the variable-partition scheme, a hole – initially, one large block of available memory;Eventually, a set of holes of various size, scattered throughout memoryWhen a process arrives, it is allocated memory from a hole large enough to accommodate itProcess exiting frees its partition, adjacent free partitions combinedOperating system maintains information about: a) allocated partitions b) free partitions (hole)OSOSOSOSprocess 5process 5process 5process 5process 9process 9process 8process 10process 2process 2process 2process 2
22 Dynamic Storage-Allocation Problem How to satisfy a request of size n from a list of free holes?First-fit: Allocate the first hole that is big enoughBest-fit: Allocate the smallest hole that is big enough; must search entire list, unless ordered by sizeProduces the smallest leftover holeWorst-fit: Allocate the largest hole; must also search entire listProduces the largest leftover holeAccording to simulations, first-fit and best-fit are better than worst-fit in terms of speed and storage utilization. First-fit is generally faster.
23 FragmentationExternal Fragmentation – when total memory space exists to satisfy a request, but the available spaces are not contiguous.Storage is fragmented into a large number of small holes caused by first-fit and best-fit strategies for memory allocation plus variable-partition schemeInternal Fragmentation – when allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being usedFirst fit analysis reveals that given N blocks allocated, 0.5 N blocks are lost to fragmentation1/3 may be unusable known as the 50-percent rule
24 Fragmentation (Cont.)One solution to the external fragmentation : compactionShuffle memory contents to place all free memory together in one large blockMove all processes toward one end of memoryAll holes move in the other direction with one large hole of available memory produced.Expensive schemeCompaction is possible only if:relocation is dynamic and is done at execution timeI/O problemLatch job in memory while it is involved in I/ODo I/O only into OS buffersAnother solution to the external-fragmentation problempermitting the logical address space of the processes to be non-contiguousSegmentation and pagingNow consider that backing store has the same fragmentation problems as main memory.
25 SegmentationSegmentation is a memory-management scheme that supports user (programmer) ’s view of memorySegmentation as a hardware supported memory mechanism:mapping the programmer’s view to the actual physical memoryA program is a collection of segmentsA segment is a logical unit such as:main programprocedurefunctionmethodobjectlocal variables, global variablescommon blockstacksymbol tablearrays
26 Programmer’s View of a Program Logical address space is a collection of segments.Each segment has a name and a length.<segment-number, offset>While Compiling, the compiler automatically constructs segments reflecting the input program.Since segments vary in length, memory allocation is a dynamic storage-allocation problem.
27 Logical View of Segmentation 14231234user spacephysical memory space
28 Segmentation Hardware Logical address consists of a two tuple:<segment-number, offset>Segment number – an index to the segment tableOffset – be between 0 and the segment limit, if it exceeds the segment limit, trap to OSMap two-dimensional programmer-defined addresses into one-dimensional physical addressesMapping through a segment table – each table entry has:Segment base – contains the starting physical address where the segments reside in memorySegment limit – specifies the length of the segmentThe segment table is an array of base-limit register pairs.Segment-table base register (STBR) points to the segment table’s location in memorySegment-table length register (STLR) indicates number of segments used by a program;segment number s is legal, if s < STLR
30 Example of Segmentation Separate entryfor each segment
31 PagingPhysical address space of a process is allowed to be noncontiguous; process is allocated physical memory whenever availableAvoids external fragmentation and the need for compaction.Basic method for implementing paging:Breaking physical memory into fixed-sized blocks called framesDividing logical memory into blocks of same size called pagesWhen executing a process, its pages are loaded into any available memory frames from their source (a file system or the backing store)To run a program of size N pages, need to find N free frames and load programBacking store is divided into fixed-sized blocks that are of the same size as the memory framesKeep track of all free framesStill have internal fragmentation
32 Address Translation Scheme Address generated by CPU is divided into:Page number (p) – used as an index into a page table which contains base address of each page in physical memoryPage offset (d) – used as a displacement, combined with base address to define the physical memory address that is sent to the memory unitPage size (frame size) is defined by the hardware.Size is power of 2, between 512 bytes and 16 Mbytes per page.For given logical address space 2m and page size 2nHigh-order m-n bits of a logical address designates the page numbern low-order bits designate the page offsetLogical address structure:p is an index into the page table and d is the displacement within the pagepage numberpage offsetpdm - nn
33 Hardware Support for Paging Every address generated by the CPU is divided into two parts:a page number (p) anda page offset (d)Page number is used as an index into a page table.Page table contains the base address of each page inphysical memory.
35 Paging Example 1 2 3 4 5 6 In the logical address, n=2 and m=4. Frame No.1234567In the logical address, n=2 and m=4.Using 32-byte physical memory and 4-byte pages
36 Paging (Cont.) Calculating internal fragmentation Page size = 2,048 bytes (n=11)Process size = 72,766 bytes35 pages (71,680 bytes)+ 1,086 bytesInternal fragmentation of 2, ,086 = 962 bytesWorst case fragmentation = 1 frame – 1 byteOn average fragmentation = 1 / 2 frame sizeSo small frame sizes desirable. But overheadBut each page table entry takes memory to trackDisk I/O burdenAs a result, page sizes growing over timeSolaris supports two page sizes – 8 KB and 4 MB
37 Paging (Cont.)Clear separation between the programmer’s view of memory and the actual physical memory.Programmer’s view: as one single space (in fact, scattered)The mapping is hidden from the programmer and is controlled by the OS.By implementation, the user process can only access its own memory.Page table includes only those pages that the process ownsThe OS must be aware of the allocation details of physical memory.
39 Implementation of Page Table Page table for each process is kept in main memory.PCB contains a pointer to the page table like the other register values, the instruction counter.Page-table base register (PTBR) points to the page table.Page-table length register (PRLR) indicates size of the page table.In this scheme, every data/instruction access requires two memory accessesOne for the page table and one for the data / instructionThe two memory access problem can be solved by the use of a special fast-lookup hardware cache called associative memory or translation look-aside buffers (TLBs)Some TLBs store address-space identifiers (ASIDs) in each TLB entry – uniquely identifies each process to provide address-space protection for that processOtherwise need to flush at every context switch in order to prevent the next executing process from using the wrong translation informationTLBs typically small (64 to 1,024 entries)On a TLB miss, value is loaded into the TLB for faster access next timeReplacement policies must be consideredSome entries can be wired down for permanent fast access (e.g. TLB entries for kernel code)
40 Associative Memory, TLB Associative memory – parallel searchAddress translation (p, d)If p is in associative register, get frame # outOtherwise get frame # from page table in memoryPage #Frame #
42 Effective Access Time Associative Lookup = time unit Hit ratio = Can be < 10% of memory access timeHit ratio = Hit ratio – percentage of times that a page number is found in the associative registers; ratio related to number of associative registersConsider = 80%, = 20ns for TLB search, 100ns for memory accessEffective Memory Access Time (EAT)EAT = 0.80 x x 220 = 140 nsConsider slower memory but better hit ratio -> = 98%, = 20ns for TLB search, 140ns for memory accessEAT = 0.98 x x 300 = ns
43 Memory ProtectionMemory protection implemented by associating protection bit with each frame to indicate if read-only or read-write access is allowedCan also add more bits to indicate page execute-only, and so onValid-invalid bit attached to each entry in the page table:“valid” indicates that the associated page is in the process’s logical address space, and is thus a legal page“invalid” indicates that the page is not in the process’s logical address spaceOr use PTLR (Page-Table Length Register)Any violations result in a trap to the kernel
45 Shared Pages Advantage of paging Shared code Private code and data Possibility of sharing common codeImportant in a time-sharing environmentShared codeOne copy of read-only (reentrant) code shared among processes (i.e., text editors, compilers, window systems)Similar to multiple threads sharing the same process spaceAlso useful for interprocess communication if sharing of read-write pages is allowedPrivate code and dataEach process keeps a separate copy of the code and dataThe pages for the private code and data can appear anywhere in the logical address space
47 Structure of the Page Table Memory structures for paging can get huge using straight-forward methodsConsider a 32-bit logical address space as on modern computersPage size of 4 KB (212)Page table would have 1 million entries (232 / 212)If each entry is 4 bytes 4 MB of physical address space / memory for page tableThat amount of memory used to cost a lotDon’t want to allocate page table contiguously in main memorySolution to this problem is to divide the page table into smaller pieces.Hierarchical PagingHashed Page TablesInverted Page Tables
48 Hierarchical Page Tables Break up the logical address space into multiple page tablesA simple technique is a two-level page tableWe then page the page table
50 Two-Level Paging Example A logical address (on 32-bit machine with 1K page size) is divided into:a page number consisting of 22 bitsa page offset consisting of 10 bitsSince the page table is paged, the page number is further divided into:a 12-bit page numbera 10-bit page offsetThus, a logical address is as follows:where p1 is an index into the outer page table, and p2 is the displacement within the page of the inner page tableKnown as forward-mapped page tablepage numberpage offsetp1p2d121010
52 64-bit Logical Address Space Even two-level paging scheme not sufficientIf page size is 4 KB (212)Then page table has 252 entriesIf two level scheme, inner page tables could be 210 entries * 4-byteAddress would look likeOuter page table has 242 entries * 4 bytes per entry = 244 bytesOne solution is to add a 2nd outer page tableBut in the following example the 2nd outer page table is still 234 bytes in sizeAnd possibly 4 memory access to get to one physical memory locationouter pageinner pagepage offsetp1p2d421012
54 Hashed Page TablesCommon approach for handling address spaces larger than 32 bits with the hash value being the virtual page numberThe virtual page number is hashed into a page tableEach entry in the hash table contains a chain (linked list) of elements hashing to the same location.Each element contains three fields:(1) the virtual page number(2) the value of the mapped page frame(3) a pointer to the next element in the chain (linked list)Virtual page numbers are compared in this chain searching for a matchIf a match is found, the corresponding physical frame is extracted
56 Inverted Page TableRather than each process having a page table and keeping track of all possible logical pages, track all physical pagesOne entry for each real page (or frame) of memory is added.Entry consists of the virtual address of the page stored in that real memory location, with information about the process that owns that pageASID (address-space identifier) in each entry of the inverted page tableOnly one page table is in the system.Simplified version of the inverted page table used in the IBM RT.Virtual address<process-id, page-number, offset>Inverted page-table entry<process-id, page-number>where process-id acts like an ASIDIf a match is found at entry i physical address <i, offset> is generated.If no match is found an illegal address access
57 Inverted Page Table (cont.) Decreases memory needed to store each page table with only one table, but increases time needed to search the table when a page reference occursBecause the inverted page table is sorted by physical addressbut lookups occur on virtual addresses might need to search the whole table for a matchUse hash table to limit the search to one — or at most a few — page-table entriesTLB (Translation Look-aside Buffers) can accelerate accessBut how to implement shared memory?Shared memory is usually implemented as multiple virtual addresses (one for each process sharing the memory) that are mapped to one physical address.Because there is only one virtual page entry for every physical page.
58 Operation of an Inverted Page Table If a match is found at entry i physical address <i, offset> is generated.
59 SegmentationMemory-management scheme that supports user view of memoryA program is a collection of segmentsA segment is a logical unit such as:main programprocedurefunctionmethodobjectlocal variables, global variablescommon blockstacksymbol tablearrays
61 Logical View of Segmentation 14231234user spacephysical memory space
62 Segmentation Architecture Logical address consists of a two tuple:<segment-number, offset>Segment number – an index to the segment tableOffset – be between 0 and the segment limit, if it exceeds the segment limit, trap to OSSegment table – maps two-dimensional user-defined addresses into one-dimensional physical addresses; each table entry has:Segment base – contains the starting physical address where the segments reside in memorySegment -limit – specifies the length of the segmentThe segment table is an array of base-limit register pairs.Segment-table base register (STBR) points to the segment table’s location in memorySegment-table length register (STLR) indicates number of segments used by a program;segment number s is legal if s < STLR
64 Example of Segmentation Separate entryfor each segment
65 Segmentation Architecture (Cont.) ProtectionWith each entry in segment table associate:validation bit = 0 illegal segmentread/write/execute privilegesProtection bits associated with segments; code sharing occurs at segment levelSince segments vary in length, memory allocation is a dynamic storage-allocation problem
66 Example: The Intel Pentium Supports both segmentation and segmentation with pagingEach segment can be 4 GBUp to 16 K segments per processDivided into two partitionsFirst partition of up to 8 K segments are private to process (kept in local descriptor table LDT)Second partition of up to 8K segments shared among all processes (kept in global descriptor table GDT)CPU generates logical addresses: <selector, offset>Given to segmentation unit which produces a linear address for each logical addressThe linear address is given to the paging unit, which generates the physical address in main memoryThe segmentation and paging units form the equivalent of the memory-management unit.Pages sizes can be 4 KB or 4 MB
67 Logical to Physical Address Translation in the Intel Pentium Logical-to-physical address translation in the PentiumLogical addresses: <selector, offset>s: segment numberg: GDT/LDTp: protection1312SelectorLinear address (two level paging scheme)
69 Pentium Paging Architecture <two level paging scheme for 4-KB page>(Linear Address)outer-mostpage tablePages sizes can be 4 KB or 4 MB.bypassing the inner page table
70 Linear Address in Linux Linux uses only 6 segments:kernel codekernel datauser codeuser datatask-state segment (TSS) : hardware context of each task during Context Switch, eg CR3 registerdefault LDT segmentLinux only uses two of four (2-bit) possible protection modes – kernel and user modesUses a three-level paging strategy that works well for 32-bit and 64-bit systemsLinear address in Linux broken into four parts:Linux rarely uses segmentation because it is designed to run on a variety of processors.
71 Three-level Paging Model in Linux What if using Linux on Pentium?Pentium only supports two-level paging. How Linux apply three-level paging on Pentium? Quiz