64
Chapter 8: Memory Management Chapter 8: Memory Management Hung Q. Ngo KyungHee University Spring 2009 http://uclab.khu.ac.kr/lectures/2009-1-os.html

Chapter 8: Memory Management Hung Q. Ngo KyungHee University Spring 2009

Embed Size (px)

Citation preview

Chapter 8: Memory ManagementChapter 8: Memory Management

Hung Q. Ngo

KyungHee University

Spring 2009

http://uclab.khu.ac.kr/lectures/2009-1-os.html

8.2 Hung Q. Ngo, Spring’09Operating System

Chapter 8: Memory ManagementChapter 8: Memory Management

Background

Swapping

Contiguous Allocation

Paging

Segmentation

Segmentation with Paging

Note: Some slides and/or pictures in the following areadapted from slides ©2005 Silberschatz, Galvin, and Gagne. Many slides generated from my lecture notes by Kubiatowicz.

8.3 Hung Q. Ngo, Spring’09Operating System

Virtualizing ResourcesVirtualizing Resources

Physical Reality: Different Processes/Threads share the same hardware Need to multiplex CPU (Just finished: scheduling) Need to multiplex use of Memory (Today) Need to multiplex disk and devices (later in term)

Why worry about memory sharing? The complete working state of a process and/or kernel is defined by its

data in memory (and registers) Consequently, cannot just let different threads of control use the same

memory Physics: two different pieces of data cannot occupy the same

locations in memory Probably don’t want different threads to even have access to each other’s

memory (protection)

8.4 Hung Q. Ngo, Spring’09Operating System

Recall: Single and Multithreaded ProcessesRecall: Single and Multithreaded Processes

Threads encapsulate concurrency

“Active” component of a process

Address spaces encapsulate protection

Keeps buggy program from trashing the system

“Passive” component of a process

8.5 Hung Q. Ngo, Spring’09Operating System

Important Aspects of Memory MultiplexingImportant Aspects of Memory Multiplexing Controlled overlap:

Separate state of threads should not collide in physical memory. Obviously, unexpected overlap causes chaos!

Conversely, would like the ability to overlap when desired (for communication)

Translation: Ability to translate accesses from one address space (virtual) to a

different one (physical) When translation exists, processor uses virtual addresses, physical

memory uses physical addresses Side effects:

Can be used to avoid overlap Can be used to give uniform view of memory to programs

Protection: Prevent access to private memory of other processes

Different pages of memory can be given special behavior (Read Only, Invisible to user programs, etc).

Kernel data protected from User programs Programs protected from themselves

8.6 Hung Q. Ngo, Spring’09Operating System

BackgroundBackground

Program must be brought into memory and placed within a process for it to be run

Input queue – collection of processes on the disk that are waiting to be brought into memory to run the program

User programs go through several steps before being run

To run, CPU fetches instructions from memory at address contained in PC; the instructions may cause additional load/store.

8.7 Hung Q. Ngo, Spring’09Operating System

Binding of Instructions and Data to MemoryBinding of Instructions and Data to Memory

Compile time: If memory location known a priori, absolute code can be generated; must recompile code if starting location changes

MS-DOS .com format

Load time: Coimpiler must generate relocatable code if memory location is not known at compile time

Absolute address!!!

Execution time

Virtual address

Address binding of instructions and data to memory addresses canhappen at three different stages

8.8 Hung Q. Ngo, Spring’09Operating System

Recall: UniprogrammingRecall: Uniprogramming Uniprogramming (no Translation or Protection)

Application always runs at same place in physical memory since only one application at a time

Application can access any physical address

Application given illusion of dedicated machine by giving it reality of a dedicated machine

Of course, this doesn’t help us with multithreading

0x00000000

0xFFFFFFFF

Application

OperatingSystem

Val

id 3

2-bi

tA

ddre

sses

8.9 Hung Q. Ngo, Spring’09Operating System

Multiprogramming (First Version)Multiprogramming (First Version) Multiprogramming without Translation or Protection

Must somehow prevent address overlap between threads

Trick: Use Loader/Linker: Adjust addresses while program loaded into memory (loads, stores, jumps) Everything adjusted to memory location of program Translation done by a linker-loader Was pretty common in early days

With this solution, no protection: bugs in any program can cause other programs to crash or even the OS

0x00000000

0xFFFFFFFF

Application1

OperatingSystem

Application2 0x00020000

8.10 Hung Q. Ngo, Spring’09Operating System

Multiprogramming (Version with Protection)Multiprogramming (Version with Protection) Can we protect programs from each other without translation?

Yes: use two special registers BaseAddr and LimitAddr to prevent user from straying outside designated area If user tries to access an illegal address, cause an error

During switch, kernel loads new base/limit from TCB User not allowed to change base/limit registers

0x00000000

0xFFFFFFFF

Application1

OperatingSystem

Application2 0x00020000 BaseAddr=0x20000

LimitAddr=0x10000

8.11 Hung Q. Ngo, Spring’09Operating System

A base and a limit register define a logical address spaceA base and a limit register define a logical address space

8.12 Hung Q. Ngo, Spring’09Operating System

HW address protection with base and limit registersHW address protection with base and limit registers

Note: absolute addresses from CPU

8.13 Hung Q. Ngo, Spring’09Operating System

Binding of Instructions and Data to MemoryBinding of Instructions and Data to Memory

Compile time

Load time

Execution time: Binding delayed until run time if the process can be moved during its execution from one memory segment to another. Need hardware support for address maps (e.g., base and limit registers).

Logical (virtual) address (from 0max)

Address binding of instructions and data to memory addresses canhappen at three different stages

8.14 Hung Q. Ngo, Spring’09Operating System

Two Views of MemoryTwo Views of Memory

Recall: Address Space: All the addresses and state a process can touch Each process and kernel has different address space

Consequently: two views of memory: View from the CPU (what program sees, virtual memory) View fom memory (physical memory) Translation box converts between the two views

Translation helps to implement protection If task A cannot even gain access to task B’s data, no way for A to adversely

affect B With translation, every program can be linked/loaded into same region of user

address space Overlap avoided through translation, not relocation

PhysicalAddressesCPU MMU

VirtualAddresses

Untranslated read or write

8.15 Hung Q. Ngo, Spring’09Operating System

Example of General Address TranslationExample of General Address Translation

Prog 1VirtualAddressSpace 1

Prog 2VirtualAddressSpace 2

Code

Data

Heap

Stack

Code

Data

Heap

Stack

Data 2

Stack 1

Heap 1

OS heap & Stacks

Code 1

Stack 2

Data 1

Heap 2

Code 2

OS code

OS dataTranslation Map 1 Translation Map 2

Physical Address Space

8.16 Hung Q. Ngo, Spring’09Operating System

Dynamic relocation using a relocation registerDynamic relocation using a relocation register

Logical address translated physical address (0 max) (relocation with base R) (R R + max)

OS

process 5

process 8

process 2

Contiguous allocation!

8.17 Hung Q. Ngo, Spring’09Operating System

Dynamic LoadingDynamic Loading

Routine is not loaded until it is called

Better memory-space utilization; unused routine is never loaded (e.g. error routines)

Useful when large amounts of code are needed to handle infrequently occurring cases

No special support from the operating system is required, implemented through program design

8.18 Hung Q. Ngo, Spring’09Operating System

Dynamic LinkingDynamic Linking

Linking postponed until execution time

Small piece of code, stub, used to locate the appropriate memory-resident library routine

Stub replaces itself with the address of the routine, and executes the routine

Operating system needed to check if routine is in processes’ memory address

All processes that use a language lib execute only one copy of the lib code

Dynamic linking is particularly useful for libraries, e.g. lib updates (bug fixes)

8.19 Hung Q. Ngo, Spring’09Operating System

SwappingSwapping

A process can be swapped temporarily out of memory to a backing store, and then brought back into memory for continued execution

Backing store – fast disk large enough to accommodate copies of all memory images for all users; must provide direct access to these memory images

Roll 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 executed

Major part of swap time is transfer time; total transfer time is directly proportional to the amount of memory swapped

Modified versions of swapping are found on many systems (i.e., UNIX, Linux, and Windows) MS Windows 3.1: user decides which/when to swap out/in

8.20 Hung Q. Ngo, Spring’09Operating System

Schematic View of SwappingSchematic View of Swapping

Quiz: in execution-time binding, can it be different memory space after swap out & in? Why or why not?

Who does the swapping actions?

Why do programmers need to issue system calls request/release mem when dealing with dynamic mem requirements?

8.21 Hung Q. Ngo, Spring’09Operating System

Issues with SwappingIssues with Swapping

Never swap a process with pending I/O, or execute I/O operations only into OS buffers.

Swapping creates fragmentation in Mem & Disk from such contiguous allocation scheme

8.22 Hung Q. Ngo, Spring’09Operating System

Contiguous AllocationContiguous Allocation

Main memory usually into two partitions:

Resident operating system, usually held in low memory with interrupt vector

User processes then held in high memory

Single-partition allocation

Relocation-register scheme used to protect user processes from each other, and from changing operating-system code and data (e.g. code & buffers for device drivers)

Relocation register contains value of smallest physical address; limit register contains range of logical addresses – each logical address must be less than the limit register

OS

process 5

process 8

process 2

8.23 Hung Q. Ngo, Spring’09Operating System

Contiguous Allocation & ProtectionContiguous Allocation & Protection

Dispatcher loads the relocation & limit registers from PCB/TCB at context switching

This scheme allows OS size to change dynamically, called transient OS code.

8.24 Hung Q. Ngo, Spring’09Operating System

Contiguous Allocation (Cont.)Contiguous Allocation (Cont.)

Multiple-partition allocation

Hole – block of available memory; holes of various size are scattered throughout memory

When a process arrives, it is allocated memory from a hole large enough to accommodate it

Operating system maintains information about:a) allocated partitions b) free partitions (hole)

OS

process 5

process 8

process 2

OS

process 5

process 2

OS

process 5

process 2

OS

process 5

process 9

process 2

process 9

process 10

8.25 Hung Q. Ngo, Spring’09Operating System

Dynamic Storage-Allocation ProblemDynamic Storage-Allocation Problem

First-fit: Allocate the first hole that is big enough

Best-fit: Allocate the smallest hole that is big enough; must search entire list, unless ordered by size. Produces the smallest leftover hole.

Worst-fit: Allocate the largest hole; must also search entire list. Produces the largest leftover hole.

How to satisfy a request of size n from a list of free holes?

Criteria: speed (searching time) and storage utilization

8.26 Hung Q. Ngo, Spring’09Operating System

FragmentationFragmentation

External Fragmentation – total memory space exists to satisfy a request, but it is not contiguous

Internal Fragmentation – allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being used

Reduce external fragmentation by compaction

Shuffle memory contents to place all free memory together in one large block

Compaction is possible only if relocation is dynamic, and is done at execution time

I/O problem

Do I/O only into OS buffers

Compaction is impossible in DISK

Better solution: non-contiguous allocation schemes!

8.27 Hung Q. Ngo, Spring’09Operating System

PagingPaging

Logical address space of a process can be noncontiguous; process is allocated physical memory whenever available

Divide physical memory into fixed-sized blocks called frames (size is power of 2, between 512 bytes and 8192 bytes = 8MB)

Divide logical memory into blocks of same size called pages.

Keep track of all free frames

To run a program of size n pages, need to find n free frames and load program

Set up a page table to translate logical to physical addresses

Internal fragmentation

8.28 Hung Q. Ngo, Spring’09Operating System

Address Translation SchemeAddress 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 memory

Page offset (d) – combined with base address to define the physical memory address that is sent to the memory unit page size

Frame number f is an entry of the page table, usually 4bytes containing the base address

8.29 Hung Q. Ngo, Spring’09Operating System

Address Translation SchemeAddress Translation Scheme

p d

m bits logical address

n bitsPage size = 2n bytes/words

Typically 4KB, 8KB, Solaris: up to 4MB

m – n bitsMax table size = 2m-n entries

Quiz: each entry 4bytes long, frame size 4KB, so physical memory = ?

16bits, 8KB, max table size = ?

8.30 Hung Q. Ngo, Spring’09Operating System

Page size: 4bytes, Mem size: 32bytes (8pages)

Logical addr = 0Logical addr = 3Logical addr = 4Logical addr = 13

Base addr = f * page size

Physical addr = 20Physical addr = 23Physical addr = 24Physical addr = 9

p d

m bits logical address

n bitsPage size = 2n bytes/words

m – n bitsMax table size = 2m-n entries

8.31 Hung Q. Ngo, Spring’09Operating System

Free FramesFree Frames

Before allocation After allocation

Frame table

Maintained by OS, pointer is stored in PCB

8.32 Hung Q. Ngo, Spring’09Operating System

Implementation of Page TableImplementation of Page Table

Page table is kept in main memory If small (~256), can be kept in dedicated registers

Page-table base register (PTBR) points to the page table

Page-table length register (PRLR) indicates size of the page table

Reducing context-switching time

But in this scheme every data/instruction access requires two memory accesses. One for the page table and one for the data/instruction.

The 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)

8.33 Hung Q. Ngo, Spring’09Operating System

Associative MemoryAssociative Memory

Associative memory – high-speed cache, parallel search (64 to 1024 items)

Address translation (P, F)

If P is in associative register, get frame # out

If not TLB miss get frame # from page table in memory

Page # Frame #

8.34 Hung Q. Ngo, Spring’09Operating System

Paging Hardware With TLBPaging Hardware With TLB

ASIDs

8.35 Hung Q. Ngo, Spring’09Operating System

Effective Access TimeEffective Access Time

Associative Lookup = time unit

Assume memory cycle time is t microsecond

Hit ratio – percentage of times that a page number is found in the associative registers; ration related to number of associative registers

Hit ratio = Effective Access Time (EAT)

EAT = (t + ) + (2t + )(1 – )

= (2 - )t +

e.g.: 20ns, 100ns, 80%, 98%

8.36 Hung Q. Ngo, Spring’09Operating System

Memory ProtectionMemory Protection

Memory protection implemented by associating protection bit with each frame

Valid-invalid bit attached to each entry in the page table:

“valid” indicates that the associated page is in the process’ logical address space, and is thus a legal page

“invalid” indicates that the page is not in the process’ logical address space

R-only, R/W, E-only, etc.

8.37 Hung Q. Ngo, Spring’09Operating System

Valid (v) or Invalid (i) Bit In A Page TableValid (v) or Invalid (i) Bit In A Page Table

8.38 Hung Q. Ngo, Spring’09Operating System

QuizQuiz

Suppose we have a 32-bit processor (with 32-bit virtual addresses) and 8 KB pages. Assume that it can address up to 2 TB (terabytes) of DRAM.

Assume that we need 4 permissions bits in each page table entry (PTE), namely Valid (V), Writable (W), Accessed (A), and Dirty (D).

Show the format of a PTE, assuming that each page should be able to hold an integer number of PTEs.

8.39 Hung Q. Ngo, Spring’09Operating System

SolutionSolution

Since the PTE must have sufficient bits to address all of the physical pages, we must ask how many physical pages there are.

2TB = 2×(1024)4=2×240=241.

Total number of pages =2TB/8KB = 241/213= 228

Consequently, we need 28 bits in the PTE for the physical page number. With the 4 other bits, this leads us to a 32 bit PTE (which fits an integral number of times in an 8KB page (with no wasted bits).

Our PTE looks like (bits in any order):

8.40 Hung Q. Ngo, Spring’09Operating System

Shared PagesShared Pages

Shared code

One copy of read-only (reentrant) code shared among processes (i.e., text editors, compilers, window systems).

Shared code must appear in same location in the logical address space of all processes

Private code and data

Each process keeps a separate copy of the code and data

The pages for the private code and data can appear anywhere in the logical address space

8.41 Hung Q. Ngo, Spring’09Operating System

Shared Pages ExampleShared Pages Example

8.42 Hung Q. Ngo, Spring’09Operating System

Page Table StructurePage Table Structure

Hierarchical Paging

Hashed Page Tables

Inverted Page Tables

8.43 Hung Q. Ngo, Spring’09Operating System

Hierarchical Page TablesHierarchical Page Tables

Break up the logical address space into multiple page tables

A simple technique is a two-level page table

8.44 Hung Q. Ngo, Spring’09Operating System

Two-Level Paging ExampleTwo-Level Paging Example

A logical address (on 32-bit machine with 4K page size) is divided into: a page number consisting of 20 bits a page offset consisting of 12 bits

Since the page table is paged, the page number is further divided into: a 10-bit page number a 10-bit page offset

Thus, a logical address is as follows:

where pi is an index into the outer page table, and p2 is the displacement within the page of the outer page table

page number page offset

pi p2 d

10 10 12

8.45 Hung Q. Ngo, Spring’09Operating System

Two-Level Page-Table SchemeTwo-Level Page-Table Scheme

pi p2 d

8.46 Hung Q. Ngo, Spring’09Operating System

E.g.: Pentium PagingE.g.: Pentium Paging

10-10-12 or 20-12

+ 4KB or 4MB+ Set by Page Size flag

page number page offset

pi p2 d

10 10 12

8.47 Hung Q. Ngo, Spring’09Operating System

QuizQuiz

Suppose that we have a two-level page translation scheme with 4K-byte pages and 4-byte page table entries (includes a valid bit, a couple permission bits, and a pointer to another page/table entry). What is the format of a 32-bit virtual address? Sketch out the format of a complete page table

8.48 Hung Q. Ngo, Spring’09Operating System

SolutionSolution

8.49 Hung Q. Ngo, Spring’09Operating System

QuizQuiz

8.50 Hung Q. Ngo, Spring’09Operating System

Hashed Page TablesHashed Page Tables

Common in address spaces > 32 bits

The virtual page number is hashed into a page table. This page table contains a chain of elements hashing to the same location.

Virtual page numbers are compared in this chain searching for a match. If a match is found, the corresponding physical frame is extracted.

A hash function that maps names to integers from 0 to 15. Note the collision between keys "John Smith" and "Sandra Dee".

Many names can be mapped to 1 integer!

8.51 Hung Q. Ngo, Spring’09Operating System

Hashed Page TableHashed Page Table

8.52 Hung Q. Ngo, Spring’09Operating System

Inverted Page TableInverted Page Table

One entry for each real page of memory

Entry consists of the virtual address of the page stored in that real memory location, with information about the process that owns that page

Decreases memory needed to store each page table, but increases time needed to search the table when a page reference occurs

Use hash table to limit the search to one — or at most a few — page-table entries

Difficult to implement shared mem.

8.53 Hung Q. Ngo, Spring’09Operating System

QuizQuiz

Suppose you have a system with 32-bit pointers and 4 megabytes of physical memory that is partitioned into 8192-byte pages. The system uses an Inverted Page Table (IPT). Assume that there is no page sharing between processes.

Describe what page table entries should look like. Specifically, how many bits should be in each page table entry, and what are they for? Also, how many page table entries should there be in the page table?

8.54 Hung Q. Ngo, Spring’09Operating System

SolutionSolution

Each page = 8192 bytes (213 bits)

Memory is 4 megabytes partitioned into 512 pages

Therefore the inverted page table will consist of 512 entries. Each of these entries must have:

19 bits for the virtual page number of the physical page.

Some number of bits (16 in Unix) for the processs ID of the process that owns the page.

Protection bits (r/w/x)

8.55 Hung Q. Ngo, Spring’09Operating System

SegmentationSegmentation

Memory-management scheme that supports user view of memory A program is a collection of segments. A segment is a logical unit

such as:

main program,

procedure,

function,

method,

object,

local variables, global variables,

common block,

stack,

symbol table, arrays

8.56 Hung Q. Ngo, Spring’09Operating System

User’s View of a ProgramUser’s View of a Program

<segment-number, offset>

1) C Compiler constructs segments:

The codeGlobal varsThe heapThe stacksThe standard C lib.

2) Loader assigns segment numbers.

8.57 Hung Q. Ngo, Spring’09Operating System

Logical View of SegmentationLogical View of Segmentation

1

3

2

4

1

4

2

3

user space physical memory space

8.58 Hung Q. Ngo, Spring’09Operating System

Segmentation Architecture Segmentation Architecture

Logical address consists of a two tuple:

<segment-number, offset>,

Segment table – maps two-dimensional physical addresses; each table entry has:

base – contains the starting physical address where the segments reside in memory

limit – specifies the length of the segment

Segment-table base register (STBR) points to the segment table’s location in memory

Segment-table length register (STLR) indicates number of segments used by a program;

segment number s is legal if s < STLR

offset is legal if d < limit

8.59 Hung Q. Ngo, Spring’09Operating System

Address Translation Architecture Address Translation Architecture

8.60 Hung Q. Ngo, Spring’09Operating System

Example of SegmentationExample of Segmentation

8.61 Hung Q. Ngo, Spring’09Operating System

Sharing of SegmentsSharing of Segments

End of Chapter 8End of Chapter 8

8.63 Hung Q. Ngo, Spring’09Operating System

Homework (1/2)Homework (1/2)

8.1, 8.3, 8.4, 8.8, 8.9

Given five memory partitions of 100 KB, 500 KB, 200 KB, 300 KB, and 600 KB (in order), how would each of the first-fit, best-fit, and worst-fit algorithms place processes of 212 KB, 417 KB, 112 KB, and 426 KB (in order)?Which algorithm makes the most efficient use of memory?

Given a paging system with the page table stored in memory.

1. If a memory reference takes 200 nanoseconds, how long does a paged memory reference take?

2. If we use TLB, and TLB hit ratio is 75%, what is the effective memory reference time? Assume that finding a page-table entry in the TLB takes 10nanoseconds, if the entry is there.)

8.64 Hung Q. Ngo, Spring’09Operating System

Homework (2/2)Homework (2/2)

Consider the following segment table:

Segment Base Length

0 219 600

1 2300 14

2 90 100

3 1327 580

4 1952 96

What are the physical addresses for the following logical addresses?

a. 0,430

b. 1,10

c. 2,500

d. 3,400

e. 4,112