Operating System: Presented By:-Dr. Sanjeev Sharma
Operating System: Presented By:-Dr. Sanjeev Sharma
Chapter 1
• Memory Management
• Processor Management
• Device Management
• File Management
• Security
• Control over system performance
• Job accounting
• Error detecting aids
• Coordination between other software and users
• Memory management refers to management of Primary
Memory or Main Memory.
• Main memory is a large array of words or bytes where each
word or byte has its own address.
• Main memory provides a fast storage that can be accessed
directly by the CPU.
• For a program to be executed, it must in the main memory.
• An Operating System does the following activities for memory
management:
– Keeps tracks of primary memory, i.e., what part of it are in use
by whom, what parts are not in use?
– In multiprogramming, the OS decides which process will get
memory when and how much.
– Allocates the memory when a process requests it to do so.
– De-allocates the memory when a process no longer needs it or
has been terminated.
Processor Management
• Several jobs are kept in main memory at the same time, and
the CPU is multiplexed among them.
• If memory can hold several programs, then CPU can switch to
another one whenever a program is waiting for an I/O to
complete – This is multiprogramming.
Time-sharing Operating Systems
• Terminated or Exit
• Once the process finishes its execution, or it is terminated by
the operating system, it is moved to the terminated state where
it waits to be removed from main memory.
Diagram of Process State
Process Control Block (PCB)
A Process Control Block is a data structure maintained by the
Operating System for every process. The PCB is identified by an
integer process ID (PID). A PCB keeps all the information needed to
keep track of a process
Information associated with each process
• Process state:-The current state of the process i.e., whether it is
ready, running, waiting, or whatever.
• Program counter:- Program Counter is a pointer to the address of
the next instruction to be executed for this process.
• CPU registers:- Various CPU registers where process need to be
stored for execution for running state.
• CPU scheduling information:- Process priority and other
scheduling information which is required to schedule the process.
• Memory-management information:-This includes the
information of page table, memory limits, Segment table
depending on memory used by the operating system.
while (true) {
while (true) {
while (counter == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in nextConsumed
}
Race Condition
• A race condition is a special condition that may occur inside a
critical section. A critical section is a section of code that is executed
by multiple threads and where the sequence of execution for the
threads makes a difference in the result of the concurrent execution
of the critical section.
• When the result of multiple threads executing a critical section may
differ depending on the sequence in which the threads execute, the
critical section is said to contain a race condition. The term race
condition stems from the metaphor that the threads are racing
through the critical section, and that the result of that race impacts
the result of executing the critical section.
• This may all sound a bit complicated, so I will elaborate more on
race conditions and critical sections in the following sections.
• To prevent race conditions from occurring you must make sure
that the critical section is executed as an atomic instruction.
That means that once a single thread is executing it, no other
threads can execute it until the first thread has left the critical
section.
• Then turn is set to j to allow the other process to enter their critical
section if process j so desires.
• The while loop is a busy loop ( notice the semicolon at the end ),
which makes process i wait as long as process j has the turn and
wants to enter the critical section.
• Two operations:
– block – place the process invoking the operation on the
appropriate waiting queue.
– wakeup – remove one of processes in the waiting queue and
place it in the ready queue.
Semaphore Implementation with no Busy waiting (Cont.)
• Implementation of wait:
wait (S){
value--;
if (value < 0) {
add this process to waiting queue
block(); }
}
• Implementation of signal:
Signal (S){
value++;
if (value <= 0) {
remove a process P from the waiting queue
wakeup(P); }
}
Deadlock and Starvation
• Deadlock – two or more processes are waiting indefinitely for
an event that can be caused by only one of the waiting
processes
• Let S and Q be two semaphores initialized to 1
P0 P1
wait (S); wait (Q);
wait (Q); wait (S);
. .
. .
. .
signal (S); signal (Q);
signal (Q); signal (S);
• Starvation – indefinite blocking. A process may never be
removed from the semaphore queue in which it is suspended.
Classical Problems of Synchronization
• Bounded-Buffer Problem
• Readers and Writers Problem
• Dining-Philosophers Problem
Bounded-Buffer Problem
• This is a generalization of the producer-consumer problem
wherein access is controlled to a shared group of buffers of a
limited size. In this solution, the two counting semaphores
"full" and "empty" keep track of the current number of full and
empty buffers respectively ( and initialized to 0 and N
respectively. )
• The binary semaphore mutex controls access to the critical
section.
• The producer and consumer processes are nearly identical -
One can think of the producer as producing full buffers, and
the consumer producing empty buffers Semaphore mutex
initialized to the value 1
• Semaphore full initialized to the value 0
• Semaphore empty initialized to the value N.
Bounded Buffer Problem (Cont.)
Bounded Buffer Problem (Cont.)
Readers-Writers Problem
• In the readers-writers problem there are some processes ( termed readers ) who only
read the shared data, and never change it, and there are other processes ( termed
writers ) who may change the data in addition to or instead of reading it. There is no
limit to how many readers can access the data simultaneously, but when a writer
accesses the data, it needs exclusive access.
• There are several variations to the readers-writers problem, most centered around
relative priorities of readers versus writers. The first readers-writers problem gives
priority to readers. In this problem, if a reader wants access to the data, and there is
not already a writer accessing it, then access is granted to the reader. A solution to
this problem can lead to starvation of the writers, as there could always be more
readers coming along to access the data. ( A steady stream of readers will jump
ahead of waiting writers as long as there is currently already another reader
accessing the data, because the writer is forced to wait until the data is idle, which
may never happen if there are enough readers. )
• The second readers-writers problem gives priority to the writers. In this problem,
when a writer wants access to the data it jumps to the head of the queue - All
waiting readers are blocked, and the writer gets access to the data as soon as it
becomes available. In this solution the readers may be starved by a steady stream of
writers.
Readers-Writers Problem (Cont.)
• The following code is an example of the first readers-writers
problem, and involves an important counter and two binary
semaphores: readcount is used by the reader processes, to count the
number of readers currently accessing the data.
• mutex is a semaphore used only by the readers for controlled access
to readcount.
• rw_mutex is a semaphore used to block and release the writers. The
first reader to access the data will set this lock and the last reader to
exit will release it; The remaining readers do not touch rw_mutex. (
Eighth edition called this variable wrt. )
• Note that the first reader to come along will block on rw_mutex if
there is currently a writer accessing the data, and that all following
readers will only block on mutex for their turn to increment
readcount.
Readers-Writers Problem (Cont.)
Dining-Philosophers Problem
• The dining philosophers problem is a classic synchronization
problem involving the allocation of limited resources amongst a
group of processes in a deadlock-free and starvation-free manner:
Consider five philosophers sitting around a table, in which there are
five chopsticks evenly distributed and an endless bowl of rice in the
center, as shown in the diagram below. ( There is exactly one
chopstick between each pair of dining philosophers. )
• These philosophers spend their lives alternating between two
activities: eating and thinking.
• When it is time for a philosopher to eat, it must first acquire two
chopsticks - one from their left and one from their right.
• When a philosopher thinks, it puts down both chopsticks in their
original locations.
Dining-Philosophers Problem (Cont.)
P1 24
P2 3
P3 3
• In the first Gantt chart below, process P1 arrives first. The
average waiting time for the three processes is ( 0 + 24 + 27 ) /
3 = 17.0 ms.
• In the second Gantt chart below, the same three processes have
an average wait time of ( 0 + 3 + 6 ) / 3 = 3.0 ms. The total run
time for the three bursts is the same, but in the second case two
of the three finish much quicker, and the other process is only
delayed by a short amount.
• FCFS can also block the system in a busy dynamic system in
another way, known as the convoy effect. When one CPU
intensive process blocks the CPU, a number of I/O intensive
processes can get backed up behind it, leaving the I/O devices
idle. When the CPU hog finally relinquishes the CPU, then the
I/O processes pass through the CPU quickly, leaving the CPU
idle while everyone queues up for I/O, and then the cycle
repeats itself when the CPU intensive process gets back to the
ready queue.
Shortest-Job-First Scheduling, SJF
Operating System Concepts – 9th Edition Silberschatz, Galvin and Gagne ©2013
Chapter : Deadlocks
System Model
Deadlock Characterization
Methods for Handling Deadlocks
Deadlock Prevention
Deadlock Avoidance
Deadlock Detection
Recovery from Deadlock
Operating System Concepts – 9th Edition 7.2 Silberschatz, Galvin and Gagne ©2013
Chapter Objectives
Operating System Concepts – 9th Edition 7.3 Silberschatz, Galvin and Gagne ©2013
System Model
Operating System Concepts – 9th Edition 7.4 Silberschatz, Galvin and Gagne ©2013
Deadlock Characterization
Deadlock can arise if four conditions hold simultaneously.
Operating System Concepts – 9th Edition 7.5 Silberschatz, Galvin and Gagne ©2013
Resource-Allocation Graph
A set of vertices V and a set of edges E.
V is partitioned into two types:
P = {P1, P2, …, Pn}, the set consisting of all the processes
in the system
Operating System Concepts – 9th Edition 7.6 Silberschatz, Galvin and Gagne ©2013
Resource-Allocation Graph (Cont.)
Process
Pi requests instance of Rj
Pi
Rj
Pi is holding an instance of Rj
Pi
Rj
Operating System Concepts – 9th Edition 7.7 Silberschatz, Galvin and Gagne ©2013
Example of a Resource Allocation Graph
Operating System Concepts – 9th Edition 7.8 Silberschatz, Galvin and Gagne ©2013
Resource Allocation Graph With A Deadlock
Operating System Concepts – 9th Edition 7.9 Silberschatz, Galvin and Gagne ©2013
Graph With A Cycle But No Deadlock
Operating System Concepts – 9th Edition 7.10 Silberschatz, Galvin and Gagne ©2013
Basic Facts
Operating System Concepts – 9th Edition 7.11 Silberschatz, Galvin and Gagne ©2013
Methods for Handling Deadlocks
Operating System Concepts – 9th Edition 7.12 Silberschatz, Galvin and Gagne ©2013
Deadlock Prevention
Restrain the ways request can be made
Operating System Concepts – 9th Edition 7.13 Silberschatz, Galvin and Gagne ©2013
Deadlock Prevention (Cont.)
No Preemption –
If a process that is holding some resources requests
another resource that cannot be immediately allocated to
it, then all resources currently being held are released
Preempted resources are added to the list of resources
for which the process is waiting
Process will be restarted only when it can regain its old
resources, as well as the new ones that it is requesting
Circular Wait – impose a total ordering of all resource types,
and require that each process requests resources in an
increasing order of enumeration
Operating System Concepts – 9th Edition 7.14 Silberschatz, Galvin and Gagne ©2013
Deadlock Example
/* thread one runs in this function */
void *do_work_one(void *param)
{
pthread_mutex_lock(&first_mutex);
pthread_mutex_lock(&second_mutex);
/** * Do some work */
pthread_mutex_unlock(&second_mutex);
pthread_mutex_unlock(&first_mutex);
pthread_exit(0);
}
/* thread two runs in this function */
void *do_work_two(void *param)
{
pthread_mutex_lock(&second_mutex);
pthread_mutex_lock(&first_mutex);
/** * Do some work */
pthread_mutex_unlock(&first_mutex);
pthread_mutex_unlock(&second_mutex);
pthread_exit(0);
}
Operating System Concepts – 9th Edition 7.15 Silberschatz, Galvin and Gagne ©2013
Deadlock Example with Lock Ordering
void transaction(Account from, Account to, double amount)
{
mutex lock1, lock2;
lock1 = get_lock(from);
lock2 = get_lock(to);
acquire(lock1);
acquire(lock2);
withdraw(from, amount);
deposit(to, amount);
release(lock2);
release(lock1);
}
Operating System Concepts – 9th Edition 7.16 Silberschatz, Galvin and Gagne ©2013
Deadlock Avoidance
Requires that the system has some additional a priori information
available
Simplest and most useful model requires that each process
declare the maximum number of resources of each type
that it may need
The deadlock-avoidance algorithm dynamically examines
the resource-allocation state to ensure that there can never
be a circular-wait condition
Resource-allocation state is defined by the number of
available and allocated resources, and the maximum
demands of the processes
Operating System Concepts – 9th Edition 7.17 Silberschatz, Galvin and Gagne ©2013
Safe State
Operating System Concepts – 9th Edition 7.18 Silberschatz, Galvin and Gagne ©2013
Basic Facts
Operating System Concepts – 9th Edition 7.19 Silberschatz, Galvin and Gagne ©2013
Safe, Unsafe, Deadlock State
Operating System Concepts – 9th Edition 7.20 Silberschatz, Galvin and Gagne ©2013
Avoidance Algorithms
Operating System Concepts – 9th Edition 7.21 Silberschatz, Galvin and Gagne ©2013
Resource-Allocation Graph Scheme
Claim edge Pi → Rj indicated that process Pj may request
resource Rj; represented by a dashed line
Claim edge converts to request edge when a process requests
a resource
Request edge converted to an assignment edge when the
resource is allocated to the process
When a resource is released by a process, assignment edge
reconverts to a claim edge
Resources must be claimed a priori in the system
Operating System Concepts – 9th Edition 7.22 Silberschatz, Galvin and Gagne ©2013
Resource-Allocation Graph
Operating System Concepts – 9th Edition 7.23 Silberschatz, Galvin and Gagne ©2013
Unsafe State In Resource-Allocation Graph
Operating System Concepts – 9th Edition 7.24 Silberschatz, Galvin and Gagne ©2013
Resource-Allocation Graph Algorithm
Operating System Concepts – 9th Edition 7.25 Silberschatz, Galvin and Gagne ©2013
Banker’s Algorithm
Multiple instances
Operating System Concepts – 9th Edition 7.26 Silberschatz, Galvin and Gagne ©2013
Data Structures for the Banker’s Algorithm
Operating System Concepts – 9th Edition 7.27 Silberschatz, Galvin and Gagne ©2013
Safety Algorithm
1. Let Work and Finish be vectors of length m and n, respectively.
Initialize:
Work = Available
Finish [i] = false for i = 0, 1, …, n- 1
4. If Finish [i] == true for all i, then the system is in a safe state
Operating System Concepts – 9th Edition 7.28 Silberschatz, Galvin and Gagne ©2013
Resource-Request Algorithm for Process Pi
Operating System Concepts – 9th Edition 7.29 Silberschatz, Galvin and Gagne ©2013
Example of Banker’s Algorithm
Operating System Concepts – 9th Edition 7.30 Silberschatz, Galvin and Gagne ©2013
Example (Cont.)
The content of the matrix Need is defined to be Max – Allocation
Need
ABC
P0 743
P1 122
P2 600
P3 011
P4 431
The system is in a safe state since the sequence < P1, P3, P4, P2, P0>
satisfies safety criteria
Operating System Concepts – 9th Edition 7.31 Silberschatz, Galvin and Gagne ©2013
Example: P1 Request (1,0,2)
Check that Request ≤ Available (that is, (1,0,2) ≤ (3,3,2) ⇒ true
Allocation Need Available
ABC ABC ABC
P0 010 743 230
P1 302 020
P2 302 600
P3 211 011
P4 002 431
Executing safety algorithm shows that sequence < P1, P3, P4, P0, P2>
satisfies safety requirement
Operating System Concepts – 9th Edition 7.32 Silberschatz, Galvin and Gagne ©2013
Deadlock Detection
Detection algorithm
Recovery scheme
Operating System Concepts – 9th Edition 7.33 Silberschatz, Galvin and Gagne ©2013
Single Instance of Each Resource Type
Operating System Concepts – 9th Edition 7.34 Silberschatz, Galvin and Gagne ©2013
Resource-Allocation Graph and Wait-for Graph
Operating System Concepts – 9th Edition 7.35 Silberschatz, Galvin and Gagne ©2013
Several Instances of a Resource Type
Available: A vector of length m indicates the number of
available resources of each type
Allocation: An n x m matrix defines the number of resources
of each type currently allocated to each process
Request: An n x m matrix indicates the current request of
each process. If Request [i][j] = k, then process Pi is
requesting k more instances of resource type Rj.
Operating System Concepts – 9th Edition 7.36 Silberschatz, Galvin and Gagne ©2013
Detection Algorithm
Operating System Concepts – 9th Edition 7.37 Silberschatz, Galvin and Gagne ©2013
Detection Algorithm (Cont.)
3. Work = Work + Allocationi
Finish[i] = true
go to step 2
Operating System Concepts – 9th Edition 7.38 Silberschatz, Galvin and Gagne ©2013
Example of Detection Algorithm
Five processes P0 through P4; three resource types
A (7 instances), B (2 instances), and C (6 instances)
Sequence <P0, P2, P3, P1, P4> will result in Finish[i] = true for all i
Operating System Concepts – 9th Edition 7.39 Silberschatz, Galvin and Gagne ©2013
Example (Cont.)
State of system?
Can reclaim resources held by process P0, but insufficient
resources to fulfill other processes; requests
Deadlock exists, consisting of processes P1, P2, P3, and P4
Operating System Concepts – 9th Edition 7.40 Silberschatz, Galvin and Gagne ©2013
Detection-Algorithm Usage
When, and how often, to invoke depends on:
How often a deadlock is likely to occur?
How many processes will need to be rolled back?
one for each disjoint cycle
Operating System Concepts – 9th Edition 7.41 Silberschatz, Galvin and Gagne ©2013
Recovery from Deadlock: Process Termination
Operating System Concepts – 9th Edition 7.42 Silberschatz, Galvin and Gagne ©2013
Recovery from Deadlock: Resource Preemption
Operating System Concepts – 9th Edition 7.43 Silberschatz, Galvin and Gagne ©2013
Main Memory
Operating System Concepts – 9th Edition Silberschatz, Galvin and Gagne ©2013
Background
8.2
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
8.3
Hardware Address Protection
8.4
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
8.5
Logical vs. Physical Address Space
8.6
Memory-Management Unit (MMU)
Hardware device that at run time maps virtual to physical
address
Many methods possible, covered in the rest of this chapter
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
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
8.7
Dynamic relocation using a relocation register
8.8
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
8.9
Schematic View of Swapping
8.10
Context Switch Time including Swapping
8.11
Context Switch Time and Swapping (Cont.)
8.12
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
8.13
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
Can then allow actions such as kernel code being transient
and kernel changing size
8.14
Hardware Support for Relocation and Limit Registers
8.15
Multiple-partition allocation
Multiple-partition allocation
Degree of multiprogramming limited by number of partitions
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)
8.16
Dynamic Storage-Allocation Problem
How to satisfy a request of size n from a list of free holes?
Worst-fit: Allocate the largest hole; must also search entire list
Produces the largest leftover hole
First-fit and best-fit better than worst-fit in terms of speed and storage
utilization
8.17
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
First fit analysis reveals that given N blocks allocated, 0.5 N
blocks lost to fragmentation
1/3 may be unusable -> 50-percent rule
8.18
Fragmentation (Cont.)
8.19
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
8.20
User’s View of a Program
8.21
Logical View of Segmentation
4
1
3 2
4
8.22
Segmentation Architecture
Logical address consists of a two tuple:
<segment-number, offset>,
8.23
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
A segmentation example is shown in the following diagram
8.24
Segmentation Hardware
8.25
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
8.26
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
8.27
Paging Hardware
8.28
Paging Model of Logical and Physical Memory
8.29
Paging Example
8.30
Paging (Cont.)
8.31
Free Frames
8.32
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)
8.33
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
8.34
Associative Memory
Page # Frame #
8.35
Paging Hardware With TLB
8.36
8.37
Effective Access Time
Associative Lookup = time unit
Can be < 10% of memory access time
Hit ratio =
Hit ratio – percentage of times that a page number is found in the
associative registers; ratio related to number of associative
registers
Consider = 80%, = 20ns for TLB search, 100ns for memory access
Consider = 80%, = 20ns for TLB search, 100ns for memory access
EAT = 0.80 x 100 + 0.20 x 200 = 120ns
Consider more realistic hit ratio -> = 99%, = 20ns for TLB search,
100ns for memory access
EAT = 0.99 x 100 + 0.01 x 200 = 101ns
8.38
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
8.39
Valid (v) or Invalid (i) Bit In A Page Table
8.40
Virtual Memory
Background (Cont.)
Virtual memory – separation of user logical memory from
physical memory
Only part of the program needs to be in memory for execution
Logical address space can therefore be much larger than physical
address space
Allows address spaces to be shared by several processes
Allows for more efficient process creation
More programs running concurrently
Less I/O needed to load or swap processes
Background (Cont.)
Virtual address space – logical view of how process is
stored in memory
Usually start at address 0, contiguous addresses until end of
space
Meanwhile, physical memory organized in page frames
MMU must map logical to physical
Virtual memory can be implemented via:
Demand paging
Demand segmentation
Virtual Memory That is Larger Than Physical Memory
Demand Paging
Could bring entire process into memory
at load time
Or bring a page into memory only when
it is needed
Less I/O needed, no unnecessary
I/O
Less memory needed
Faster response
More users
Similar to paging system with swapping
(diagram on right)
Page is needed reference to it
invalid reference abort
not-in-memory bring to memory
Lazy swapper – never swaps a page
into memory unless page will be needed
Swapper that deals with pages is a
pager
Basic Concepts
With swapping, pager guesses which pages will be used before
swapping out again
Instead, pager brings in only those pages into memory
How to determine that set of pages?
Need new MMU functionality to implement demand paging
If pages needed are already memory resident
No difference from non demand-paging
If page needed and not memory resident
Need to detect and load the page into memory from storage
Without changing program behavior
Without programmer needing to change code
Valid-Invalid Bit
With each page table entry a valid–invalid bit is associated
(v in-memory – memory resident, i not-in-memory)
Initially valid–invalid bit is set to i on all entries
Example of a page table snapshot:
3. Bring the desired page into the (newly) free frame; update the page
and frame tables
4. Continue the process by restarting the instruction that caused the trap
Note now potentially 2 page transfers for page fault – increasing EAT
Page Replacement
Page and Frame Replacement Algorithms
15 page faults
Can vary by reference string: consider 1,2,3,4,1,2,5,1,2,3,4,5
Adding more frames can cause more page faults!
Belady’s Anomaly
How to track ages of pages?
Just use a FIFO queue
FIFO Illustrating Belady’s Anomaly
Optimal Algorithm
Replace page that will not be used for longest period of time
9 is optimal for the example
How do you know this?
Can’t read the future
Used for measuring how well your algorithm performs
Least Recently Used (LRU) Algorithm
Use past knowledge rather than future
Replace page that has not been used in the most amount of time
Associate time of last use with each page
The disk arm starts at one end of the disk, and moves toward the
other end, servicing requests until it gets to the other end of the
disk, where the head movement is reversed and servicing
continues.
SCAN algorithm Sometimes called the elevator algorithm
Illustration shows total head movement of 236 cylinders
But note that if requests are uniformly dense, largest density at
other end of disk and those wait the longest
SCAN (Cont.)
C-SCAN
Provides a more uniform wait time than SCAN
The head moves from one end of the disk to the other, servicing
requests as it goes
When it reaches the other end, however, it immediately
returns to the beginning of the disk, without servicing any
requests on the return trip
Treats the cylinders as a circular list that wraps around from the
last cylinder to the first one
Total number of cylinders?
C-SCAN (Cont.)
C-LOOK
LOOK a version of SCAN, C-LOOK a version of C-SCAN
Arm only goes as far as the last request in each direction,
then reverses direction immediately, without first going all
the way to the end of the disk
Total number of cylinders?
C-LOOK (Cont.)