Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

5.1 Main Memory

Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

Main Memory

Watch these videos to get a good idea of how CPU and Memory work together
to execute instructions:

The Fetch-Execute Cycle: What's Your Computer Actually Doing?

The Central Processing Unit (CPU): Crash Course Computer Science #7

Instructions & Programs: Crash Course Computer Science #8


Background
Program must be brought (from disk) 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 for execution.
User programs go through several steps before being executed.

Main memory and registers are only storage CPU can access directly
Memory unit only sees
a stream of addresses + read requests,
or address + data and write requests
Register access in one CPU clock (or less)
Main memory can take many cycles, causing a stall
Cache sits between main memory and CPU registers
Protection of memory required to ensure correct operation
Protection of Memory using Base and Limit
Registers
A pair of base and limit registers define the logical address space
CPU must check every memory access generated in user mode to
be sure it is between base and limit for that user
Hardware Address Protection
Multistep Processing of a User Program
Address Binding
Programs on disk, ready to be brought into memory to execute form an
input queue
Without support, must be loaded into address 0000
Inconvenient to have first user process physical address always at 0000
How can it not be?
Further, addresses represented in different ways at different stages of a
program’s life
Source code addresses usually symbolic
Compiled code addresses bind to relocatable addresses
 i.e. “14 bytes from beginning of this module”
Linker or loader will bind relocatable addresses to absolute addresses
 i.e. 74014
Each binding maps one address space to another
Binding of [Instructions and Data] to [Memory]

Address binding of instructions and data to memory addresses can


happen at three different stages.

Compile time: If memory location known a priori, absolute code can be


generated; must recompile code if starting location changes.

Load time: Must generate relocatable code if memory location is not


known at compile 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 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
management
Logical address – generated by the CPU; also referred to
as virtual address
Physical address – address seen by the memory unit
Logical and physical addresses are the same in compile-time
and load-time address-binding schemes; logical (virtual) and
physical addresses differ in execution-time address-binding
scheme
Logical address space is the set of all logical addresses
generated by a program
Physical address space is the set of all physical addresses
generated by a program
Memory-Management Unit (MMU)
Hardware device that at run time maps virtual to physical
address

To 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 memory
Base register now called relocation register
MS-DOS on Intel 80x86 used 4 relocation registers (one for
each of code segment, data segment, stack segment, extra
segment)

The user program deals with logical addresses; it never sees


the real physical addresses
Execution-time binding occurs when reference is made to
location in memory
Logical address bound to physical addresses
Dynamic Loading: Dynamic relocation using a
relocation register
Routine is not loaded until it is
called
Better memory-space utilization;
unused routine is never loaded
All routines kept on disk in
relocatable load format
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
OS can help by providing libraries
to implement dynamic loading
Dynamic Linking
Static linking – system libraries and program code combined by
the loader into the binary program image
Dynamic 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 checks if routine is in processes’ memory
address
If not in address space, add to address space
Dynamic linking is particularly useful for libraries
System also known as shared libraries
Consider applicability to patching system libraries
Versioning may be needed
Swapping
A process can be swapped temporarily out of memory to a backing
store, and then brought back into memory for continued execution
Total physical memory space of processes can exceed physical
memory

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

System maintains a ready queue of ready-to-run processes which have


memory images on disk
Schematic View of Swapping
Memory Allocation/Mapping Techniques

Fixed/Static
Partition
Memory Allocation

Contiguous
Variable Size
Partition

Paging
Non-Contiguous
Segmentation
Contiguous Allocation

Main memory must support both OS and user processes


Limited resource, must allocate efficiently
Contiguous allocation is one early method
Main memory usually into two partitions:
Resident operating system, usually held in low
memory with interrupt vector
User processes then held in high memory
Each process contained in single contiguous section
of memory
Contiguous Allocation (Cont.)
Relocation registers used to protect user processes from
each other, and from changing operating-system code
and data
Base register contains value of smallest physical
address
Limit register contains range of logical addresses –
each logical address must be less than the limit
register
MMU maps logical address dynamically
Contiguous Allocation: Hardware Support for Relocation
and Limit Registers
Contiguous Allocation

Main memory must support both OS and user processes


Limited resource, must allocate efficiently
Contiguous allocation is one early method
Main memory usually into two partitions:
Resident operating system, usually held in low
memory with interrupt vector
User processes then held in high memory
Each process contained in single contiguous section
of memory
Contiguous Allocation (Cont.)
Relocation registers used to protect user processes from
each other, and from changing operating-system code
and data
Base register contains value of smallest physical
address
Limit register contains range of logical addresses –
each logical address must be less than the limit
register
MMU maps logical address dynamically
Contiguous Storage Allocation
A memory resident program occupies a single contiguous block of
memory.
Fixed/Static Partitioning
The main memory is divided into a number of static partitions
at system generation time.
Moreover, a process may be loaded into a partition of equal or
greater size.
Partition size: Two alternatives of fixed partition are as
follows:
1. Equal-size partitions
2. Unequal-size partitions
Contiguous Storage Allocation
Equal-size partitions:
Any process whose size is less than or equal to the partition size
can be loaded into any available partition.
Two problems with this technique are as follows:
1. A program may be too big to fit into a partition.
Use overlaying to solve this problem.
2. Main memory utilization is extremely inefficient, as there
is a possibility of internal fragmentation.
In internal fragmentation, there is a space wastage internal to a
partition due to the fact that the block of data loaded is smaller
than the partition.
Contiguous Storage Allocation
Unequal-sized partition:
Both the problems with equal-size partition can be lessened by
using unequal-sized partitions.
Placement algorithm: With equal-size partitions, the placement
of processes in memory is trivial.
As all partitions are of equal size, it doesn’t matter which
partition is used.
With Unequal-size partitions, there are two possible ways to
assign processes to partitions:
1. Assign each process to the smallest partition within
which it will fit.
2. Employ a single queue for all processes
Contiguous Storage Allocation
1. Assign each process to the smallest partition within which it
will fit.

Figure shows one process queue for partition.


Minimized internal fragmentation.
Possibility of unused partitions.
2. Employ a single queue for all processes
When it is time to load a process into main memory, the smallest
available partition that will hold the process is selected.
Fragmentation
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

Source: Difference between Internal and External fragmentation - GeeksforGeeks


Compaction
Compaction is a technique by which the resident program are
relocated in such a way that the small chunks of free memory
are made contiguous to each other and clubbed together into a
single free partition that may be big enough to accommodate
more programs.

It should be noted that compaction involves dynamic relocation


of a program.
Fixed/Static Allocation

Advantages
1. Simple to implement.
2. Little OS overhead.
Disadvantages
1. Inefficient use of memory due to internal
fragmentation.
2. Maximum number of active processes is fixed.
Contiguous Storage Allocation
Variable Size or Dynamic Partitioning
With dynamic partitioning, the partitions are of
variable length and number.
When a process is brought into main memory, it is
allocated exactly as much memory as it requires and
no more.
Contiguous Storage Allocation
Variable-partition sizes for efficiency (sized to a given process’ needs)
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
Process exiting frees its partition, adjacent free partitions combined
Operating system maintains information about:
a) allocated partitions b) free partitions (hole)
Contiguous Storage Allocation
This method starts out well, but eventually it leads to
a situation in which there are a lot of small holes in
memory.
As time goes on, memory becomes more and more
fragmented and memory utilization declines. This
phenomenon is referred to as external fragmentation.
It indicates the memory that is external to all
partitions becomes increasingly fragmented.
Placement algorithm
How to satisfy a request of size n from a list of free holes?
The most common strategies to allocate free partitions to the
new processes are as follows:
1. First fit: Allocate the first free partition, large enough to
accommodate the process. It executes faster.
2. Best fit: Allocate the smallest free partition that meets
the requirement of the process. It achieves higher
utilization of memory by searching smallest free partition.
3. Worst fit: Allocate the largest available partition to the
newly entered process in the system.
4. Next fit: Start from current location in the list.
Placement algorithm
Example: Consider the following memory configuration after a number of
placement and swapping out operations. The last block that was used was
a 22 MB block from which a 14 MB partition was created. The figure (b)
shows 16 MB allocation request.
Placement algorithm
Advantages of dynamic partitioning
1. Memory utilization is generally better as
partitions are created dynamically.
2. Less internal fragmentation as partitions are
changed dynamically.
3. The process of merging adjacent holes to form a
single larger hole is called coalescing.
Disadvantages
1. Lots of OS space, time, complex memory
management algorithms are required.
2. Compaction time is very high.
Memory Allocation/Mapping Techniques

Fixed/Static
Partition
Memory Allocation

Contiguous
Variable Size
Partition

Paging
Non-Contiguous
Segmentation

Operating System Concepts – 9th Edition 8.37 Silberschatz, Galvin and Gagne ©2013
Non-Contiguous Allocation: Segmentation

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
User’s View of a Program
Logical View of Segmentation

4
1

3 2
4

user space physical memory space


Segmentation
Each process is divided into a number of unequal-size
segments.
A process is loaded by loading all of its segments into
dynamic partitions that need not be contiguous.
The logical address using segmentation consists of two parts:
segment number and an offset.
It makes use of a segment table for each process and a list of
free blocks of main memory.
Each segment table entry would have to give the starting
address in main memory of the corresponding segment.
It also contains the length of the segment.
Segmentation
Steps for address translation:
Extract the segment number from the logical address.
Use the segment number as an index into the process
segment table to find the starting physical address of
the segment.
Compare the offset to the length of the segment. If the
offset is greater than or equal to the length, the address
is invalid.
The desired physical address is the sum of the starting
physical address of the segment plus the offset.
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
Segmentation Hardware
Segmentation
Example: Consider the logical address 0001001011110000. Let the
segment number consists of 4-bits. Then segment number = 0001 = 1
Offset = 001011110000 = 752.

0000

0001

Part of the segment table


Segmentation
Advantages
No internal fragmentation
Improved memory utilization.
Disadvantage
External fragmentation.
Segmentation Architecture (Cont.)
Protection
With each entry in segment table associate:
 validation bit = 0  illegal segment
 read/write/execute privileges
Protection bits associated with segments; code sharing
occurs at segment level
Since segments vary in length, memory allocation is a
dynamic storage-allocation problem
Non-Contiguous Allocation: Paging
Physical address space of a process can be noncontiguous;
process is allocated physical memory whenever the latter is
available
Avoids external fragmentation
Avoids problem of varying sized memory chunks
Divide physical memory into fixed-sized blocks called frames
Size is power of 2, between 512 bytes and 16 Mbytes
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
Backing store likewise split into pages
Still have Internal fragmentation
Non-contiguous Allocation: Paging

Permits the physical address space of a process to be noncontiguous


The main memory is divided into a number of equal-size frames.
Each process is divided into a number of equal-size frames.
The chunks of processes are referred as pages.
A process is loaded by loading all of its pages into available, not necessarily
contiguous frames.
Example: At a point in time, some of the frames in memory are in use and
some are free. A list of free frames is maintained by the OS. Consider four
processes with their pages as displayed below:

Paging avoids external fragmentation and the need for compaction


Non-contiguous Allocation: Paging

Let the main memory consist of 15 frames: Main memory


Non-contiguous Allocation: Paging

The OS maintains a page table for each process.


The page table shows the frame location for each page of the process.
Within a program, each logical address consists of a page number and an
offset with in the page.
Here a logical address is the location of a word relative to the beginning of
the program; the processor translates that into a physical address.
For this, the processor must know the following details:
Logical address: Consists page number and offset.
Page table: Used to produce physical address (Frame number, offset).
Non-contiguous Allocation: Paging

In the previous example, the page tables of each process will be:
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 memory
Page offset (d) – combined with base address to define the
physical memory address that is sent to the memory unit

page number page offset


p d
m -n n

For given logical address space 2m and page size 2n


Paging Hardware
Steps for address translation
Extract the page number from the logical address.
Use the page number as an index into the process page table to find the
frame number.
The physical address will be constructed by appending the frame number to
the offset.
Advantage
There is no external fragmentation.
Disadvantage
There is a small amount of internal fragmentation.
Paging Model of Logical and Physical Memory
Paging Example

n=2 and m=4 32-byte memory and 4-byte pages


Exercise
Q) Consider a machine with 64 MB physical memory and a 32–bit logical
address. If the page size is 4KB, what is the size of the page table.
Answer
Q) Consider a machine with 64 MB physical memory and a 32–bit logical
address. If the page size is 4KB, what is the approx. size of the page table.

Answer:

Physical Address Space = 64MB = 226B


Page Size = 4KB = 212B
Page Size = Frame Size = 212B
So, Number of frames = 226 / 212 = 214 frames.

Virtual Address = 32-bits, Virtual Address Space = 232B


Page Size = 4KB = 212B

So, Number of pages = 232 / 212 = 220 pages.

Page Table Size = Number of Pages * Size of each Page Table Entry

Assuming that, each page table entry contains the Frame Number and nothing else and we found
that the Frame Number is represented using 14-bits (as there are 214 frames).

So, Page Table Size = 220×14-bits ≈ 220×2B = 2MB (if the memory is byte-addressable)
Paging (Cont.)

Calculating internal fragmentation


Page size = 2,048 bytes
Process size = 72,766 bytes
35 pages + 1,086 bytes
Internal fragmentation of 2,048 - 1,086 = 962 bytes
Worst case fragmentation = 1 frame – 1 byte
On average fragmentation = 1 / 2 frame size
So small frame sizes desirable?
But each page table entry takes memory to track
Page sizes growing over time
 Solaris supports two page sizes – 8 KB and 4 MB

By implementation process can only access its own memory


Free Frames

Before allocation After allocation


Implementation of Page Table
Page table is kept in main memory
Page-table base register (PTBR) points to the page table
Page-table length register (PTLR) indicates size of the page
table
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)
Implementation of Page Table (Cont.)
Some TLBs store address-space identifiers (ASIDs) in each
TLB entry – uniquely identifies each process to provide
address-space protection for that process
Otherwise need to flush at every context switch
TLBs typically small (64 to 1,024 entries)
On a TLB miss, value is loaded into the TLB for faster access
next time
Replacement policies must be considered
Some entries can be wired down for permanent fast
access
Associative Memory

Associative memory – parallel search


Page # Frame #

Address translation (p, d)


If p is in associative register, get frame # out
Otherwise get frame # from page table in memory
Paging Hardware With TLB
Effective Access Time
The percentage of times that the page number of interest is found in the
TLB is called the hit ratio.
An 80-percent hit ratio, for example, means that we find the desired page
number in the TLB 80 percent of the time.
If it takes 100 nanoseconds to access memory, then a mapped-memory
access takes 100 nanoseconds when the page number is in the TLB.
If we fail to find the page number in the TLB then we must first access
memory for the page table and frame number (100 nanoseconds) and then
access the desired byte in memory (100 nanoseconds), for a total of 200
nanoseconds. (We are assuming that a page-table lookup takes only one
memory access, but it can take more)
Effective Access Time (EAT)

In this example, we suffer a 20-percent slowdown in average memory-access


time (from 100 to 120 nanoseconds).
Exercise
Q) Consider a paging hardware with a TLB. Assume that the entire page table
and all the pages are in the physical memory. It takes 10 milliseconds to search
the TLB and 80 milliseconds to access the physical memory. If the TLB hit ratio
is 0.6, the effective memory access time is _______
Answer
Q) Consider a paging hardware with a TLB. Assume that the entire page table
and all the pages are in the physical memory. It takes 10 milliseconds to search
the TLB and 80 milliseconds to access the physical memory. If the TLB hit ratio
is 0.6, the effective memory access time is _______

Answer:

Effective Access Time (EAT) = Hit ratio * (c+m) + (1 - Hit ratio)*(c+m+m)

c= time taken to search TLB


m= time to access physical memory

EAT = 0.6 ( 10 + 80 ) + 0.4 ( 10 + 80 + 80 ) = 90 X 0.6 + 0.4 X 170 = 122


Memory Protection
Memory protection implemented by associating protection bit
with each frame to indicate if read-only or read-write access is
allowed
Can also add more bits to indicate page execute-only, and
so on
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
Or use page-table length register (PTLR)
Any violations result in a trap to the kernel
Valid (v) or Invalid (i) Bit In A Page Table
Shared Pages
Shared code
One copy of read-only (reentrant) code shared among
processes (i.e., text editors, compilers, window systems)
Similar to multiple threads sharing the same process space
Also useful for interprocess communication if sharing of
read-write pages is allowed
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
Shared Pages Example

You might also like