OS Notes
OS Notes
CHAPTER 1:-Introduction To OS
An OS is an intermediary between the user of the computer & the computer
hardware.
It provides a basis for application program & acts as an intermediary between user of
computer & computer hardware.
The purpose of an OS is to provide a environment in which the user can execute the
program in a convenient & efficient manner.
OS is an important part of almost every computer systems.
A computer system can be roughly divided into four components
a. The Hardware
b. The OS
c. The application Program
d. The user
The Hardware consists of memory, CPU, ALU, I/O devices, peripherals devices &
storage devices.
The application program mainly consisted of word processors, spread sheets,
compilers & web browsers defines the ways in which the resources are used to solve
the problems of the users.
The OS controls & co-ordinates the use of hardware among various application
program for various users.
The following figure shows the conceptual view of a computer system
Views OF OS
1. User Views:- The user view of the computer depends on the interface used.
i. Some users may use PC’s. In this the system is designed so that only one
user can utilize the resources and mostly for ease of use where the
attention is mailnly on performances and not on the resource utilization.
ii. Some users may use a terminal connected to a mainframe or
minicomputers.
iii. Other users may access the same computer through other terminals.
These users may share resources and exchange information. In this
case the OS is designed to maximize resource utilization- so that all
available CPU time, memory & I/O are used efficiently.
iv. Other users may sit at workstations, connected to the networks of other
workstation and servers. In this case OS is designed to compromise
between individual visibility & resource utilization.
2. System Views:-
i. We can view system as resource allocator i.e. a computer system has
many resources that may be used to solve a problem. The OS acts as a
manager of these resources. The OS must decide how to allocate these
resources to programs and the users so that it can operate the computer
system efficiently and fairly.
ii. A different view of an OS is that it need to control various I/O devices
& user programs i.e. an OS is a control program used to manage the
execution of user program to prevent errors and improper use of the
computer.
iii. Resources can be either CPU Time, memory space, file storage space,
I/O devices and so on.
The OS must support the following tasks
a. Provide the facility to create, modification of programs & data files using
on editors.
b. Access to compilers for translating the user program from high level
language to machine language.
c. Provide a loader program to move the compiled program code to
computers memory for execution.
d. Provides routines that handle the details of I/O programming.
I. Mainframe System:-
a. Mainframe systems are mainly used for scientific & commercial
applications.
b. An OS may process its workload serially where the computer runs only
one application or concurrently where computer runs many applications.
Batch Systems:-
a. Early computers where physically large machines.
b. The common I/P devices are card readers & tape drives.
c. The common O/P devices are line printers, tape drives & card punches.
d. The user do not interact directly with computers but we use to prepare a
job with the program, data & some control information & submit it to the
Computer program
e. The job was mainly in the form punched cards.
f. At later time the O/P appeared and it consisted of result along with dump
of memory and register content for debugging.
The OS of these computers was very simple. Its major task was to transfer control
from one job to the next. The OS was always resident in the memory. The processing of
job was very slow. To improve the processing speed operators batched together the jobs
with similar needs and processed it through the computers. This is called Batch Systems.
In batch systems the CPU may be idle for some time because the speed of the
mechanical devices slower compared to the electronic devices.
Later improvement in technology and introduction of disks resulted in faster I/O
devices.
The introduction of disks allowed the OS to store all the jobs on the disk. The OS
could perform the scheduling to use the resources and perform the task efficiently.
The memory layout of simple batch system is shown below
OS
User
program
area
Disadvantages of Batch Systems:-
1. Turn around time can be large from user.
2. Difficult to debug the program.
3. A job can enter into infinite loop.
4. A job could corrupt the monitor.
5. Due to lack of protection scheme, one job may affect the pending jobs.
Multi programmed System:-
a. If there are two or more programs in the memory at the same time sharing the
processor, this is referred as multi programmed OS.
b. It increases the CPU utilization by organizing the jobs so that the CPU will
always have one job to execute.
c. Jobs entering the systems are kept in memory.
d. OS picks the job from memory & it executes it.
e. Having several jobs in the memory at the same time requires some form of
memory management.
f. Multi programmed systems monitors the state of all active program and system
resources and ensures that CPU is never idle until there are no jobs.
g. While executing a particular job, if the job has to wait for any task like I/O
operation to be complete then the CPU will switch to some other jobs and starts
executing it and when the first job finishes waiting the CPU will switch back to
that.
h. This will keep the CPU & I/O utilization busy.
The following figure shows the memory layout of multi programmed OS
Web Based Computing has increased the emphasis on N/w. Web based
computing uses PC, handheld PDA & cell phones. One of the feature of this type is load
balancing. In load balancing, N/w connection is distributed among a pool of similar
servers.
System Components :-
Modern OS supports all system components. The system components are,
1. Process Management.
2. Main M/y Management.
3. File Management.
4. Secondary Storage Management.
5. I/O System management.
6. Networking.
7. Protection System.
8. Command Interpreter System.
Process Management:-
A process is a program in execution.
A process abstraction is a fundamental OS mechanism for the management of
concurrent program execution.
The OS responds by creating process.
Process requires certain resources like CPU time, M/y, I/O devices. These
resources are allocated to the process when it created or while it is running.
When process terminates the process reclaims all the reusable resources.
Process refers to the execution of M/c instructions.
A program by itself is not a process but is a passive entity.
The OS is responsible for the following activities of the process management,
Creating & destroying of the user & system process .
Allocating H/w resources among the processes.
Controlling the progress of the process.
Provides mechanism for process communication.
Provides mechanism for deadlock handling.
Main Memory Management:-
Main M/y is the centre to the operation of the modern computer.
Main M/y is the array of bytes ranging from hundreds of thousands to billions.
Each byte will have their own address.
The central processor reads the instruction from main M/y during instruction fetch
cycle & it both reads & writes the data during the data-fetch cycle. The I/O
operation reads and writes data in main M/y.
The main M/y is generally a large storage device in which a CPU can address &
access directly.
When a program is to be executed it must be loaded into memory & mapped to
absolute address. When it is executing it access the data & instruction from M/y
by generating absolute address. When the program terminates all available M/y
will be returned back.
To improve the utilization of CPU & the response time several program will be
kept in M/y.
Several M/y management scheme are available & selection depends on the H/w
design of the system.
The OS is responsible for the following activities.
Keeping track of which part of the M/y is used & by whom.
Deciding which process are to be loaded into M/y.
Allocating & de allocating M/y space as needed.
File Management:-
File management is one of the most visible component of an OS.
Computer stores data on different types of physical media like Magnetic Disks,
Magnetic tapes, optical disks etc.
For convenient use of the computer system the OS provides uniform logical view
of information storage.
The OS maps file on to physical media & access these files via storage devices.
A file is logical collection of information.
File consists of both program & data. Data files may be numeric, alphabets or
alphanumeric.
Files can be organized into directories.
The OS is responsible for the following activities,
Creating & deleting of files.
Creating & deleting directories.
Supporting primitives for manipulating files & directories.
Maping files onto secondary storage.
Backing up files on stable storage media.
Secondary Storage management :-
Is a mechanism where the computer system may store information in a way that it
can be retrieved later.
They are used to store both data & programs.
The programs & data are stored in main memory.
Since the size of the M/y is small & volatile Secondary storage devices is used.
Magnetic disk is central importance of computer system.
The OS is responsible for the following activities,
Free space management.
Storage allocation.
Disk scheduling.
The entire speed of computer system depends on the speed of the disk sub system.
I/O System Management:-
Each I/o device has a device handler that resides in separate process associated
with that device.
The I/O management consists of,
A M/y management component that include buffering,, caching & spooling.
General device-driver interface.
Drivers for specific H/w device.
Networking :-
Networking enables users to share resources & speed up computations.
The process communicates with one another through various communication lines
like high speed buses or N/w.
Following parameters are considered while designing the N/w,
Topology of N/w.
Type of N/w.
Physical media.
Communication protocol,
Routing algorithms.
Protection system:-
Modern computer system supports many users & allows the concurrent execution
of multiple processes organization rely on computers to store information. It
necessary that the information & devices must be protected from unauthorized
users or processors.
The protection is a mechanism for controlling the access of program, processes or
users to the resources defined by a computer system.
Protection mechanism are implemented in OS to support various security policies.
The goal of security system is to authenticate their access to any object.
Protection can improve reliability by detecting latent errors at the interface B/w
component sub system.
Protection domains are extensions of H/w supervisor mode ability.
Command Interpreter System:-
Command interpreter system between the user & the OS. It is a system program
to the OS.
Command interpreter is a special program in UNIX & MS DOS OS i.e. running
when the user logs on.
Many commands are given to the OS through control statements when the user
logs on, a program that reads & interprets control statements is executed
automatically. This program is sometimes called the control card interpreter or
command line interpreter and is also called as shell.
The command statements themselves deal with process creation & management,
I/O handling, secondary storage management, main memory management, file
system access, protection & N/w.
OPERATING SYSTEM SERVICES:-
An OS provides services for the execution of the programs and the users of such
programs. The services provided by one OS may be different from other OS. OS makes
the programming task easier. The common services provided by the OS are
1. Program Execution:- The OS must able to load the program into memory & run
that program. The program must end its execution either normally or abnormally.
2. I/O Operation:- A program running may require any I/O. This I/O may be a file
or a specific device users cant control the I/O device directly so the OS must
provide a means for controlling I/O devices.
3. File System Interface:- Program need to read or write a file. The OS should
provide permission for the creation or deletion of files by names.
4. Communication:- In certain situation one process may need to exchange
information with another process. This communication May takes place in two
ways.
a. Between the processes executing on the same computer.
b. Between the processes executing on different computer that are connected
by a network.
This communication can be implemented via shared memory or by OS.
5. Error Detection:- Errors may occur in CPU, I/O devices or in M/y H/w. The OS
constantly needs to be aware of possible errors. For each type of errors the OS
should take appropriate actions to ensure correct & consistent computing.
OS with multiple users provides the following services,
a. Resource Allocation:- When multiple users logs onto the system or when
The OS manages different types of OS resources. Some resources may
need some special allocation codes & others may have some general
request & release code.
b. Accounting:- We need to keep track of which users use how many &
what kind of resources. This record keeping may be used for accounting.
This accounting data may be used for statistics or billing. It can also be
used to improve system efficiency.
c. Protection:- Protection ensures that all the access to the system are
controlled. Security starts with each user having authenticated to the
system, usually by means of a password. External I/O devices must also be
protected from invalid access. In multi process environment it is possible
that one process may interface with the other or with the OS, so protection
is required.
SYSTEM CALLS
System provides interface between the process & the OS.
The calls are generally available as assembly language instruction & certain
system allow system calls to be made directly from a high level language
program.
Several language have been defined to replace assembly language program.
A system call instruction generates an interrupt and allows OS to gain control of
the processors.
System calls occur in different ways depending on the computer. Some time more
information is needed to identify the desired system call. The exact type &
amount of information needed may vary according to the particular OS & call.
PASSING PARAMETERS TO OS
Three general methods are used to pass the parameters to the OS.
The simplest approach is to pass the parameters in registers. In some there can be
more parameters than register. In these the parameters are generally in a block or
table in m/y and the address of the block is passed as parameters in register. This
approach used by Linux.
Parameters can also be placed or pushed onto stack by the program & popped off
the stack by the OS.
Some OS prefer the block or stack methods, because those approaches do not
limit the number or length of parameters being passed.
System calls may be grouped roughly into 5 categories
1. Process control.
2. File management.
3. Device management.
4. Information maintenance.
5. Communication.
FILE MANAGEMENT
System calls can be used to create & deleting of files. System calls may require
the name of the files with attributes for creating & deleting of files.
Other operation may involve the reading of the file, write & reposition the file
after it is opened.
Finally we need to close the file.
For directories some set of operation are to be performed. Sometimes we require
to reset some of the attributes on files & directories. The system call get file
attribute & set file attribute are used for this type of operation.
DEVICE MANAGEMENT:-
The system calls are also used for accessing devices.
Many of the system calls used for files are also used for devices.
In multi user environment the requirement are made to use the device. After using
the device must be released using release system call the device is free to be used
by another user. These function are similar to open & close system calls of files.
Read, write & reposition system calls may be used with devices.
MS-DOS & UNIX merge the I/O devices & the files to form file services
structure. In file device structure I/O devices are identified by file names.
INFORMATION MAINTAINANCE:-
Many system calls are used to transfer information between user program & OS.
Example:- Most systems have the system calls to return the current time & date,
number of current users, version number of OS, amount of free m/y or disk space
& so on.
In addition the OS keeps information about all its processes & there are system
calls to access this
COMMUNICATION:-
There are two modes of communication,
1. Message Passing Models:-
In this information is exchanged using inter-process communication facility
provided by OS.
Before communication the connection should be opened.
The name of the other communicating party should be known, it ca be on the
same computer or it can be on another computer connected by a computer
network.
Each computer in a network may have a host name like IP name similarly each
process can have a process name which can be translated into equivalent identifier
by OS.
The get host id & process id system call do this translation. These identifiers are
then passed to the open & close connection system calls.
The recipient process must give its permission for communication to take place
with an accept connection call.
Most processes receive the connection through special purpose system program
dedicated for that purpose called daemons. The daemon on the server side is
called server daemon & the daemon on the client side is called client daemon.
2. Shared Memory:-
In this the processes uses the map m/y system calls to gain access to m/y owned
by another process.
The OS tries to prevent one process from accessing another process m/y.
In shared m/y this restriction is eliminated and they exchange information by
reading and writing data in shared areas. These areas are located by these
processes and not under OS control.
They should ensure that they are not writing to same m/y area.
Both these types are commonly used in OS and some even implement both.
Message passing is useful when small number of data need to be exchanged since
no conflicts are to be avoided and it is easier to implement than in shared m/y.
Shared m/y allows maximum speed and convenience of communication as it is
done at m/y speed when within a computer.
PROCESS CONTROL & JOB CONTROL
A system call can be used to terminate the program either normally or
abnormally. Reasons for abnormal termination are dump of m/y, error message
generated etc.
[Link]
Debugger is mainly used to determine problem of the dump & returns back the
dump to the OS.
In normal or abnormal situations the OS must transfer the control to the command
interpreter system.
In batch system the command interpreter terminates the execution of job &
continues with the next job.
Some systems use control cards to indicate the special recovery action to be taken
in case of errors.
Normal & abnormal termination can be combined at some errors level. Error level
is defined before & he command interpreter uses this error level to determine next
action automatically.
MS-DOS:-
MS-DOS is an example of single tasking system, which has command interpreter system
i.e. invoked when the computer is started. To run a program MS-DOS uses simple
method. It does not create a process when one process is running MS-DOS the program
into m/y & gives the program as much as possible. It lacks the general multitasking
capabilities.
BSD:-
Free BSD is an example of multitasking system. In free BSD the command interpreter
may continue running while other program is executing. FORK is used to create new
process.
SYSTEM STRUCTURES
Modern OS is large & complex.
OS consists of different types of components.
These components are interconnected & melded into kernel.
Ready Queue:-
The process that are placed in main m/y and are already and waiting to executes are
placed in a list called the ready queue. This is in the form of linked list. Ready queue
header contains pointer to the first & final PCB in the list. Each PCB contains a
pointer field that points next PCB in ready queue.
Device Queue:-
The list of processes waiting for a particular I/O device is called device. When the CPU is
allocated to a process it may execute for some time & may quit or interrupted or wait for
the occurrence of a particular
busy with some other processes. In this case the process must wait for I/O. This will be
placed in device queue. Each device will have its own queue.
The process scheduling is represented using a queuing diagram. Queues are represented
by the rectangular box & resources they need are represented by circles. It contains two
queues ready queue & device queues.
Once the process is assigned to CPU and is executing the following events can occur,
a. It can execute an I/O request and is placed in I/O queue.
b. The process can create a sub process & wait for its termination.
c. The process may be removed from the CPU as a result of interrupt and can
be put back into ready queue.
Schedulers:-
The following are the different type of schedulers
1. Long-term scheduler (or job scheduler) – selects which processes should be
brought into the ready queue.
2. Short-term scheduler (or CPU scheduler) – selects which process should be
executed next and allocates CPU.
3. Medium-term schedulers
-> Short-term scheduler is invoked very frequently (milliseconds) (must be fast)
-> Long-term scheduler is invoked very infrequently (seconds, minutes) (may be
slow)
-> The long-term scheduler controls the degree of multiprogramming
->Processes can be described as either:
I/O-bound process – spends more time doing I/O than computations,
many short CPU bursts
CPU-bound process – spends more time doing computations; few very
long CPU bursts
Context Switch:-
1. When CPU switches to another process, the system must save the state of the old
process and load the saved state for the new process.
2. Context-switch time is overhead; the system does no useful work while switching.
3. Time dependent on hardware support
Cooperating Processes & Independent Processes
Independent process: one that is independent of the rest of the universe.
Its state is not shared in any way by any other process.
Deterministic: input state alone determines results.
Reproducible.
Can stop and restart with no bad effects (only time varies). Example: program that
sums the integers from 1 to i (input).
There are many different ways in which a collection of independent processes might be
executed on a processor:
Uniprogramming: a single process is run to completion before anything else can
be run on the processor.
Multiprogramming: share one processor among several processes. If no shared
state, then order of dispatching is irrelevant.
Multiprocessing: if multiprogramming works, then it should also be ok to run
processes in parallel on separate processors.
o A given process runs on only one processor at a time.
o A process may run on different processors at different times (move state,
assume processors are identical).
o Cannot distinguish multiprocessing from multiprogramming on a very fine
grain.
Cooperating processes:
Machine must model the social structures of the people that use it. People
cooperate, so machine must support that cooperation. Cooperation means shared
state, e.g. a single file system.
Cooperating processes are those that share state. (May or may not actually be
"cooperating")
Behavior is nondeterministic: depends on relative execution sequence and cannot
be predicted a priori.
Behavior is irreproducible.
Example: one process writes "ABC", another writes "CBA". Can get different
outputs, cannot tell what comes from which. E.g. which process output first "C"
in "ABCCBA"? Note the subtle state sharing that occurs here via the terminal.
Not just anything can happen, though. For example, "AABBCC" cannot occur.
1. Independent process cannot affect
or be affected by the execution of
another process
2. Cooperating process can affect or
be affected by the execution of
another process
3. Advantages of process
cooperation
Information sharing
Computation speed-up
Modularity
Convenience
Interprocess Communication (IPC)
1. Mechanism for processes to communicate and to synchronize their actions
2. Message system – processes communicate with each other without resorting to
shared variables
3. IPC facility provides two operations:
send(message) – message size fixed or variable
receive(message)
4. If P and Q wish to communicate, they need to:
establish a communication link between them
exchange messages via send/receive
5. Implementation of communication link
physical (e.g., shared memory, hardware bus)
logical (e.g., logical properties)
Communications Models
there are two types of communication models
1. Multi programming
2. Shared Memory
Direct Communication
1. Processes must name each other explicitly:
send (P, message) – send a message to process P
receive(Q, message) – receive a message from process Q
2. Properties of communication link
Links are established automatically
A link is associated with exactly one pair of communicating processes
Between each pair there exists exactly one link
The link may be unidirectional, but is usually bi-directional
Indirect Communication
1. Messages are directed and received from mailboxes (also referred to as ports)
Each mailbox has a unique id
Processes can communicate only if they share a mailbox
2. Properties of communication link
Link established only if processes share a common mailbox
A link may be associated with many processes
Each pair of processes may share several communication links
Link may be unidirectional or bi-directional
3. Operations
o create a new mailbox
o send and receive messages through mailbox
o destroy a mailbox
[Link] are defined as:
send(A, message) – send a message to mailbox A
receive(A, message) – receive a message from mailbox A
5. Mailbox sharing
P1, P2, and P3 share mailbox A
P1, sends; P2 and P3 receive
Who gets the message?
6. Solutions
Allow a link to be associated with at most two processes
Allow only one process at a time to execute a receive operation
Allow the system to select arbitrarily the receiver. Sender is notified who the
receiver was.
Synchronization
1. Message passing may be either blocking or non-blocking
2. Blocking is considered synchronous
->Blocking send has the sender block until the message is received.
->Blocking receive has the receiver block until a message is available.
3. Non-blocking is considered asynchronous
->Non-blocking send has the sender send the message and continue.
User-Level Threads
1. Thread management done by user-level threads library
2. Three primary thread libraries:
-> POSIX Pthreads
-> Win32 threads
-> Java threads
User-level threads implement in user-level libraries, rather than via systems calls, so
thread switching does not need to call operating system and to cause interrupt to the
kernel. In fact, the kernel knows nothing about user-level threads and manages them as if
they were single-threaded processes.
Advantages:
The most obvious advantage of this technique is that a user-level threads package can be
implemented on an Operating System that does not support threads. Some other
advantages are
User-level threads does not require modification to operating systems.
Simple representation:
Each thread is represented simply by a PC, registers, stack and a small control
block, all stored in the user process address space.
Simple Management:
This simply means that creating a thread, switching between threads and
synchronization between threads can all be done without intervention of the
kernel.
Fast and Efficient:
Thread switching is not much more expensive than a procedure call.
Disadvantages:
There is a lack of coordination between threads and operating system kernel.
Therefore, process as whole gets one time slice irrespect of whether process has
one thread or 1000 threads within. It is up to each thread to relinquish control to
other threads.
User-level threads requires non-blocking systems call i.e., a multithreaded kernel.
Otherwise, entire process will blocked in the kernel, even if there are runable
threads left in the processes. For example, if one thread causes a page fault, the
process blocks.
Kernel-Level Threads
1. Supported by the Kernel
2. Examples
->Windows XP/2000
->Solaris
->Linux
->Tru64 UNIX
->Mac OS X
In this method, the kernel knows about and manages the threads. No runtime system is
needed in this case. Instead of thread table in each process, the kernel has a thread table
that keeps track of all threads in the system. In addition, the kernel also maintains the
traditional process table to keep track of processes. Operating Systems kernel provides
system call to create and manage threads.
Advantages:
Because kernel has full knowledge of all threads, Scheduler may decide to give
more time to a process having large number of threads than process having small
number of threads.
Kernel-level threads are especially good for applications that frequently block.
Disadvantages:
The kernel-level threads are slow and inefficient. For instance, threads operations
are hundreds of times slower than that of user-level threads.
Since kernel must manage and schedule threads as well as processes. It require a
full thread control block (TCB) for each thread to maintain information about
threads. As a result there is significant overhead and increased in kernel
complexity.
Advantages of Threads over Multiple Processes
Context Switching Threads are very inexpensive to create and destroy, and
they are inexpensive to represent. For example, they require space to store, the
PC, the SP, and the general-purpose registers, but they do not require space to
share memory information, Information about open files of I/O devices in use,
etc. With so little context, it is much faster to switch between threads. In other
words, it is relatively easier for a context switch using threads.
Sharing Treads allow the sharing of a lot resources that cannot be shared in
process, for example, sharing code section, data section, Operating System
resources like open file etc.
Disadvantages of Threads over Multiprocesses
Blocking The major disadvantage if that if the kernel is single threaded, a
system call of one thread will block the whole process and CPU may be idle
during the blocking period.
Security Since there is, an extensive sharing among threads there is a potential
problem of security. It is quite possible that one thread over writes the stack of
another thread (or damaged shared data) although it is very unlikely since threads
are meant to cooperate on a single task.
Application that Benefits from Threads
A proxy server satisfying the requests for a number of computers on a LAN would be
benefited by a multi-threaded process. In general, any program that has to do more than
one task at a time could benefit from multitasking. For example, a program that reads
input, process it, and outputs could have three threads, one for each task.
Application that cannot Benefit from Threads
Any sequential process that cannot be divided into parallel task will not benefit from
thread, as they would block until the previous one completes. For example, a program
that displays the time of the day would not benefit from multiple threads.
Multithreading Models
Many-to-One
One-to-One
Many-to-Many
Many-to-One
Many user-level threads mapped to single kernel thread
->Examples:
->Solaris Green Threads
->GNU Portable Threads
One-to-One
1. Each user-level thread maps to kernel thread
2. Examples
Windows NT/XP/2000
Linux
Solaris 9 and later
Many-to-Many Model
1. Allows many user level threads to be mapped to many kernel threads.
2. Allows the operating system to create a sufficient number of kernel threads.
3. Solaris prior to version 9.
4. Windows NT/2000 with the ThreadFiber package.
When a new thread is created it shares its code section, data section and operating system
resources like open files with other threads. But it is allocated its own stack, register set
and a program counter.
The creation of a new process differs from that of a thread mainly in the fact that all the
shared resources of a thread are needed explicitly for each process. So though two
processes may be running the same piece of code they need to have their own copy of the
code in the main memory to be able to run. Two processes also do not share other
resources with each other. This makes the creation of a new process very costly
compared to that of a new thread.
Thread Pools
1. Create a number of threads in a pool where they await work
2. Advantages:
Usually slightly faster to service a request with an existing thread than
create a new thread
Allows the number of threads in the application(s) to be bound to the
size of the pool
Context Switch
To give each process on a multiprogrammed machine a fair share of the CPU, a hardware
clock generates interrupts periodically. This allows the operating system to schedule all
processes in main memory (using scheduling algorithm) to run on the CPU at equal
intervals. Each time a clock interrupt occurs, the interrupt handler checks how much time
the current running process has used. If it has used up its entire time slice, then the CPU
scheduling algorithm (in kernel) picks a different process to run. Each switch of the CPU
from one process to another is called a context switch.
Major Steps of Context Switching
The values of the CPU registers are saved in the process table of the process that
was running just before the clock interrupt occurred.
The registers are loaded from the process picked by the CPU scheduler to run
next.
In a multiprogrammed uniprocessor computing system, context switches occur frequently
enough that all processes appear to be running concurrently. If a process has more than
one thread, the Operating System can use the context switching technique to schedule the
threads so they appear to execute in parallel.
This is the case if threads are implemented at the kernel level. Threads can also be
implemented entirely at the user level in run-time libraries. Since in this case no thread
scheduling is provided by the Operating System, it is the responsibility of the
programmer to yield the CPU frequently enough in each thread so all threads in the
process can make progress.
Action of Kernel to Context Switch Among Threads
The threads share a lot of resources with other peer threads belonging to the same
process. So a context switch among threads for the same process is easy. It involves
switch of register set, the program counter and the stack. It is relatively easy for the
kernel to accomplished this task.
Action of kernel to Context Switch Among Processes
Context switches among processes are expensive. Before a process can be switched its
process control block (PCB) must be saved by the operating system. The PCB consists of
the following information:
The process state.
The program counter, PC.
The values of the different registers.
The CPU scheduling information for the process.
Memory management information regarding the process.
Possible accounting information for this process.
I/O status information of the process.
When the PCB of the currently executing process is saved the operating system loads the
PCB of the next process that has to be run on CPU. This is a heavy task and it takes a lot
of time.
CPU/Process Scheduling:-
The assignment of physical processors to processes allows processors to accomplish
work. The problem of determining when processors should be assigned and to which
processes is called processor scheduling or CPU scheduling.
When more than one process is runable, the operating system must decide which
one first. The part of the operating system concerned with this decision is called the
scheduler, and algorithm it uses is called the scheduling algorithm.
CPU Scheduler
a. Selects from among the processes in memory that are ready to execute, and
allocates the CPU to one of them
b. CPU scheduling decisions may take place when a process:
1. Switches from running to waiting state
2. Switches from running to ready state
3. Switches from waiting to ready
4. Terminates
Scheduling under 1 and 4 is nonpreemptive
All other scheduling is preemptive
Dispatcher
1. Dispatcher module gives control of the CPU to the process selected by the short-
term scheduler; this involves:
switching context
switching to user mode
jumping to the proper location in the user program to restart that
program
2. Dispatch latency – time it takes for the dispatcher to stop one process and start
another running.
Scheduling Criteria
1. CPU utilization – keep the CPU as busy as possible
2. Throughput – # of processes that complete their execution per time unit
3. Turnaround time – amount of time to execute a particular process
4. Waiting time – amount of time a process has been waiting in the ready queue
5. Response time – amount of time it takes from when a request was submitted until
the first response is produced, not output (for time-sharing environment)
General Goals
Fairness
Fairness is important under all circumstances. A scheduler makes sure that each
process gets its fair share of the CPU and no process can suffer indefinite postponement.
Note that giving equivalent or equal time is not fair. Think of safety control and payroll
at a nuclear plant.
Policy Enforcement
The scheduler has to make sure that system's policy is enforced. For example, if the
local policy is safety then the safety control processes must be able to run whenever they
want to, even if it means delay in payroll processes.
Efficiency
Scheduler should keep the system (or in particular CPU) busy cent percent of the
time when possible. If the CPU and all the Input/Output devices can be kept running all
the time, more work gets done per second than if some components are idle.
Response Time
A scheduler should minimize the response time for interactive user.
Turnaround
A scheduler should minimize the time batch users must wait for an output.
Throughput
A scheduler should maximize the number of jobs processed per unit time.
A little thought will show that some of these goals are contradictory. It can be shown that
any scheduling algorithm that favors some class of jobs hurts another class of jobs. The
amount of CPU time available is finite, after all.
Preemptive Vs Nonpreemptive Scheduling
The Scheduling algorithms can be divided into two categories with respect to how they
deal with clock interrupts.
Nonpreemptive Scheduling
A scheduling discipline is nonpreemptive if, once a process has been given the CPU, the
CPU cannot be taken away from that process.
Following are some characteristics of nonpreemptive scheduling
1. In nonpreemptive system, short jobs are made to wait by longer jobs but the
overall treatment of all processes is fair.
2. In nonpreemptive system, response times are more predictable because incoming
high priority jobs can not displace waiting jobs.
3. In nonpreemptive scheduling, a schedular executes jobs in the following two
situations.
a. When a process switches from running state to the waiting state.
b. When a process terminates.
Preemptive Scheduling
A scheduling discipline is preemptive if, once a process has been given the CPU can
taken away.
The strategy of allowing processes that are logically runable to be temporarily suspended
is called Preemptive Scheduling and it is contrast to the "run to completion" method.
Scheduling Algorithms
CPU Scheduling deals with the problem of deciding which of the processes in the ready
queue is to be allocated the CPU.
Following are some scheduling algorithms we will study
FCFS Scheduling.
Round Robin Scheduling.
SJF Scheduling.
SRT Scheduling.
Priority Scheduling.
Multilevel Queue Scheduling.
Multilevel Feedback Queue Scheduling.
A. First-Come-First-Served (FCFS) Scheduling
Other names of this algorithm are:
First-In-First-Out (FIFO)
Run-to-Completion
Run-Until-Done
Perhaps, First-Come-First-Served algorithm is the simplest scheduling algorithm is the
simplest scheduling algorithm. Processes are dispatched according to their arrival time on
the ready queue. Being a nonpreemptive discipline, once a process has a CPU, it runs to
completion. The FCFS scheduling is fair in the formal sense or human sense of fairness
but it is unfair in the sense that long jobs make short jobs wait and unimportant jobs make
important jobs wait.
FCFS is more predictable than most of other schemes since it offers time. FCFS scheme
is not useful in scheduling interactive users because it cannot guarantee good response
time. The code for FCFS scheduling is simple to write and understand.
One of the major drawback of this scheme is that the average time is often quite
long. The First-Come-First-Served algorithm is rarely used as a master scheme in
modern operating systems but it is often embedded within other schemes.
Example:-
Process Burst Time
P1 24
P2 3
P3 3
Suppose that the processes arrive in the order: P1 , P2 , P3
The Gantt Chart for the schedule is:
P1 P2 P3
0 24 27 30
Waiting time for P1 = 0; P2 = 24; P3 = 27
Average waiting time: (0 + 24 + 27)/3 = 17
Suppose that the processes arrive in the order P2 , P3 , P1
The Gantt chart for the schedule is:
P2 P3 P1
0 3 6 30
Waiting time for P1 = 6; P2 = 0; P3 = 3
Average waiting time: (6 + 0 + 3)/3 = 3
Much better than previous case
Convoy effect short process behind long process
B. Round Robin Scheduling
One of the oldest, simplest, fairest and most widely used algorithm is round robin (RR).
In the round robin scheduling, processes are dispatched in a FIFO manner but are given a
limited amount of CPU time called a time-slice or a quantum.
If a process does not complete before its CPU-time expires, the CPU is preempted
and given to the next process waiting in a queue. The preempted process is then placed at
the back of the ready list.
Round Robin Scheduling is preemptive (at the end of time-slice) therefore it is
effective in time-sharing environments in which the system needs to guarantee reasonable
response times for interactive users.
The only interesting issue with round robin scheme is the length of the quantum.
Setting the quantum too short causes too many context switches and lower the CPU
efficiency. On the other hand, setting the quantum too long may cause poor response time
and appoximates FCFS.
In any event, the average waiting time under round robin scheduling is often quite long.
1. Each process gets a small unit of CPU time (time quantum), usually 10-100
milliseconds. After this time has elapsed, the process is preempted and added to
the end of the ready queue.
2. If there are n processes in the ready queue and the time quantum is q, then each
process gets 1/n of the CPU time in chunks of at most q time units at once. No
process waits more than (n-1)q time units.
3. Performance
->q large FIFO
->q small q must be large with respect to context switch, otherwise
overhead is too high.
Example:-
Process Burst Time
P1 53
P2 17
P3 68
P4 24
The Gantt chart is:
P1 P2 P3 P4 P1 P3 P4 P1 P3 P3
P1 P2 P3 P2 P4 P1
0 2 4 5 7 11 16
->Average waiting time = (9 + 1 + 0 +2)/4 = 3
D. Shortest-Remaining-Time (SRT) Scheduling
The SRT is the preemtive counterpart of SJF and useful in time-sharing
environment.
In SRT scheduling, the process with the smallest estimated run-time to
completion is run next, including new arrivals.
In SJF scheme, once a job begin executing, it run to completion.
In SJF scheme, a running process may be preempted by a new arrival process
with shortest estimated run-time.
The algorithm SRT has higher overhead than its counterpart SJF.
The SRT must keep track of the elapsed time of the running process and must
handle occasional preemptions.
In this scheme, arrival of small processes will run almost immediately. However,
longer jobs have even longer mean waiting time.
E. Priority Scheduling
1. A priority number (integer) is associated with each process
2. The CPU is allocated to the process with the highest priority (smallest integer
highest priority)
->Preemptive
->nonpreemptive
3. SJF is a priority scheduling where priority is the predicted next CPU burst time
4. Problem Starvation – low priority processes may never execute
5. Solution Aging – as time progresses increase the priority of the process
The basic idea is straightforward: each process is assigned a priority, and priority is
allowed to run. Equal-Priority processes are scheduled in FCFS order. The shortest-Job-
First (SJF) algorithm is a special case of general priority scheduling algorithm.
An SJF algorithm is simply a priority algorithm where the priority is the inverse
of the (predicted) next CPU burst. That is, the longer the CPU burst, the lower the
priority and vice versa.
Priority can be defined either internally or externally. Internally defined priorities
use some measurable quantities or qualities to compute priority of a process.
Examples of Internal priorities are
Time limits.
Memory requirements.
File requirements,
for example, number of open files.
CPU Vs I/O requirements.
Externally defined priorities are set by criteria that are external to operating system such
as
The importance of process.
Type or amount of funds being paid for computer use.
The department sponsoring the work.
Politics.
Priority scheduling can be either preemptive or non preemptive
A preemptive priority algorithm will preemptive the CPU if the priority of the
newly arrival process is higher than the priority of the currently running process.
A non-preemptive priority algorithm will simply put the new process at the head
of the ready queue.
A major problem with priority scheduling is indefinite blocking or starvation. A solution
to the problem of indefinite blockage of the low-priority process is aging. Aging is a
technique of gradually increasing the priority of processes that wait in the system for a
long period of time.
F. Multilevel Queue Scheduling
A multilevel queue scheduling algorithm partitions the ready queue in several separate
queues, for instance
In a multilevel queue scheduling processes are permanently assigned to one queues.
The processes are permanently assigned to one another, based on some property of the
process, such as
Memory size
Process priority
Process type
Algorithm choose the process from the occupied queue that has the highest priority, and
run that process either
Preemptive or
Non-preemptively
Each queue has its own scheduling algorithm or policy.
Possibility I
If each queue has absolute priority over lower-priority queues then no process in the
queue could run unless the queue for the highest-priority processes were all empty.
For example, in the above figure no process in the batch queue could run unless
the queues for system processes, interactive processes, and interactive editing processes
will all empty.
Possibility II
If there is a time slice between the queues then each queue gets a certain amount of
CPU times, which it can then schedule among the processes in its queue. For instance;
80% of the CPU time to foreground queue using RR.
20% of the CPU time to background queue using FCFS.
Since processes do not move between queue so, this policy has the advantage of low
scheduling overhead, but it is inflexible.
G. Multilevel Feedback Queue Scheduling
Multilevel feedback queue-scheduling algorithm allows a process to move between
queues. It uses many ready queues and associate a different priority with each queue.
The Algorithm chooses to process with highest priority from the occupied queue and run
that process either preemptively or unpreemptively.
If the process uses too much CPU time it will moved to a lower-priority queue.
Similarly, a process that wait too long in the lower-priority queue may be moved to a
higher-priority queue may be moved to a highest-priority queue. Note that this form of
aging prevents starvation.
A process entering the ready queue is placed in queue 0.
If it does not finish within 8 milliseconds time, it is moved to the tail of queue 1.
If it does not complete, it is preempted and placed into queue 2.
Processes in queue 2 run on a FCFS basis, only when 2 run on a FCFS basis
queue, only when queue 0 and queue 1 are empty.
Example:-
1. Three queues:
Q0 – RR with time quantum 8 milliseconds
Q1 – RR time quantum 16 milliseconds
Q2 – FCFS
2. Scheduling
A new job enters queue Q0 which is served FCFS. When it gains CPU,
job receives 8 milliseconds. If it does not finish in 8 milliseconds, job
is moved to queue Q1.
At Q1 job is again served FCFS and receives 16 additional
milliseconds. If it still does not complete, it is preempted and moved
to queue Q2.
Process Synchronization
Interprocess Communication
Since processes frequently needs to communicate with other processes therefore, there is
a need for a well-structured communication, without using interrupts, among processes.
Race Conditions
In operating systems, processes that are working together share some common
storage (main memory, file etc.) that each process can read and write. When two or
more processes are reading or writing some shared data and the final result depends
on who runs precisely when, are called race conditions.
Concurrently executing threads that share data need to synchronize their operations
and processing in order to avoid race condition on shared data. Only one ‘customer’
thread at a time should be allowed to examine and update the shared variable.
Race conditions are also possible in Operating Systems.
If the ready queue is implemented as a linked list and if the ready queue is being
manipulated during the handling of an interrupt, then interrupts must be disabled to
prevent another interrupt before the first one completes. If interrupts are not disabled than
the linked list could become corrupt.
1. count++ could be implemented as
register1 = count
register1 = register1 + 1
count = register1
2. count-- could be implemented as
register2 = count
register2 = register2 – 1
count = register2
3. Consider this execution interleaving with “count = 5” initially:
S0: producer execute register1 = count {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = count {register2 = 5}
S3: consumer execute register2 = register2 - 1 {register2 = 4}
S4: producer execute count = register1 {count = 6 }
S5: consumer execute count = register2 {count = 4}
Solution to Critical-Section Problem
1. Mutual Exclusion - If process Pi is executing in its critical section, then no other
processes can be executing in their critical sections
2. Progress - If no process is executing in its critical section and there exist some
processes that wish to enter their critical section, then the selection of the processes that
will enter the critical section next cannot be postponed indefinitely
3. Bounded Waiting - A bound must exist on the number of times that other
processes are allowed to enter their critical sections after a process has made a request to
enter its critical section and before that request is granted
⚫ Assume that each process executes at a nonzero speed
⚫ No assumption concerning relative speed of the N processes
A. Critical Section
The key to preventing trouble involving shared storage is find some way to prohibit
more than one process from reading and writing the shared data simultaneously. That
part of the program where the shared memory is accessed is called the Critical
Section.
To avoid race conditions and flawed results, one must identify codes in Critical
Sections in each thread. The characteristic properties of the code that form a Critical
Section are
Codes that reference one or more variables in a “read-update-write” fashion while
any of those variables is possibly being altered by another thread.
Codes that alter one or more variables that are possibly being referenced in “read-
updata-write” fashion by another thread.
Codes use a data structure while any part of it is possibly being altered by another
thread.
Codes alter any part of a data structure while it is possibly in use by another
thread.
Here, the important point is that when one process is executing shared modifiable
data in its critical section, no other process is to be allowed to execute in its
critical section. Thus, the execution of critical sections by the processes is
mutually exclusive in time.
B. Mutual Exclusion
A way of making sure that if one process is using a shared modifiable data, the other
processes will be excluded from doing the same thing.
Formally, while one process executes the shared variable, all other processes
desiring to do so at the same time moment should be kept waiting; when that process has
finished executing the shared variable, one of the processes waiting; while that process
has finished executing the shared variable, one of the processes waiting to do so should
be allowed to proceed.
In this fashion, each process executing the shared data (variables) excludes all
others from doing so simultaneously. This is called Mutual Exclusion.
Note that mutual exclusion needs to be enforced only when processes access
shared modifiable data - when processes are performing operations that do not conflict
with one another they should be allowed to proceed concurrently.
Mutual Exclusion Conditions
If we could arrange matters such that no two processes were ever in their critical sections
simultaneously, we could avoid race conditions. We need four conditions to hold to have
a good solution for the critical section problem (mutual exclusion).
No two processes may at the same moment inside their critical sections.
No assumptions are made about relative speeds of processes or number of CPUs.
No process should outside its critical section should block other processes.
No process should wait arbitrary long to enter its critical section.
C. Proposals for Achieving Mutual Exclusion
The mutual exclusion problem is to devise a pre-protocol (or entry protocol) and a post-
protocol (or exist protocol) to keep two or more threads from being in their critical
sections at the same time.
Problem
When one process is updating shared modifiable data in its critical section, no other
process should allowed to enter in its critical section.
Proposal 1 -Disabling Interrupts (Hardware Solution)
Each process disables all interrupts just after entering in its critical section and re-enable
all interrupts just before leaving critical section. With interrupts turned off the CPU could
not be switched to other process. Hence, no other process will enter its critical and mutual
exclusion achieved.
Conclusion
Disabling interrupts is sometimes a useful interrupts is sometimes a useful technique
within the kernel of an operating system, but it is not appropriate as a general mutual
exclusion mechanism for users process. The reason is that it is unwise to give user
process the power to turn off interrupts.
Proposal 2 - Lock Variable (Software Solution)
In this solution, we consider a single, shared, (lock) variable, initially 0. When a process
wants to enter in its critical section, it first test the lock. If lock is 0, the process first sets
it to 1 and then enters the critical section. If the lock is already 1, the process just waits
until (lock) variable becomes 0. Thus, a 0 means that no process in its critical section, and
1 means hold your horses - some process is in its critical section.
Conclusion
The flaw in this proposal can be best explained by example. Suppose process A sees that
the lock is 0. Before it can set the lock to 1 another process B is scheduled, runs, and sets
the lock to 1. When the process A runs again, it will also set the lock to 1, and two
processes will be in their critical section simultaneously.
Proposal 3 - Strict Alteration
In this proposed solution, the integer variable 'turn' keeps track of whose turn is to enter
the critical section. Initially, process A inspect turn, finds it to be 0, and enters in its
critical section. Process B also finds it to be 0 and sits in a loop continually testing 'turn'
to see when it becomes [Link] testing a variable waiting for some value to
appear is called the Busy-Waiting.
Conclusion
Taking turns is not a good idea when one of the processes is much slower than the other.
Suppose process 0 finishes its critical section quickly, so both processes are now in their
noncritical section. This situation violates above mentioned condition 3.
Using Systems calls 'sleep' and 'wakeup'
Basically, what above mentioned solution do is this: when a processes wants to enter in
its critical section , it checks to see if then entry is allowed. If it is not, the process goes
into tight loop and waits (i.e., start busy waiting) until it is allowed to enter. This
approach waste CPU-time.
Now look at some interprocess communication primitives is the pair of steep-wakeup.
Sleep
o It is a system call that causes the caller to block, that is, be suspended until
some other process wakes it up.
Wakeup
o It is a system call that wakes up the process.
Both 'sleep' and 'wakeup' system calls have one parameter that represents a memory
address used to match up 'sleeps' and 'wakeups' .
The Bounded Buffer Producers and Consumers
The bounded buffer producers and consumers assumes that there is a fixed buffer size
i.e., a finite numbers of slots are available.
Statement
To suspend the producers when the buffer is full, to suspend the consumers when the
buffer is empty, and to make sure that only one process at a time manipulates a buffer so
there are no race conditions or lost updates.
As an example how sleep-wakeup system calls are used, consider the producer-consumer
problem also known as bounded buffer problem.
Two processes share a common, fixed-size (bounded) buffer. The producer puts
information into the buffer and the consumer takes information out.
Trouble arises when
1. The producer wants to put a new data in the buffer, but buffer is already full.
Solution: Producer goes to sleep and to be awakened when the consumer has
removed data.
2. The consumer wants to remove data the buffer but buffer is already empty.
Solution: Consumer goes to sleep until the producer puts some data in buffer and
wakes consumer up.
Conclusion
This approaches also leads to same race conditions we have seen in earlier approaches.
Race condition can occur due to the fact that access to 'count' is unconstrained. The
essence of the problem is that a wakeup call, sent to a process that is not sleeping, is lost.
D. Semaphores
Definition
A semaphore is a protected variable whose value can be accessed and altered only by the
operations P and V and initialization operation called 'Semaphoiinitislize'.
Binary Semaphores can assume only the value 0 or the value 1 counting semaphores also
called general semaphores can assume only nonnegative values.
The P (or wait or sleep or down) operation on semaphores S, written as P(S) or wait (S),
operates as follows:
P(S): IF S > 0
THEN S := S - 1
ELSE (wait on S)
The V (or signal or wakeup or up) operation on semaphore S, written as V(S) or signal
(S), operates as follows:
V(S): IF (one or more process are waiting on S)
THEN (let one of these processes proceed)
ELSE S := S +1
Operations P and V are done as single, indivisible, atomic action. It is guaranteed that
once a semaphore operations has stared, no other process can access the semaphore until
operation has completed. Mutual exclusion on the semaphore, S, is enforced within P(S)
and V(S).
If several processes attempt a P(S) simultaneously, only process will be allowed to
proceed. The other processes will be kept waiting, but the implementation of P and V
guarantees that processes will not suffer indefinite postponement.
Semaphores solve the lost-wakeup problem.
Semaphore as General Synchronization Tool
1. Counting semaphore – integer value can range over an unrestricted domain.
2. Binary semaphore – integer value can range only between 0
and 1; can be simpler to implement Also known as mutex locks.
3. Can implement a counting semaphore S as a binary semaphore.
4. Provides mutual exclusion
Semaphore S; // initialized to 1
wait (S);
Critical Section
signal (S);
Semaphore Implementation
1. Must guarantee that no two processes can execute wait () and signal () on the
same semaphore at the same time
2. Thus, implementation becomes the critical section problem where the wait and
signal code are placed in the crtical section.
Could now have busy waiting in critical section implementation
But implementation code is short
Little busy waiting if critical section rarely occupied
3. Note that applications may spend lots of time in critical sections and therefore this
is not a good solution.
Semaphore Implementation with no Busy waiting
1. With each semaphore there is an associated waiting queue. Each entry in a
waiting queue has two data items:
value (of type integer)
pointer to next record in the list
2. 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.
->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); }
}
Synchronization Hardware
1. Many systems provide hardware support for critical section code
2. Uniprocessors – could disable interrupts
Currently running code would execute without preemption
Generally too inefficient on multiprocessor systems
Operating systems using this not broadly scalable
3. Modern machines provide special atomic hardware instructions
->Atomic = non-interruptable
Either test memory word and set value
Or swap contents of two memory words
Classical Problems of Synchronization
1. Bounded-Buffer Problem
2. Readers and Writers Problem
3. Dining-Philosophers Problem
Bounded-Buffer Problem
1. N buffers, each can hold one item
2. Semaphore mutex initialized to the value 1
3. Semaphore full initialized to the value 0
4. Semaphore empty initialized to the value N.
5. The structure of the producer process
while (true) {
// produce an item
wait (empty);
wait (mutex);
// add the item to the buffer
signal (mutex);
signal (full);
}
6. The structure of the consumer process
while (true) {
wait (full);
wait (mutex);
// remove an item from buffer
signal (mutex);
signal (empty);
// consume the removed item
}
Readers-Writers Problem
1. A data set is shared among a number of concurrent processes
o Readers – only read the data set; they do not perform any
updates
o Writers – can both read and write.
2. Problem – allow multiple readers to read at the same time. Only one single writer
can access the shared data at the same time.
3. Shared Data
o Data set
o Semaphore mutex initialized to 1.
o Semaphore wrt initialized to 1.
o Integer readcount initialized to 0.
4. The structure of a writer process
while (true) {
wait (wrt) ;
// writing is performed
signal (wrt) ;
}
5. The structure of a reader process
while (true) {
wait (mutex) ;
readcount ++ ;
if (readcount == 1) wait (wrt) ;
signal (mutex)
// reading is performed
wait (mutex) ;
readcount - - ;
if (readcount == 0) signal (wrt) ;
signal (mutex) ;
}
Dining-Philosophers Problem
1. Shared data
o Bowl of rice (data set)
o Semaphore chopstick [5] initialized to 1
2. The structure of Philosopher i:
While (true) {
wait ( chopstick[i] );
wait ( chopStick[ (i + 1) % 5] );
// eat
signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
}
Problems with Semaphores
1. Correct use of semaphore operations:
o signal (mutex) …. wait (mutex)
o wait (mutex) … wait (mutex)
o Omitting of wait (mutex) or signal (mutex) (or both)
Monitors
1. high-level abstraction that provides a convenient and effective mechanism for
process synchronization
2. Only one process may be active within the monitor at a time
monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }
…
procedure Pn (…) {……}
Initialization code ( ….) { … }
…
}
}
Solution to Dining Philosophers
monitor DP
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5];
Eg:- R1 R3
. .
P1 P2 P3
. .
.
. .
R2 R4
If the graph contain no cycle, then no process in the system is deadlock. If the
graph contains a cycle then a deadlock may exist.
If each resource type has exactly one instance than a cycle implies that a deadlock
has occurred. If each resource has several instances then a cycle do not
necessarily implies that a deadlock has occurred.
Methods for Handling Deadlocks:-
There are three ways to deal with deadlock problem
We can use a protocol to prevent deadlocks ensuring that the system will never
enter into the deadlock state.
We allow a system to enter into deadlock state, detect it and recover from it.
We ignore the problem and pretend that the deadlock never occur in the system.
This is used by most OS including UNIX.
To ensure that the deadlock never occur the system can use either
deadlock avoidance or a deadlock prevention.
Deadlock prevention is a set of method for ensuring that at least one of the
necessary conditions does not occur.
Deadlock avoidance requires the OS is given advance information about
which resource a process will request and use during its lifetime.
If a system does not use either deadlock avoidance or deadlock prevention
then a deadlock situation may occur. During this it can provide an
algorithm that examines the state of the system to determine whether a
deadlock has occurred and algorithm to recover from deadlock.
Undetected deadlock will result in deterioration of the system
performance.
Deadlock Prevention:-
For a deadlock to occur each of the four necessary conditions must hold. If at least
one of the there condition does not hold then we can prevent occurrence of deadlock.
1. Mutual Exclusion:-
This holds for non-sharable resources.
Eg:- A printer can be used by only one process at a time.
Mutual exclusion is not possible in sharable resources and thus
they cannot be involved in deadlock. Read-only files are good examples for sharable
resources. A process never waits for accessing a sharable resource. So we cannot prevent
deadlock by denying the mutual exclusion condition in non-sharable resources.
2. Hold and Wait:-
This condition can be eliminated by forcing a process to release all its resources held by it
when it request a resource i.e., not available.
One protocol can be used is that each process is allocated with all of its
resources before its start execution.
Eg:- consider a process that copies the data from a tape drive to the disk, sorts
the file and then prints the results to a printer. If all the resources are allocated
at the beginning then the tape drive, disk files and printer are assigned to the
process. The main problem with this is it leads to low resource utilization
because it requires printer at the last and is allocated with it from the
beginning so that no other process can use it.
Another protocol that can be used is to allow a process to request a
resource when the process has none. i.e., the process is allocated with tape
drive and disk file. It performs the required operation and releases both.
Then the process once again request for disk file and the printer and the
problem and with this is starvation is possible.
3. No Preemption:-
To ensure that this condition never occurs the resources must be
preempted. The following protocol can be used.
If a process is holding some resource and request another resource that
cannot be immediately allocated to it, then all the resources currently held
by the requesting process are preempted and added to the list of resources
for which other processes may be waiting. The process will be restarted
only when it regains the old resources and the new resources that it is
requesting.
When a process request resources, we check whether they are available or
not. If they are available we allocate them else we check that whether they
are allocated to some other waiting process. If so we preempt the
resources from the waiting process and allocate them to the requesting
process. The requesting process must wait.
4. Circular Wait:-
The fourth and the final condition for deadlock is the circular wait
condition. One way to ensure that this condition never, is to impose ordering on all
resource types and each process requests resource in an increasing order.
Let R={R1,R2,………Rn} be the set of resource types. We assign
each resource type with a unique integer value. This will allows us to compare two
resources and determine whether one precedes the other in ordering.
Eg:-we can define a one to one function
F:RN as follows :- F(disk drive)=5
F(printer)=12
F(tape drive)=1
Deadlock can be prevented by using the following protocol:-
Each process can request the resource in increasing order.
A process can request any number of instances of resource
type say Ri and it can request instances of resource type Rj
only F(Rj) > F(Ri).
Alternatively when a process requests an instance of
resource type Rj, it has released any resource Ri such that
F(Ri) >= F(Rj).
If these two protocol are used then the circular wait can’t hold.
Deadlock Avoidance:-
Deadlock prevention algorithm may lead to low device utilization and reduces
system throughput.
Avoiding deadlocks requires additional information about how resources are to be
requested. With the knowledge of the complete sequences of requests and releases
we can decide for each requests whether or not the process should wait.
For each requests it requires to check the resources currently available, resources
that are currently allocated to each processes future requests and release of each
process to decide whether the current requests can be satisfied or must wait to
avoid future possible deadlock.
A deadlock avoidance algorithm dynamically examines the resources allocation
state to ensure that a circular wait condition never exists. The resource allocation
state is defined by the number of available and allocated resources and the
maximum demand of each process.
Safe State:-
A state is a safe state in which there exists at least one order in which all the
process will run completely without resulting in a deadlock.
A system is in safe state if there exists a safe sequence.
A sequence of processes <P1,P2,………..Pn> is a safe sequence for the current
allocation state if for each Pi the resources that Pi can request can be satisfied by
the currently available resources.
If the resources that Pi requests are not currently available then Pi can obtain all
of its needed resource to complete its designated task.
A safe state is not a deadlock state.
Whenever a process request a resource i.e., currently available, the system must
decide whether resources can be allocated immediately or whether the process
must wait. The request is granted only if the allocation leaves the system in safe
state.
In this, if a process requests a resource i.e., currently available it must still have to
wait. Thus resource utilization may be lower than it would be without a deadlock
avoidance algorithm.
Resource Allocation Graph Algorithm:-
This algorithm is used only if we have one instance of a resource type. In addition
to the request edge and the assignment edge a new edge called claim edge is used.
For eg:- A claim edge PiRj indicates that process Pi may request Rj in future.
The claim edge is represented by a dotted line.
When a process Pi requests the resource Rj, the claim edge is converted to
a request edge.
When resource Rj is released by process Pi, the assignment edge RjPi is
replaced by the claim edge PiRj.
When a process Pi requests resource Rj the request is granted only if converting
the request edge PiRj to as assignment edge RjPi do not result in a cycle.
Cycle detection algorithm is used to detect the cycle. If there are no cycles then
the allocation of the resource to process leave the system in safe state
Banker’s Algorithm:-
This algorithm is applicable to the system with multiple instances of each
resource types, but this is less efficient then the resource allocation graph
algorithm.
When a new process enters the system it must declare the maximum number of
resources that it may need. This number may not exceed the total number of
resources in the system. The system must determine that whether the allocation of
the resources will leave the system in a safe state or not. If it is so resources are
allocated else it should wait until the process release enough resources.
Several data structures are used to implement the banker’s algorithm. Let ‘n’ be
the number of processes in the system and ‘m’ be the number of resources types.
We need the following data structures:-
Available:- A vector of length m indicates the number of available resources. If
Available[i]=k, then k instances of resource type Rj is available.
Max:- An n*m matrix defines the maximum demand of each process if
Max[i,j]=k, then Pi may request at most k instances of resource type Rj.
Allocation:- An n*m matrix defines the number of resources of each type
currently allocated to each process. If Allocation[i,j]=k, then Pi is currently k
instances of resource type Rj.
Need:- An n*m matrix indicates the remaining resources need of each process. If
Need[i,j]=k, then Pi may need k more instances of resource type Rj to compute its
task. So Need[i,j]=Max[i,j]-Allocation[i]
Safety Algorithm:-
This algorithm is used to find out whether or not a system is in safe state
or not.
Step 1. Let work and finish be two vectors of length M and N respectively.
Initialize work = available and
Finish[i]=false for i=1,2,3,…….n
Step 2. Find i such that both
Finish[i]=false
Need i <= work
If no such i exist then go to step 4
Step 3. Work = work + Allocation
Finish[i]=true
Go to step 2
Step 4. If finish[i]=true for all i, then the system is in safe state.
This algorithm may require an order of m*n*n operation to decide
whether a state is safe.
Resource Request Algorithm:-
Let Request(i) be the request vector of process Pi. If Request(i)[j]=k, then process Pi
wants K instances of the resource type Rj. When a request for resources is made by
process Pi the following actions are taken.
If Request(i) <= Need(i) go to step 2 otherwise raise an error condition
since the process has exceeded its maximum claim.
If Request(i) <= Available go to step 3 otherwise Pi must wait. Since the
resources are not available.
If the system want to allocate the requested resources to process Pi then
modify the state as follows.
Available = Available – Request(i)
Allocation(i) = Allocation(i) + Request(i)
Need(i) = Need(i) – Request(i)
If the resulting resource allocation state is safe, the transaction is
complete and Pi is allocated its resources. If the new state is unsafe then
Pi must wait for Request(i) and old resource allocation state is restored.
Deadlock Detection:-
If a system does not employ either deadlock prevention or a deadlock avoidance
algorithm then a deadlock situation may occur. In this environment the system
may provide
An algorithm that examines the state of the system to determine whether a
deadlock has occurred.
An algorithm to recover from the deadlock.
Single Instances of each Resource Type:-
If all the resources have only a single instance then we can define
deadlock detection algorithm that uses a variant of resource allocation
graph called a wait for graph. This graph is obtained by removing the
nodes of type resources and removing appropriate edges.
An edge from Pi to Pj in wait for graph implies that Pi is waiting for Pj to
release a resource that Pi needs.
An edge from Pi to Pj exists in wait for graph if and only if the
corresponding resource allocation graph contains the edges PiRq and
RqPj.
Deadlock exists within the system if and only if there is a cycle. To detect
deadlock the system needs an algorithm that searches for cycle in a graph.
P5
R1 R3 R4
P1 P2 P3
R2 P4 R5
P5
P1 P2 P3
P4
Several Instances of a Resource Types:-
The wait for graph is applicable to only a single instance of a resource type. The
following algorithm applies if there are several instances of a resource type. The
following data structures are used:-
Available:-
o Is a vector of length m indicating the number of available
resources of each type .
Allocation:-
o Is an m*n matrix which defines the number of resources of each
type currently allocated to each process.
Request:-
o Is an m*n matrix indicating the current request of each process. If
request[i,j]=k then Pi is requesting k more instances of resources
type Rj.
Step 1. let work and finish be vectors of length m and n respectively. Initialize
Work = available/expression
For i=0,1,2 ............ n if allocation(i)!=0 then Finish[i]=0
else Finish[i]=true
Step 2. Find an index(i) such that both
Finish[i] = false
Request(i)<=work
If no such I exist go to step 4.
Step 3. Work = work + Allocation(i)
Finish[i] = true
Go to step 2.
Step 4. If Finish[i] = false for some I where m>=i>=1.
When a system is in a deadlock state.
This algorithm needs an order of m*n square operations to detect whether the
system is in deadlock state or not.
Example Problem:-
1. For the following snapshot of the system find the safe sequence (using
Banker’s algorithm).
Process Allocation Max Available
R1 R2 R3 R1 R2 R3 R1 R2 R3
P1 0 1 0 7 5 3 3 3 2
P2 2 0 0 3 2 2
P3 3 0 2 9 0 2
P4 2 1 1 2 2 2
P5 0 0 2 4 3 2
3. The operating system contains three resources. The numbers of instances of each
resource type are (7, 7, 10). The current allocation state is given below.
a. Is the current allocation is safe?
b. find need?
c. Can the request made by the process P1(1,1,0) can be granted?
Process Allocation Max
R1 R2 R3 R1 R2 R3
P1 2 2 3 3 6 8
P2 2 0 3 4 3 3
P3 1 2 4 3 4 4
Address Binding:-
Programs are stored on the secondary storage disks as binary executable files.
When the programs are to be executed they are brought in to the main memory
and placed within a process.
The collection of processes on the disk waiting to enter the main memory forms
the input queue.
One of the processes which are to be executed is fetched from the queue and
placed in the main memory.
During the execution it fetches instruction and data from main memory. After the
process terminates it returns back the memory space.
During execution the process will go through different steps and in each step the
address is represented in different ways.
In source program the address is symbolic.
The compiler converts the symbolic address to re-locatable address.
The loader will convert this re-locatable address to absolute address.
Binding of instructions and data can be done at any step along the way:-
1. Compile time:-
If we know whether the process resides in memory then absolute code can
be generated. If the static address changes then it is necessary to re-
compile the code from the beginning.
2. Load time:-
If the compiler doesn’t know whether the process resides in memory then
it generates the re-locatable code. In this the binding is delayed until the
load time.
3. Execution time:-
If the process is moved during its execution from one memory segment to
another then the binding is delayed until run time. Special hardware is
used for this. Most of the general purpose operating system uses this
method.
Source
Program
Compiler
Or
Assembler
Other
Object
Module
Object
Module
Logical versus physical address:-
The address generated by the CPU is called logical address or virtual address.
The address seen by the memory unit i.e., the one loaded in to the memory
register is called the physical address.
Compile time and load time address binding methods generate some logical
and physical address.
The execution time addressing binding generate different logical and physical
address.
Set of logical address space generated by the programs is the logical address
space.
Set of physical address corresponding to these logical addresses is the
physical address space.
The mapping of virtual address to physical address during run time is done by
the hardware device called memory management unit (MMU).
The base register is also called re-location register.
Value of the re-location register is added to every address generated by the
user process at the time it is sent to memory.
Relocation register
CPU Memory
MMU
The above figure shows that dynamic re-location which implies mapping from
virtual addresses space to physical address space and is performed by the
hardware at run time.
Re-location is performed by the hardware and is invisible to the user dynamic
relocation makes it possible to move a partially executed process from one
area of memory to another without affecting.
Dynamic Loading:-
Advantage:-
Gives better memory utilization.
Unused routine is never loaded.
Do not need special operating system support.
This method is useful when large amount of codes are needed to handle in
frequently occurring cases.
Overlays:-
The size of the process is limited to the size of physical memory. If the size is
more than the size of physical memory then a technique called overlays is used.
The idea is to load only those instructions and data that are needed at any given
time. When other instructions are needed, they are loaded in to memory apace that
was previously occupied by the instructions that are no longer needed.
Eg:-
Consider a 2-pass assembler where pass-1 generates a symbol table and
pass-2 generates a machine code.
Assume that the sizes of components are as follows:
Pass-1 = 70k
Pass-2 = 80k
Symbol table = 20k
Common routine = 30k
To load everything at once, it requires 200k of memory. Suppose if 150k
of memory is available, we can’t run all the components at same time.
Swapping:-
Memory Protection:-
Memory protection means protecting the OS from user process and protecting
process from one another.
Memory protection is provided by using a re-location register, with a limit
register.
Re-location register contains the values of smallest physical address and limit
register contains range of logical addresses. (Re-location = 100040 and limit =
74600).
The logical address must be less than the limit register, the MMU maps the
logical address dynamically by adding the value in re-location register.
When the CPU scheduler selects a process for execution, the dispatcher loads the
re-location and limit register with correct values as a part of context switch.
Since every address generated by the CPU is checked against these register we
can protect the OS and other users programs and data from being modified.
Fragmentation:-
Memory fragmentation can be of two types:-
Internal Fragmentation
External Fragmentation
In Internal Fragmentation there is wasted space internal to a portion due to the
fact that block of data loaded is smaller than the partition.
Eg:- If there is a block of 50kb and if the process requests 40kb and if the block is
allocated to the process then there will be 10kb of memory left.
External Fragmentation exists when there is enough memory space exists to
satisfy the request, but it not contiguous i.e., storage is fragmented in to large
number of small holes.
External Fragmentation may be either minor or a major problem.
One solution for over-coming external fragmentation is compaction. The goal is
to move all the free memory together to form a large block. Compaction is not
possible always. If the re-location is static and is done at load time then
compaction is not possible. Compaction is possible if the re-location is dynamic
and done at execution time.
Another possible solution to the external fragmentation problem is to permit the
logical address space of a process to be non-contiguous, thus allowing the process
to be allocated physical memory whenever the latter is available.
Paging:-
Logical address generated by the CPU is divided in to two parts: page number (p)
and page offset (d).
The page number (p) is used as index to the page table. The page table contains
base address of each page in physical memory. This base address is combined
with the page offset to define the physical memory i.e., sent to the memory unit.
The page size is defined by the hardware. The size of a power of 2, varying
between 512 bytes and 10Mb per page.
If the size of logical address space is 2^m address unit and page size is 2^n, then
high order m-n designates the page number and n low order bits represents page
offset.
Eg:- To show how to map logical memory in to physical memory consider a page size of
4 bytes and physical memory of 32 bytes (8 pages).
a. Logical address 0 is page 0 and offset 0. Page 0 is in frame 5. The logical address
0 maps to physical address 20. [(5*4) + 0].
b. Logical address 3 is page 0 and offset 3 maps to physical address 23 [(5*4) + 3].
c. Logical address 4 is page 1 and offset 0 and page 1 is mapped to frame 6. So
logical address 4 maps to physical address 24 [(6*4) + 0].
d. Logical address 13 is page 3 and offset 1 and page 3 is mapped to frame 2. So
logical address 13 maps to physical address 9 [(2*4) + 1].
The hardware implementation of the page table can be done in several ways:-
1. The simplest method is that the page table is implemented as a set of
dedicated registers. These registers must be built with very high speed logic
for making paging address translation. Every accessed memory must go
through paging map. The use of registers for page table is satisfactory if the
page table is small.
2. If the page table is large then the use of registers is not visible. So the page
table is kept in the main memory and a page table base register [PTBR] points
to the page table. Changing the page table requires only one register which
reduces the context switching type. The problem with this approach is the
time required to access memory location. To access a location [i] first we have
to index the page table using PTBR offset. It gives the frame number which is
combined with the page offset to produce the actual address. Thus we need
two memory accesses for a byte.
3. The only solution is to use special, fast, lookup hardware cache called
translation look aside buffer [TLB] or associative register.
TLB is built with associative register with high speed memory. Each register
contains two paths a key and a value.
When an associative register is presented with an item, it is compared with all the
key values, if found the corresponding value field is return and searching is fast.
TLB is used with the page table as follows:-
TLB contains only few page table entries.
When a logical address is generated by the CPU, its page number along
with the frame number is added to TLB. If the page number is found its
frame memory is used to access the actual memory.
If the page number is not in the TLB (TLB miss) the memory reference to
the page table is made. When the frame number is obtained use can use it
to access the memory.
If the TLB is full of entries the OS must select anyone for replacement.
Each time a new page table is selected the TLB must be flushed [erased]
to ensure that next executing process do not use wrong information.
The percentage of time that a page number is found in the TLB is called
HIT ratio.
Protection:-
Memory protection in paged environment is done by protection
bits that are associated with each frame these bits are kept in page
table.
One bit can define a page to be read-write or read-only.
To find the correct frame number every reference to the memory
should go through page table. At the same time physical address is
computed.
The protection bits can be checked to verify that no writers are
made to read-only page.
Any attempt to write in to read-only page causes a hardware trap to
the OS.
This approach can be used to provide protection to read-only, read-
write or execute-only pages.
One more bit is generally added to each entry in the page table: a
valid-invalid bit.
a. Hierarchical paging:-
Recent computer system support a large logical address apace from 2^32 to 2^64.
In this system the page table becomes large. So it is very difficult to allocate
contiguous main memory for page table. One simple solution to this problem is to
divide page table in to smaller pieces. There are several ways to accomplish this
division.
One way is to use two-level paging algorithm in which the page table itself is also
paged.
Eg:- In a 32 bit machine with page size of 4kb. A logical address is divided in to a page
number consisting of 20 bits and a page offset of 12 bit. The page table is further divided
since the page table is paged, the page number is further divided in to 10 bit page number
and a 10 bit offset. So the logical address is
Hashed page table handles the address space larger than 32 bit. The virtual page
number is used as hashed value. Linked list is used in the hash table which
contains a list of elements that hash to the same location.
Each element in the hash table contains the following three fields:-
Virtual page number
Mapped page frame value
Pointer to the next element in the linked list
Working:-
Virtual page number is taken from virtual address.
Virtual page number is hashed in to hash table.
Virtual page number is compared with the first element of
linked list.
Both the values are matched, that value is (page frame)
used for calculating the physical address.
If not match then entire linked list is searched for matching
virtual page number.
Clustered pages are similar to hash table but one difference
is that each entity in the hash table refer to several pages.
Since the address spaces have grown to 64 bits, the traditional page
tables become a problem. Even with two level page tables. The
table can be too large to handle.
An inverted page table has only entry for each page in memory.
Each entry consisted of virtual address of the page stored in that
read-only location with information about the process that owns
that page.
Each virtual address in the Inverted page table consists of triple
<process-id , page number , offset >.
The inverted page table entry is a pair <process-id , page number>.
When a memory reference is made, the part of virtual address i.e.,
<process-id , page number> is presented in to memory sub-
system.
The inverted page table is searched for a match.
If a match is found at entry I then the physical address <i , offset>
is generated. If no match is found then an illegal address access has
been attempted.
This scheme decreases the amount of memory needed to store each
page table, it increases the amount of time needed to search the
table when a page reference occurs. If the whole table is to be
searched it takes too long.
Advantage:-
Eliminates fragmentation.
Support high degree of multiprogramming.
Increases memory and processor utilization.
Compaction overhead required for the re-locatable partition scheme is also
eliminated.
Disadvantage:-
Page address mapping hardware increases the cost of the computer.
Memory must be used to store the various tables like page tables, memory
map table etc.
Some memory will still be unused if the number of available block is not
sufficient for the address space of the jobs to be run.
Shared Pages:-
Another advantage of paging is the possibility of sharing common code. This is
useful in time-sharing environment.
Eg:- Consider a system with 40 users, each executing a text editor. If the text
editor is of 150k and data space is 50k, we need 8000k for 40 users. If the code is
reentrant it can be shared. Consider the following figure
If the code is reentrant then it never changes during execution. Thus two or more
processes can execute same code at the same time. Each process has its own copy
of registers and the data of two processes will vary.
Only one copy of the editor is kept in physical memory. Each users page table
maps to same physical copy of editor but date pages are mapped to different
frames.
So to support 40 users we need only one copy of editor (150k) plus 40 copies of
50k of data space i.e., only 2150k instead of 8000k.
Segmentation:-
Basic method:-
Most users do not think memory as a linear array of bytes rather
the users thinks memory as a collection of variable sized segments
which are dedicated to a particular use such as code, data, stack,
heap etc.
A logical address is a collection of segments. Each segment has a
name and length. The address specifies both the segment name and
the offset within the segments.
The users specifies address by using two quantities: a segment
name and an offset.
For simplicity the segments are numbered and referred by a
segment number. So the logical address consists of <segment
number, offset>.
Hardware support:-
We must define an implementation to map 2D user defined address
in to 1D physical address.
This mapping is affected by a segment table. Each entry in the
segment table has a segment base and segment limit.
The segment base contains the starting physical address where the
segment resides and limit specifies the length of the segment.
The use of segment table is shown in the above figure:-
Logical address consists of two parts: segment number‘s’
and an offset‘d’ to that segment.
The segment number is used as an index to segment table.
The offset ’d’ must bi in between 0 and limit, if not an error
is reported to OS.
If legal the offset is added to the base to generate the actual
physical address.
The segment table is an array of base limit register pairs.
Advantages:-
Eliminates fragmentation.
Provides virtual growth.
Allows dynamic segment growth.
Assist dynamic linking.
Segmentation is visible.
Virtual memory
Virtual memory is a technique that allows for the execution of partially loaded process.
There are many advantages of this:-
A program will not be limited by the amount of physical memory that is available
user can able to write in to large virtual space.
Since each program takes less amount of physical memory, more than one
program could be run at the same time which can increase the throughput and
CPU utilization.
Less i/o operation is needed to swap or load user program in to memory. So each
user program could run faster.
Virtual memory is the separation of users logical memory from physical memory. This
separation allows an extremely large virtual memory to be provided when these is less
physical memory.
Separating logical memory from physical memory also allows files and memory to be
shared by several different processes through page sharing.
Virtual memory is implemented using Demand Paging.
Demand Paging:-
A demand paging is similar to paging system with swapping when we
want to execute a process we swap the process the in to memory otherwise
it will not be loaded in to memory.
A swapper manipulates the entire processes, where as a pager manipulates
individual pages of the process.
Basic concept:-
Instead of swapping the whole process the pager swaps only the
necessary pages in to memory. Thus it avoids reading unused
pages and decreases the swap time and amount of physical
memory needed.
Hardware support:-
For demand paging the same hardware is required as paging and swapping.
1. Page table:- Has the ability to mark an entry invalid through valid-
invalid bit.
2. Secondary memory:- This holds the pages that are not present in
main memory. It’s a high speed disk.
Performance of demand paging:-
Demand paging can have significant effect on the performance of the computer system.
Let P be the probability of the page fault (0<=P<=1)
Effective access time = (1-P) * ma + P * page fault.
Where P = page fault and ma = memory access time.
Effective access time is directly proportional to page fault rate. It is
important to keep page fault rate low in demand paging.
Demand Paging:
.
o Pages are of same size.
o Pages can’t be shared.
o Page size is fixed.
o Page table keeps track of pages in memory.
o Pages are allocated in memory on demand.
Process creation:-
a. Copy-on-write:-
Demand paging is used when reading a file from disk in to memory. Fork () is used to
create a process and it initially bypass the demand paging using a technique called page
sharing. Page sharing provides rapid speed for process creation and reduces the number
of pages allocated to the newly created process.
Copy-on-write technique initially allows the parent and the child to share the same pages.
These pages are marked as copy-on-write pages i.e., if either process writes to a shared
page, a copy of shared page is created.
Eg:- If a child process try to modify a page containing portions of the stack; the OS
recognizes them as a copy-on-write page and create a copy of this page and maps it on to
the address space of the child process. So the child process will modify its copied page
and not the page belonging to parent.
The new pages are obtained from the pool of free pages.
b. Memory Mapping:-
Standard system calls i.e., open (), read () and write () is used for sequential read of a file.
Virtual memory is used for this. In memory mapping a file allows a part of the virtual
address space to be logically associated with a file. Memory mapping a file is possible by
mapping a disk block to page in memory.
.
Page Replacement
Demand paging shares the I/O by not loading the pages that are never used.
Demand paging also improves the degree of multiprogramming by allowing more
process to run at the some time.
Page replacement policy deals with the solution of pages in memory to be
replaced by a new page that must be brought in. When a user process is executing a
page fault occurs.
The hardware traps to the operating system, which checks the internal table to see
that this is a page fault and not an illegal memory access.
The operating system determines where the derived page is residing on the disk,
and this finds that thee are no free frames on the list of free frames.
When all the frames are in main memory, it is necessary to bring a new page to
satisfy the page fault, replacement policy is concerned with selecting a page currently
in memory to be replaced.
The page i,e to be removed should be the page i,e least likely to be referenced in
future.
Working of Page Replacement Algorithm
The first three references (7,0,1) cases page faults and are brought into the
empty frames.
The next references 2 replaces page 7 because the page 7 was brought in
first.
Since 0 is the next references and 0 is already in memory e has no page
faults.
The next references 3 results in page 0 being replaced so that the next
references to 0 causer page fault.
This will continue till the end of string.
There are 15 faults all together.
Belady’s Anamoly
For some page replacement algorithm, the page fault may increase as the number of
allocated frames increases. FIFO replacement algorithm may face this problem.
Optimal Algorithm
Optimal page replacement algorithm is mainly to solve the problem of
Belady’s Anamoly.
Optimal page replacement algorithm has the lowest page fault rate of
all algorithms.
An optimal page replacement algorithm exists and has been called
OPT.
The working is simple “Replace the page that will not be used for the
longest period of time”
Example: consider the following reference string
The first three references cause faults that fill the three empty frames.
The references to page 2 replaces page 7, because 7 will not be used until
reference 18.
The page 0 will be used at 5 and page 1 at 14.
With only 9 page faults, optimal replacement is much better than a FIFO,
which had 15 faults.
This algorithm is difficult t implement because it requires future knowledge of
reference strings.
Counters: In this we associate each page table entry a time -of -use field, and add to the
cpu a logical clock or counter. The clock is incremented for each memory reference.
When a reference to a page is made, the contents of the clock register are copied to the
time-of-use field in the page table entry for that page.
In this way we have the time of last reference to each page we replace the page with
smallest time value. The time must also be maintained when page tables are changed.
LRU Approximation
An LRU page replacement algorithm should update the page removal status
information after every page reference updating is done by software, cost
increases.
But hardware LRU mechanism tend to degrade execution performance at the
same time, then substantially increases the cost. For this reason, simple and
efficient algorithm that approximation the LRU have been developed. With h/w
support the reference bit was used. A reference bit associate with each memory
block and this bit automatically set to 1 by the h/w whenever the page is
referenced. The single reference bit per clock can be used to approximate LRU
removal.
The page removal s/w periodically resets the reference bit to 0, write the
execution of the users job causes some reference bit to be set to 1.
If the reference bit is 0 then the page has not been referenced since the last time
the reference bit was set to 0.
Allocation of Frames
The allocation policy in a virtual memory controls the operating system decision
regarding the amount of real memory to be allocated to each active process.
In a paging system if more real pages are allocated, it reduces the page fault
frequency and improved turnaround throughput.
If too few pages are allocated to a process its page fault frequency and turnaround
times may deteriorate to unacceptable levels.
The minimum number of frames per process is defined by the architecture, and
the maximum number of frames. This scheme is called equal allocation.
With multiple processes competing for frames, we can classify page replacement
into two broad categories
a) Local Replacement: requires that each process selects frames from only its own
sets of allocated frame.
b). Global Replacement: allows a process to select frame from the set of all frames.
Even if the frame is currently allocated to some other process, one process can take a
frame from another.
In local replacement the number of frames allocated to a process do not change but with
global replacement number of frames allocated to a process do not change global
replacement results in greater system throughput.
Other consideration
There is much other consideration for the selection of a replacement algorithm and
allocation policy.
1) Preparing: This is an attempt to present high level of initial paging. This strategy
is to bring into memory all the pages at one time.
2) TLB Reach: The TLB reach refers to the amount of memory accessible from the
TLB and is simply the no of entries multiplied by page size.
3) Page Size: following parameters are considered
a) page size us always power of 2 (from 512 to 16k)
b) Internal fragmentation is reduced by a small page size.
c) A large page size reduces the number of pages needed.
4) Invented Page table: This will reduces the amount of primary memory i,e. needed
to track virtual to physical address translations.
5) Program Structure: Careful selection of data structure can increases the locality
and hence lowers the page fault rate and the number of pages in working state.
6) Real time Processing: Real time system almost never has virtual memory. Virtual
memory is the antithesis of real time computing, because it can introduce
unexpected long term delay in the execution of a process.
Thrashing
If the number of frames allocated to a low-priority process falls below the
minimum number required by the computer architecture then we suspend the
process execution.
A process is thrashing if it is spending more time in paging than executing.
If the processes do not have enough number of frames, it will quickly page fault.
During this it must replace some page that is not currently in use. Consequently it
quickly faults again and again. The process continues to fault, replacing pages for
which it then faults and brings back. This high paging activity is called thrashing.
The phenomenon of excessively moving pages back and forth b/w memory and
secondary has been called thrashing.
Cause of Thrashing
Thrashing results in severe performance problem.
The operating system monitors the cpu utilization is low. We increase the
degree of multi programming by introducing new process to the system.
A global page replacement algorithm replaces pages with no regards to the
process to which they belong.
The figure shows the thrashing
As the degree of multi programming increases, more slowly until a
maximum is reached. If the degree of multi programming is
increased further thrashing sets in and the cpu utilization drops
sharply.
Locality of Reference:
As the process executes it moves from locality to locality.
A locality is a set of pages that are actively used.
A program may consist of several different localities, which may overlap.
Locality is caused by loops in code that find to reference arrays and other data
structures by indices.
The ordered list of page number accessed by a program is called reference string.
Locality is of two types
1) spatial locality
2) temporal locality
File Attributes:-
File attributes varies from one OS to other. The common file attributes are:
1. Name:- The symbolic file name is the only information kept in
human readable form.
2. Identifier:- The unique tag, usually a number, identifies the file
within the file system. It is the non-readable name for a file.
3. Type:- This information is needed for those systems that supports
different types.
4. Location:- This information is a pointer to a device and to the
location of the file on that device.
5. Size:- The current size of the file and possibly the maximum
allowed size are included in this attribute.
6. Protection:-Access control information determines who can do
reading, writing, execute and so on.
7. Time, data and User Identification:- This information must be kept
for creation, last modification and last use. These data are useful
for protection, security and usage monitoring.
File Operation:-
File is an abstract data type. To define a file we need to consider the operation that can be
performed on the file.
Basic operations of files are:-
1. Creating a file:- Two steps are necessary to create a file. First space in the
file system for file is found. Second an entry for the new file must be made
in the directory. The directory entry records the name of the file and the
location in the file system.
2. Writing a file:- System call is mainly used for writing in to the file.
System call specify the name of the file and the information i.e., to be
written on to the file. Given the name the system search the entire
directory for the file. The system must keep a write pointer to the location
in the file where the next write to be taken place.
3. Reading a file:- To read a file system call is used. It requires the name of
the file and the memory address. Again the directory is searched for the
associated directory and system must maintain a read pointer to the
location in the file where next read is to take place.
4. Delete a file:- System will search for the directory for which file to be
deleted. If entry is found it releases all free space. That free space can be
reused by another file.
5. Truncating the file:- User may want to erase the contents of the file but
keep its attributes. Rather than forcing the user to delete a file and then
recreate it, truncation allows all attributes to remain unchanged except for
file length.
6. Repositioning within a file:- The directory is searched for appropriate
entry and the current file position is set to a given value. Repositioning
within a file does not need to involve actual i/o. The file operation is also
known as file seeks.
In addition to this basis 6 operations the other two operations include appending new
information to the end of the file and renaming the existing file. These primitives can be
combined to perform other two operations.
Most of the file operation involves searching the entire directory for the entry associated
with the file. To avoid this OS keeps a small table containing information about an open
file (the open table). When a file operation is requested, the file is specified via index in
to this table. So searching is not required.
Several piece of information are associated with an open file:-
File pointer:- on systems that does not include offset an a part of
the read and write system calls, the system must track the last read-
write location as current file position pointer. This pointer is
unique to each process operating on a file.
File open count:- As the files are closed, the OS must reuse its
open file table entries, or it could run out of space in the table.
Because multiple processes may open a file, the system must wait
for the last file to close before removing the open file table entry.
The counter tracks the number of copies of open and closes and
reaches zero to last close.
Disk location of the file:- The information needed to locate the file
on the disk is kept in memory to avoid having to read it from the
disk for each operation.
Access rights:- Each process opens a file in an access mode. This
information is stored on per-process table the OS can allow OS
deny subsequent i/o request.
Access Methods:-
The information in the file can be accessed in several ways.
Different file access methods are:-
1. Sequential Access:-
Sequential access is the simplest access method. Information in the file is processed in
order, one record after another. Editors and compilers access the files in this fashion.
Normally read and write operations are done on the files. A read operation reads the next
portion of the file and automatically advances a file pointer, which track next i/I track.
Write operation appends to the end of the file and such a file can be next to the
beginning.
2. Direct Access:-
Direct access allows random access to any file block. This method is based on disk
model of a file.A file is made up of fixed length logical records. It allows the program to
read and write records rapidly in any order.A direct access file allows arbitrary blocks to
be read or written.
Eg:-User may need block 13, then read block 99 then write block 12.
For searching the records in large amount of information with immediate result, the direct
access method is suitable. Not all OS support sequential and direct access. Few OS use
sequential access and some OS uses direct access. It is easy to simulate sequential access
on a direct access but the reverse is extremely inefficient.
Indexing Method:-
The index is like an index at the end of a book which contains
pointers to various blocks.
To find a record in a file, we search the index and then use the
pointer to access the file directly and to find the desired record.
With large files index file itself can be very large to be kept in memory. One solution to
create an index to the index files itself. The primary index file would contain pointer to
secondary index files which would point to the actual data items.
Two types of indexes can be used:-
a. Exhaustive index:- Contain one entry for each of record in the main
file. An index itself is organized as a sequential file.
b. Partial index:- Contains entries to records where the field of interest
exists with records of variable length, soma record will not contain an
fields. When a new record is added to the main file, all index files
must be updated.
Directory Structure:-
The files systems can be very large. Some systems stores millions of files on the disk.
To manage all this data we need to organize them. This organization is done in two
parts:-
1. Disks are split in to one or more partition also known as
minidisks.
2. Each partition contains information about files within it. This
information is kept in entries in a device directory or volume
table of contents.
The device directory or simple directory records information as name, location, size, type
for all files on the partition.
The directory can be viewed as a symbol table that translates the file names in to the
directory entries. The directory itself can be organized in many ways.
When considering a particular directory structure, we need to keep in mind the operations
that are to be performed on a directory.
Search for a file:- Directory structure is searched for finding
particular file in the directory. Files have symbolic name and
similar name may indicate a relationship between files, we may
want to be able to find all the files whose name match a particular
pattern.
Create a file:- New files can be created and added to the directory.
Delete a file:- when a file is no longer needed, we can remove it
from the directory.
List a directory:- We need to be able to list the files in directory
and the contents of the directory entry for each file in the list.
Rename a file:- Name of the file must be changeable when the
contents or use of the file is changed. Renaming allows the
position within the directory structure to be changed.
Traverse the file:- it is always good to keep the backup copy of the
file so that or it can be used when the system gets fail or when the
file system is not in use.
1. Single-level directory:-
This is the simplest directory structure. All the files are contained
in the same directory which is easy to support and understand.
Disadvantage:-
Not suitable for a large number of files and more than one
user.
Because of single directory files, files require unique file
names.
Difficult to remember names of all the files as the number
of files increases.
MS-DOS OS allows only 11 character file name where as UNIX
allows 255 character.
2. Two-level directory:-
A single level directory often leads to the confusion of file
names between different users. The solution here is to create
separate directory or each user.
In two level directories each user has its own directory. It is
called User File Directory (UFD). Each UFD has a similar
structure, but lists only the files of a single user.
When a user job starts or users logs in, the systems Master File
Directory (MFD) is searched. The MFD is indexed by the user
name or account number and each entry points to the UFD for
that user.
When a user refers to a particular file, only his own UFD is
searched. Thus different users may have files with the same
name.
To create a file for a user, OS searches only those users UFD to
as certain whether another file of that name exists.
To delete a file checks in the local UFD so that accidentally
delete another user’s file with the same name.
The file system must be mounted before it can be available to processes on the system
The procedure for mounting the file is:
a. The OS is given the name of the device and the location within the file
structure at which to attach the file system (mount point).A mount
point will be an empty directory at which the mounted file system will
be attached.
Eg:- On UNIX a file system containing users home directory might be mounted as /home
then to access the directory structure within that file system. We must precede the
directory names as /home/jane.
b. Then OS verifies that the device contains this valid file system. OS
uses device drivers for this verification.
c. Finally the OS mounts the file system at the specified mount point.
Disks provide bulk of secondary storage on which the file system is maintained. Disks
have two characteristics:-
a. They can be rewritten in place i.e., it is possible to read a block from
the disk to modify the block and to write back in to same place.
b. They can access any given block of information on the disk. Thus it is
simple to access any file either sequentially or randomly and switching
from one file to another.
The lowest level is the i/o control consisting of device drivers and interrupt handless to
transfer the information between memory and the disk system. The device driver is like a
translator. Its input is a high level command and the o/p consists of low level hardware
specific instructions, which are used by the hardware controllers which interface I/O
device to the rest of the system.
The basic file system needs only to issue generic commands to the appropriate device
drivers to read and write physical blocks on the disk.
The file organization module knows about files and their logical blocks as well as
physical blocks. By knowing the type of file allocation used and the location of the file,
the file organization module can translate logical block address to the physical block
address. Each logical block is numbered 0 to N. Since the physical blocks containing the
data usually do not match the logical numbers, So a translation is needed to locate each
block. The file allocation modules also include free space manager which tracks the
unallocated blocks and provides these blocks when requested.
The logical file system uses the directory structure to provide the file organization
module with the information, given a symbolic file name. The logical file system also
responsible for protection and security.
Logical file system manages metadata information. Metadata includes all the file system
structures excluding the actual data.
The file structure is maintained via file control block (FCB). FCB contains information
about the file including the ownership permission and location of the file contents.
To provide efficient and convenient access to the disks, the OS provides the file system to
allow the data to be stored, located and retrieved.
A file system has two design problems:-
a. How the file system should look to the user.
b. Selecting algorithms and data structures that must be created to map
logical file system on to the physical secondary storage devices.
The file system itself is composed of different levels. Each level uses the feature of the
lower levels to create new features for use by higher levels.
The following structures shows an example of layered design
The lowest level is the i/o control consisting of device drivers and interrupt handless to
transfer the information between memory and the disk system. The device driver is like a
translator. Its input is a high level command and the o/p consists of low level hardware
specific instructions, which are used by the hardware controllers which interface I/O
device to the rest of the system.
The basic file system needs only to issue generic commands to the appropriate device
drivers to read and write physical blocks on the disk.
The file organization module knows about files and their logical blocks as well as
physical blocks. By knowing the type of file allocation used and the location of the file,
the file organization module can translate logical block address to the physical block
address. Each logical block is numbered 0 to N. Since the physical blocks containing the
data usually do not match the logical numbers, So a translation is needed to locate each
block. The file allocation modules also include free space manager which tracks the
unallocated blocks and provides these blocks when requested.
The logical file system uses the directory structure to provide the file organization
module with the information, given a symbolic file name. The logical file system also
responsible for protection and security.
Logical file system manages metadata information. Metadata includes all the file system
structures excluding the actual data.
The file structure is maintained via file control block (FCB). FCB contains information
about the file including the ownership permission and location of the file contents.
File permission
File dates (create, access, write)
File owner, group, Acc
File size
File data blocks
Directory Implementation:-
2. Hash table:-
Hash table decreases the directory search time.
Insertion and deletion are fairly straight forward.
Hash table takes the value computed from that file name.
Then it returns a pointer to the file name in the linear list.
Hash table uses fixed size.
Allocation Methods:-
The space allocation strategy is closely related to the efficiency of the file accessing and
of logical to physical mapping of disk addresses.
A good space allocation strategy must take in to consideration several factors such as:-
1. Processing speed of sequential access to files, random access to files
and allocation and de-allocation of blocks.
2. Disk space utilization.
3. Ability to make multi-user and multi-track transfers.
4. Main memory requirement of a given algorithm.
Three major methods of allocating disk space is used.
1. Contiguous Allocation:-
A single set of blocks is allocated to a file at the time of file
creation. This is a pre-allocation strategy that uses portion of
variable size. The file allocation table needs just a single entry for
each file, showing the starting block and the length of the file.
The figure shows the contiguous allocation method.
If the file is n blocks long and starts at location b, then it occupies blocks b, b+1,
b+2…………….b+n-1. The file allocation table entry for each file indicates the address
of starting block and the length of the area allocated for this file.
Contiguous allocation is the best from the point of view of individual sequential file. It is
easy to retrieve a single block. Multiple blocks can be brought in one at a time to improve
I/O performance for sequential processing. Sequential and direct access can be supported
by contiguous allocation.
Contiguous allocation algorithm suffers from external fragmentation. Depending on the
amount of disk storage the external fragmentation can be a major or minor problem.
Compaction is used to solve the problem of external fragmentation.
The following figure shows the contiguous allocation of space after compaction. The
original disk was then freed completely creating one large contiguous space.
If the file is n blocks long and starts at location b, then it occupies blocks b, b+1,
b+2…………….b+n-1. The file allocation table entry for each file indicates the address
of starting block and the length of the area allocated for this file. Contiguous allocation is
the best from the point of view of individual sequential file. It is easy to retrieve a single
block. Multiple blocks can be brought in one at a time to improve I/O performance for
sequential processing. Sequential and direct access can be supported by contiguous
allocation. Contiguous allocation algorithm suffers from external fragmentation.
Depending on the amount of disk storage the external fragmentation can be a major or
minor problem. Compaction is used to solve the problem of external fragmentation.
The following figure shows the contiguous allocation of space after compaction. The
original disk was then freed completely creating one large contiguous space.
Another problem with contiguous allocation algorithm is pre-allocation, i.e., it is
necessary to declare the size of the file at the time of creation.
Characteristics:-
Supports variable size portion.
Pre-allocation is required.
Requires only single entry for a file.
Allocation frequency is only once.
Advantages:-
Supports variable size problem.
Easy to retrieve single block.
Accessing a file is easy.
It provides good performance.
Disadvantage:-
Pre-allocation is required.
It suffers from external fragmentation.
2. Linked Allocation:-
It solves the problem of contiguous allocation. This allocation is on the
basis of an individual block. Each block contains a pointer to the next
block in the chain.
The disk block can be scattered any where on the disk.
The directory contains a pointer to the first and the last blocks of the
file.
The following figure shows the linked allocation. To create a new file,
simply create a new entry in the directory.
Advantages:-
No external fragmentation.
Compaction is never required.
Pre-allocation is not required.
Disadvantage:-
Files are accessed sequentially.
Space required for pointers.
Reliability is not good.
Cannot support direct access.
3. Indexed Allocation:-
The file allocation table contains a separate one level index for
each file. The index has one entry for each portion allocated to the
file. The i th entry in the index block points to the i th block of the
file.
The following figure shows indexed allocation.
The indexes are not stored as a part of file allocation table rather than the index is kept as
a separate block and the entry in the file allocation table points to that block.
Allocation can be made on either fixed size blocks or variable size blocks. When the file
is created all pointers in the index block are set to nil. When an entry is made a block is
obtained from free space manager.
Allocation by fixed size blocks eliminates external fragmentation where as allocation by
variable size blocks improves locality.
Indexed allocation supports both direct access and sequential access to the file.
Advantages:-
Supports both sequential and direct access.
No external fragmentation.
Faster then other two methods.
Supports fixed size and variable sized blocks.
Disadvantage:-
Suffers from wasted space.
Pointer overhead is generally greater.
Disk Structure:-
1. Seek Time:- Seek time is the time required to move the disk arm to the
required track.
Seek time can be given by Ts = m *n + s.
Where Ts = seek time
n = number of track traversed.
m = constant that depends on the disk drive
s = startup time.
3. Rotational Delay:- Disks other than the floppy disk rotate at 3600 rpm
which is one revolution per 16.7ms.
Disk Scheduling:-
The amount of head movement needed to satisfy a series of i/o request can
affect the performance. If the desired drive and the controller are available the request
can be serviced immediately. If the device or controller is busy any new requests for
service will be placed on the queue of pending requests for that drive when one request is
complete the OS chooses which pending request to service next.
Different types of scheduling algorithms are as follows:-
1. FCFS scheduling algorithm:-
This is the simplest form of disk scheduling algorithm. This
services the request in the order they are received. This algorithm
is fair but do not provide fastest service.
It takes no special time to minimize the overall seek time.
Eg:- consider a disk queue with request for i/o to blocks on
cylinders. 98, 183, 37, 122, 14, 124, 65, 67
If the disk head is initially at 53, it will first move from 53 to 98 then to 183 and then to
37, 122, 14, 124, 65, 67 for a total head movement of 640 cylinders.
The wild swing from 122 to 14 and then back to 124 illustrates the problem with this
schedule.
If the requests for cylinders 37 and 14 could be serviced together before or after 122 and
124 the total head movement could be decreased substantially and performance could be
improved.
3. SCAN algorithm:-
In this the disk arm starts at one end of the disk and moves towards the other end,
servicing the request as it reaches each cylinder until it gets to the other end of the disk.
At the other end, the direction of the head movement is reversed and servicing continues.
Eg:- :- consider a disk queue with request for i/o to blocks on cylinders. 98, 183, 37, 122,
14, 124, 65, 67
If the disk head is initially at 53 and if the head is moving towards 0, it services 37 and
then 14. At cylinder 0 the arm will reverse and will move towards the other end of the
disk servicing 65, 67, 98, 122, 124 and 183.
If a request arrives just in from of head, it will be serviced immediately and the request
just behind the head will have to wait until the arms reach other end and reverses
direction.
The SCAN is also called as elevator algorithm.
4. C-SCAN (Circular scan) algorithm:-
C-SCAN is a variant of SCAN designed to provide a more uniform wait time. Like
SCAN, C-SCAN moves the head from end of the disk to the other servicing the request
along the way. When the head reaches the other end, it immediately returns to the
beginning of the disk, without servicing any request on the return.
The C-SCAN treats the cylinders as circular list that wraps around from the final cylinder
to the first one.
Eg:-
Both SCAN and C-SCAN move the disk arm across the full width
of the disk. In practice neither of the algorithms is implemented in
this way.
The arm goes only as far as the final request in each direction.
Then it reverses, without going all the way to the end of the disk.
These versions of SCAN and C-SCAN are called Look and C-
Look scheduling because they look for a request before continuing
to move in a given direction.
Eg:-
Selection of Disk Scheduling Algorithm:-