Professional Documents
Culture Documents
OS End-Sem Merged
OS End-Sem Merged
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
• Here First the pooled jobs are read and executed by the batch
monitor, and then these jobs are grouped; placing the identical
jobs (jobs with the similar needs) in the same batch, So, in the
batch processing system, the batched jobs were executed
automatically one after another saving its time by performing
the activities (like loading of compiler) only for once. It
resulted in improved system utilization due to reduced turn
around time.
• The operating systems (called resident monitor) manages the
execution of each program in the batch.
– Monitor utilities are loaded when needed.
– Resident monitor is always in main memory and available for
execution.
– The resident monitor usually has the following part.
• Control card interpreter – responsible for reading and
carrying out instructions on the cards.
• Loader – loads systems programs and applications
programs into memory.
• Device drivers – know special characteristics and
properties for each of the system’s I/O devices.
• One big problem associate with these OS is CPU was often
idle.
• To over come this spooling can be used.
• Uniprogramming Until Now
– I/O operations are exceedingly slow (compared to instruction
execution).
– A program containing even a very small number of I/O
operations will spend most of its time waiting for them.
– Hence: poor CPU usage when only one program is present in
memory.
Memory model for uniprogramming
Multiprogrammed Batch Systems
• 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
release
process must request a resource before using it and must release the
resource after using it. A process may request as many resources as it requires
to carry out its designated task. Obviously, the number of resources requested
may not exceed the total number of resources available in the system. In other
words, a process cannot request three printers if the system has only two
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
Deadlocks can be described more precisely in terms of a directed graph called
Resource Allocaton 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
Generally speaking, we can deal with the deadlock problem in one of three ways:
We can use a protocol to prevent or avoid deadlocks, ensuring that the
system will never enter a deadlocked state.
Operating System Concepts – 9th Edition 7.12 Silberschatz, Galvin and Gagne ©2013
Deadlock Prevention
It provides a set of methods for ensuring that at least one of the necessary conditions
(Section 7.2.1) cannot hold.
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 Use when there are Multiple instances of a resource type
When a process requests a resource it may have to wait until some other
process releases
enough resources.
When a process gets all its resources it must return them in a
finite amount of time
priori claim max use - ie when a new process enters the system, it must declare the
maximum number of instances of each resource type that it may need When a user
requests a set of resources, the system must determine whether the allocation of these
resources will leave the system in a safe state.
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
Abort will
clearly
This method all break
deadlocked processes
the deadlock cycle, but at great expense; the deadlocked processes
may have computed for a long time, and the results of these partial computations must be discarded
and probably will have to be recomputed later
Abort one process at a time until the deadlock cycle is eliminated
Operating System Concepts – 9th Edition 7.42 Silberschatz, Galvin and Gagne ©2013
Recovery from Deadlock: Resource Preemption
To eliminate deadlocks using resource preemption, we successively preempt
some resources from processes and give these resources to other processes 1-m til the
deadlock cycle is broken.
Selecting a victim – minimize cost
Cost factors may include such parameters as the number of resources a deadlocked process is
holding and the amount of time the process has thus far consumed during its execution.
Rollback – return to some safe state, restart process for that
state
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
The memory is usually divided into two partitions: one for the resident
operating system and one for the user processes. We can place the operating
system in either low memory or high memory. The major factor affecting this
decision is the location of the interrupt vector. Since the interrupt vector is
often in low memory, programmers usually place the operating system in low
memory as well.
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
One of the simplest methods for allocating memory is to divide memory into several fixed-sized
partions Each partition may contain exactly one process
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?
First-fit: Allocate the first hole that is big enough Searching can start either
at the beginning of the set of holes or at the location where the previous first-fit search ended. We
can stop searching as soon as we find a free hole that is large 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 which may be more useful than the
smaller leftover hole from a best-fit
approach
First-fit and best-fit better than worst-fit in terms of speed and storage
utilization
The system may need to check whether there are processes waiting for memory and whether this
newly freed and recombined memory could satisfy the demands of any of these waiting
processes.
This procedure is a particular instance of the general dtnamic storage allocation which concerns how
to satisfy a request of size n from a lisr of free holes.
8.17
Fragmentation
Both the first-fit and best-fit strategies for memory allocation suffer from external As processes are
loaded and removed from memory, the free memory space is broken into little pieces
External Fragmentation – total memory space exists to
satisfy a request, but it is not contiguous Storage is fragmented into a large
number of small holes
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
That is, one-third of memory may be unusable! This property is known as th
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
. A logical address space is a collection of segments. Each
segment has a name and a length. The user therefore specifies each address
by two quantities: a segment name and an offset
8.20
User’s View of a Program
8.21
Logical View of Segmentation
4
1
3 2
4
8.22
Segmentation Architecture
For simplicity of implementation, segments are numbered and are referred to by a segn"lent
number, rather than by a segment name
Logical address consists of a two tuple:
<segment-number, offset>,
Normally, the user program is compiled, and the compiler automatically constructs segments reflecting
the input program.
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
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
Read Entire Pagin from galvin , pdf pg no 341, book pg no 328
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
The basic method for implementing paging involves breaking
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
Traditionally, support for paging has been handled by hardware. However, recent designs have implemented
paging by closely integrating the hardware and operating system, especially on 64-bit microprocessors.
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 in a paged environment is accomplished by protection bits
associated with each frame. Normally, these bits are kept in the page table
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) This value is
Any violations result in a trap to the kernel checked against every
logical address to verify
that the address is in the
valid range for the process
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
Virtual memory is a tecrucique that allows the execution of processes that are not completely in memory. One major advantage of this scheme is
that programs can be larger than physical memory. Further, virtual memory abstracts main memory into an extremely large, uniform array of storage,
separating logical memory as viewed by the user from physical memory. This technique frees programmers from the concerns of memory-storage
limitations. Virtual memory also allows processes to share files easily and to implement shared memory. In addition, it provides an efficient
mechanism for process creation. Virtual memory is not easy to implement, however, and
may substantially decrease performance if it is used carelessly
Background (Cont.)
Virtual address space – logical view of how process is
stored in memory Typically, this view is that a process
begins at a certain logical address-say, address 0-and exists in contiguous
memory, as
Usually start at address 0, contiguous addresses until end of
space
Meanwhile, physical memory organized in page frames
d that the physical page
MMU must map logical to physical frames assigned to a process may not be contiguous.
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
In fact, look at any process that does not have "enough" frames. If the
process does not have the num.ber of frames it needs to support pages in
active use, it will quickly page-fault. At this point, it must replace some page.
However, since all its pages are in active use, it must replace a page that will
be needed again right away. Consequently, it quickly faults again, and again,
and again, replacing pages that it must back in immediately
Thrashing
If a process does not have “enough” pages, the page-fault rate is
very high
Page fault to get page
Replace existing frame
But quickly need replaced frame back
This leads to:
Low CPU utilization
Operating system thinking that it needs to increase the
degree of multiprogramming
Another process added to the system
Disk scheduling refers to the method or algorithm used by operating systems to determine the order in which
read and write requests to a disk are processed. Since multiple requests can come from different applications,
the goal of disk scheduling is to optimize disk performance, minimize disk head movement, reduce seek time,
and ultimately improve system efficiency and responsiveness.
Overview of Mass Storage Structure
Magnetic disks provide bulk of secondary storage of modern computers
Drives rotate at 60 to 250 times per second
Transfer rate is rate at which data flow between drive and computer
Positioning time (random-access time) is time to move disk arm to
desired cylinder (seek time) and time for desired sector to rotate
under the disk head (rotational latency) dddd acsh
Head crash results from disk head making contact with the disk
surface -- That’s bad
Disks can be removable
Drive attached to computer via I/O bus
Busses vary, including EIDE, ATA, SATA, USB, Fibre Channel,
SCSI, SAS, Firewire
Host controller in computer uses bus to talk to disk controller built
into drive or storage array
Moving-head Disk Mechanism
Seek Time:
This is the time it takes to move the disk arm (also known as the actuator arm) to the desired cylinder or track. The disk arm moves the
read/write head across the platters to reach the correct position for data access.
Rotational Latency:
This is the time it takes for the desired sector to rotate under the read/write head once the disk arm has reached the correct track. It
depends on the rotational speed of the disk, measured in revolutions per minute (RPM).
Disk Scheduling
The operating system is responsible for using hardware
efficiently — for the disk drives, this means having a fast
access time and disk bandwidth
Minimize seek time
Seek time seek distance
Disk bandwidth is the total number of bytes transferred,
divided by the total time between the first request for service
and the completion of the last transfer
Disk Scheduling (Cont.)
There are many sources of disk I/O request
OS
System processes
Users processes
I/O request includes input or output mode, disk address, memory
address, number of sectors to transfer
OS maintains queue of requests, per disk or device
Idle disk can immediately work on I/O request, busy disk means
work must queue
Optimization algorithms only make sense when a queue exists
Disk Scheduling (Cont.)
Note that drive controllers have small buffers and can manage a
queue of I/O requests (of varying “depth”)
Several algorithms exist to schedule the servicing of disk I/O
requests
The analysis is true for one or many platters
We illustrate scheduling algorithms with a request queue (0-199)
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.)