OS_PPT_pragmming
OS_PPT_pragmming
ØDefinition of OS
ØComponents of Computer System
ØMainframe Systems
ØComputer System operation
ØSingle and Multi processor System
ØComponents of Operating System
1
Lecture 1 BITS Pilani, Pilani Campus
OPERATING SYSTEM -
DEFINITION
An operating system is a program that manages a computer’s
hardware. It also provides a basis for application programs and
acts as an intermediary between the computer user and the
computer hardware. An amazing aspect of operating systems
is how they vary in accomplishing these tasks. Mainframe
operating systems are designed primarily to optimize
utilization of hardware. Personal computer (PC) operating
systems support complex games, business applications, and
everything in between. Operating systems for mobile
Computers provide an environment in which a user can easily
interface with the computer to execute programs. Thus, some
operating systems are designed to be convenient, others to be
efficient, and others to be some combination of the two. 2
Lecture I BITS Pilani, Pilani Campus
Components of Computer
System
Before we can explore the details of computer system
operation, we need to know something about system structure.
We thus discuss the basic functions of system startup, I/O, and
storage early in this chapter. We also describe the basic
computer architecture that makes it possible to write a
functional operating system. Because an operating system is
large and complex, it must be created piece by piece. Each of
these pieces should be a well-delineated portion of the
system, with carefully defined inputs, outputs, and functions
A computer system has four components. They are
1. Hardware 3. Users
2. Application Programs 4. Operating System
3
Lecture I BITS Pilani, Pilani Campus
Components of Computer
System
Operating System
Computer Hardware
4
Lecture I BITS Pilani, Pilani Campus
Components of OS
5
Lecture I BITS Pilani, Pilani Campus
Components of Computer
System
The view of the computer varies from users accordingly to the
interface provided to them. Most of the users sit in front of the
computer and execute the programs with the help of
keyboard, mouse , System unit and Monitor. In some cases,
users are provided with the GUI [ Graphical User Interface ]
feature to perform their tasks easily.
6
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
7
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
Operating
System
User Program
area
executed and were kept in the job pool. The operating system
picks and executed one of the jobs in the memory . When a
job waits for some task such waiting for an input, the operating
system switches to other job. If this job needs some wait, the
CPU is switched to another job, and so on. As long as one job
needs to be executed, the CPU is never idle.
If many jobs are waiting for the execution and are ready to be
brought into memory for the execution, the operating system
chooses one among them. This decision is called as Job
Scheduling.
10
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
Linux, MacOs)
5. Distributed Systems
These are the systems that can distribute the computation
among several physical processors.
They are loosely coupled systems. Each processor has its own
local memory and processors communicate with one another
through various communication lines such as high speed
buses or telephone lines. The advantages are
- Resource Sharing
- Computation speed up
- Reliability
- Communication
12
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
(i) Client Server Model
Client-server architecture is a network model where every
process or computer on a network is a server or a client. The
client-servers are the robust computers that are dedicated to
managing the printers, disk drives, and network traffic. Clients
are workstations or PCs on which the users run their
applications. Clients mainly rely on the servers for resources,
like devices, files, and processing power.
A client-server architecture or model is an application network
separating tasks between the clients and servers that live in
the same system or have to communicate through a computer
network.
13
Lecture I BITS Pilani, Pilani Campus
OPERATING SYSTEM
14
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
(ii) Peer – to - Peer Model
A peer-to-peer (P2P) service is a decentralized platform
whereby two individuals interact directly with each other,
without intermediation by a third party. Instead, the buyer and
the seller transact directly with each other via the P2P service.
Benefits
- A peer-to-peer service is a platform that directly connects
parties to a transaction without the third-party intermediary.
- Peer-to-peer platforms offer services such as payment
processing, information about buyers and sellers, and quality
assurance to their users.
15
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
16
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
6.Clustering systems
These are the systems supporting clustering. Clustering allows
two or more systems to share storage. They are either
Asymmetric Clustering or Symmetric Clustering.
In symmetric clustering, all ‘n’ hosts are running the
Application. In asymmetric clustering, all servers run the
application and one server acts as a stand by
Advantages
- High performance
- Fault tolerant because failure one node does not affect the
whole system
- Scalability is achieved because we can add new nodes
17
Lecture I BITS Pilani, Pilani Campus
MAINFRAME SYSTEMS
19
Lecture I BITS Pilani, Pilani Campus
Computer System operation
20
Lecture I BITS Pilani, Pilani Campus
Computer System operation
21
Lecture I BITS Pilani, Pilani Campus
Computer System operation
22
Lecture I BITS Pilani, Pilani Campus
Computer System operation
Cache
Mai Memory
Solid Disk
Magnetic disk
Optical disk
Magnetic tape
29
Lecture 1 BITS Pilani, Pilani Campus
Computer System operation
30
Lecture I BITS Pilani, Pilani Campus
Computer System operation
31
Lecture I BITS Pilani, Pilani Campus
Single and Multi processor
Systems
A computer system can be organized in a number of different
ways, which we can categorize roughly according to the
number of general-purpose processors used.
Single-Processor Systems
Until recently, most computer systems used a single processor.
On a single- processor system, there is one main CPU capable
of executing a general-purpose instruction set, including
instructions from user processes. Almost all single- processor
systems have other special-purpose processors as well. They
may come in the form of device-specific processors, such as
disk, keyboard, and graphics controllers; or, on mainframes,
they may come in the form of more general-purpose
32
Lecture I BITS Pilani, Pilani Campus
Single and Multi processor
Systems
processors, such as I/O processors that move data rapidly
among the components of the system.
Multiprocessor Systems
Within the past several years, multiprocessor systems (also
known as parallel systems or multicore systems) have
begun to dominate the landscape of computing. Such systems
have two or more processors in close communication, sharing
the computer bus and sometimes the clock, memory, and
peripheral devices. Multiprocessor systems first appeared
prominently appeared in servers and have since migrated to
desktop and laptop systems. Recently, multiple processors
have appeared on mobile devices such as smartphones and
33
Lecture I BITS Pilani, Pilani Campus
Single and Multi processor
Systems
tablet computers.
Multiprocessor systems have three main advantages:
Increased throughput. By increasing the number of
processors, we expect to get more work done in less time. The
speed-up ratio with N processors is not N, however; rather, it is
less than N. When multiple processors cooperate on a task, a
certain amount of overhead is incurred in keeping all the parts
working correctly. This overhead, plus contention for shared
resources, lowers the expected gain from additional
processors. Similarly, N programmers working closely
together do not produce N times the amount of work a single
programmer would produce.
34
Lecture I BITS Pilani, Pilani Campus
Computer System
Architecture
-Economy of scale. Multiprocessor systems can cost less than
equivalent multiple single-processor systems, because they
can share peripherals, mass storage, and power supplies. If
several programs operate on the same set of data, it is cheaper
to store those data on one disk and to have all the processors
share them than to have many computers with local disks and
many copies of the data.
Increased reliability. If functions can be distributed properly
among several processors, then the failure of one processor
will not halt the system, only slow it down. If we have ten
processors and one fails, then each of the remaining nine
processors can pick up a share of the work of the failed
processor. 35
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
An Operating System (OS) is an interface between a computer
user and computer hardware. An operating system is a
software which performs all the basic tasks like file
management, memory management, process management,
handling input and output, and controlling peripheral devices
such as disk drives and printers.
Some popular Operating Systems include Linux Operating
System, Windows OS, VMS, OS/400, AIX, z/OS, etc.
Definition
An operating system is a software that acts as an interface
between the user and the computer hardware and controls the
execution of all kinds of programs.
36
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
Following are some of important functions of an operating
System.
• Memory Management
• Processor Management
• Device Management
• File Management
• Security
• Control over system performance
• Job accounting
• Error detecting aids
• Coordination between other software and users
37
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
Memory Management
Memory management refers to management of Primary
Memory or Main Memory. Main memory is a large array of
words or bytes where each word or byte has its own address.
Main memory provides a fast storage that can be accessed
directly by the CPU. For a program to be executed, it must in
the main memory. An Operating System does the following
activities for memory management −
• Keeps tracks of primary memory, i.e., what part of it are in use
by whom, what part are not in use.
• In multiprogramming, the OS decides which process will get
memory when and how much.
38
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
• Allocates the memory when a process requests it to do so.
• De-allocates the memory when a process no longer needs it
or has been terminated.
Processor Management
In multiprogramming environment, the OS decides which
process gets the processor when and for how much time. This
function is called process scheduling. An Operating System
does the following activities for processor management −
• Keeps tracks of processor and status of process. The
program responsible for this task is known as traffic
controller.
• Allocates the processor (CPU) to a process.
39
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
• De-allocates processor when a process is no longer required.
Device Management
An Operating System manages device communication via their
respective drivers. It does the following activities for device
management −
• Keeps tracks of all devices. Program responsible for this task
is known as the I/O controller.
• Decides which process gets the device when and for how
much time.
• Allocates the device in the efficient way.
• De-allocates devices.
40
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
File Management
A file system is normally organized into directories for easy
navigation and usage. These directories may contain files and
other directions.
An Operating System does the following activities for file
management −
• Keeps track of information, location, uses, status etc. The
collective facilities are often known as file system.
• Decides who gets the resources.
• Allocates the resources.
• De-allocates the resources.
41
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
Other Important Activities
Following are some of the important activities that an
Operating System performs −
Security − By means of password and similar other
techniques, it prevents unauthorized access to programs and
data.
Control over system performance − Recording delays
between request for a service and response from the system.
Job accounting − Keeping track of time and resources used by
various jobs and users.
Error detecting aids − Production of dumps, traces, error
messages, and other debugging and error detecting aids.
42
Lecture I BITS Pilani, Pilani Campus
Components of Operating
System
Coordination between other softwares and users −
Coordination and assignment of compilers, interpreters,
assemblers and other software to the various users of the
computer systems.
43
Lecture I BITS Pilani, Pilani Campus
Learning Objectives
44
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
An operating system provides an environment for the
execution of programs. It provides certain services to
programs and to the users of those programs. The specific
services provided, of course, differ from one operating system
to another, but we can identify common classes. These
operating system services are provided for the convenience of
the programmer, to make the programming task easier.
The following Figure shows one view of the various operating-
system services and how they interrelate.
45
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
User and other system programs
SYSTEM CALLS
OPERATING SYSTEM
Hardware
46
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
One set of operating system services provides functions that
are helpful to the user.
• User interface. Almost all operating systems have a user
interface (UI). This interface can take several forms. One is a
command-line interface (CLI), which uses text commands
and a method for entering them (say, a keyboard for typing in
commands in a specific format with specific options). Another
is a batch interface, in which commands and directives to
control those commands are entered into files, and those files
are executed. Most commonly, a graphical user interface
(GUI) is used.
47
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
• Program execution. The system must be able to load a
program into memory and to run that program. The program
must be able to end its execution, either normally or
abnormally (indicating error).
• I/O operations.A running program may require I/O, which
may involve a file or an I/O device. For specific devices,
Special functions may be desired (such as recording to a CD
Or DVD drive or blanking a display screen). For efficiency and
protection, users usually cannot control I/O devices directly.
Therefore, the operating system must provide a means to do
I/O
48
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
• File-system manipulation. The file system is of particular
interest. Obviously, programs need to read and write files and
directories. They also need to create and delete them by name,
search for a given file, and list file information. Finally, some
operating systems include permissions management to allow
or deny access to files or directories based on file ownership.
Many operating systems provide a variety of file systems,
sometimes to allow personal choice and sometimes to provide
specific features or performance characteristics.
49
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
• Communications. There are many circumstances in which
one process needs to exchange information with another
process. Such communication may occur between processes
that are executing on the same computer or between
processes that are executing on different computer systems
tied together by a computer network
Error detection. The operating system needs to be detecting
and correcting errors constantly. Errors may occur in the CPU
and memory hardware (such as a memory error or a power
failure), in I/O devices (such as a parity error on disk, a
connection failure on a network, or lack of paper in the
printer), and in the user program (such as an arithmetic
50
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
overflow, an attempt to access an illegal memory location, or a
too-great use of CPU time). For each type of error, the
operating system should take the appropriate action to ensure
correct and consistent computing.
Another set of operating system functions exists not for
helping the user but rather for ensuring the efficient operation
of the system itself. Systems with multiple users can gain
efficiency by sharing the computer resources among the
users.
• Resource allocation. When there are multiple users or
multiple jobs running at the same time, resources must be
allocated to each of them.
51
Lecture - 2 BITS Pilani, Pilani Campus
OPERATING SYSTEM
SERVICES
• Accounting. We want to keep track of which users use how
much and what kinds of computer resources. This record
keeping may be used for accounting (so that users can be
billed) or simply for accumulating usage statistics. Usage
statistics may be a valuable tool for researchers who wish to
reconfigure the system to improve computing services.
• Protection and security. The owners of information stored
in a multiuser or networked computer system may want to
control use of that information. Security starts with requiring
each user to authenticate himself or herself to the system,
usually by means of a password, to gain access to system
resources.
52
Lecture - 2 BITS Pilani, Pilani Campus
SYSTEM CALLS
Functions:
- Request and Release device
- Get and Set device attribute
4.In Information Maintenance
The system call handles information and its transfer between
the user and the OS
Functions:
Get the time or setting the time
Get the process and device attributes
5. Communication
The system call is used for inter-process communication
55
Lecture - 2 BITS Pilani, Pilani Campus
SYSTEM CALLS
Functions:
Create and delete communication
Sending and receiving message
Attach and detach remote services
The following are the example for System calls in Windows
and Unix OS
Windows Unix
Process CreateProcess() fork()
Control ExitProcess() exit()
File CreateFile() open()
Manipulation ReadFile() read()
WriteFile() write()
56
Lecture - 2 BITS Pilani, Pilani Campus
SYSTEM CALLS
CloseHandle() close()
Device SetConsoleMode() ioctl()
Manipulation ReadConsole() read()
WriteConsole() write()
57
Lecture - 2 BITS Pilani, Pilani Campus
SYSTEM CALLS
58
Lecture - 2 BITS Pilani, Pilani Campus
Learning Objectives
Ø What is a process?
Ø States of a process
Ø Process Control Block
ØProcess Scheduling – Basics
- Process Scheduling queues
- Two process model
- Scheduler and its types
Ø Context Switching
59
Lecture - III BITS Pilani, Pilani Campus
PROCESS CONCEPT
Process Concept
Early computers had complete control over the execution of
programs because they allowed only one program to execute.
But current day computer systems permit multiple programs to
be loaded into the memory and to be executed concurrently. It
requires firmer control which resulted in the notion of a
Process.
A process is a program in execution. A process is not only the
program but it is also includes the program counter, Stack and
a data section.
• Program Counter – It specifies the next instruction to be
executed
60
Lecture - III BITS Pilani, Pilani Campus
PROCESS CONCEPT
• Stack – It is used to store temporary data such as local
variables, parameters and return address
• Data Section – It contains the global variables
States of a Process
As process executes, its state changes. The state of a process
represents the part by which the current activity of that
process. Each process may be in any of the following states:
(i) New
(ii) Running
(iii) Waiting
(iv) Ready
(v) Terminated
61
Lecture - III BITS Pilani, Pilani Campus
PROCESS CONCEPT
• New State – The process is being created
• Running State – Instructions of the process are being
executed
• Waiting State – The running process is waiting for some event
to occur
• Ready State – The process is waiting to be assigned to a
processor
• Terminated state – The process had finished its execution.
62
Lecture - III BITS Pilani, Pilani Campus
States of a PROCESS
new terminated
ready running
Schedule
63
Lecture - III BITS Pilani, Pilani Campus
PROCESS CONCEPT
Process Control Block
Each process is represented in the operating system by a
process control block (PCB). The process control block is also
called as a task control block. It contains many pieces of
information associated with specified process.
Process state – The state may be new, ready, wait, running,
waiting, and so on.,
Program Counter – It indicates the address of the next
instruction to be executed for the running process
CPU registers – They include accumulators , index registers ,
Stack pointers, general – purpose registers and condition –
code information. It is used to save information when an
interrupt occurs. 64
Lecture - III BITS Pilani, Pilani Campus
PROCESS CONTROL BLOCK
Process Number
Program Counter
Registers
Memory Limits
66
Lecture - III BITS Pilani, Pilani Campus
PROCESS SCHEDULING
Process Scheduling
The process scheduling is the activity of the process manages
that handles the removal of running process from the CPU and
the selection of another process on the basis of a strategy.
Process Scheduling is an essential part of multi programming
OS.
Process Scheduling Queue
The OS maintains all the PCB’s in process scheduling queues.
The operating system maintains a separate queue of each
process states and PCB’s of all processes in the same
execution state are placed in the queue. When the state of the
process is changed, its PCB is unlinked from its current queue
and moved to its new state queue. 67
Lecture - III BITS Pilani, Pilani Campus
PROCESS SCHEDULING
QUEUES
The OS maintains the following important process scheduling
queues:
Job queue – This queue keeps all the process in the system
Ready queue – This queue keeps a set of all processes
residing in main memory that are ready and waiting to
execute. A new process is always put in this queue.
Device queue – The process which are blocked due to
unavailability of an I/O device constitute this queue.
The operating system uses different policies to manage each
queue. The OS scheduler determines how to move processes
between the ready and run queues which can only have one
entry per processor core on the system.
68
Lecture - III BITS Pilani, Pilani Campus
PROCESS SCHEDULING
QUEUES
1 2
5
child executes fork a child
6
interrupt occurs waits for an
interrupt
69
Lecture - III BITS Pilani, Pilani Campus
PROCESS SCHEDULING
Two Process Model
Two process models refers to running and non – running states
as
• Running – When a new process is created , it enters into the
system as in the running state
• Not Running – Processes that are not running are kept in
the queue, waiting for their turn to execute. Each entry in the
queue is a pointer to a particular process. Queue is
implemented in linked list structure.
When a process is interrupted, the process is transferred in
the waiting queue. If the process has completed or aborted,
the process is discarded. In either case, the component
dispatcher selects a process from the queue to execute. 70
Lecture - III BITS Pilani, Pilani Campus
PROCESS SCHEDULING
Scheduler
Scheduler is a special system software which handles process
scheduling in various ways. Their main task is to select the
jobs to be submitted into the system and to decide which
process to run. There are three types of schedulers. They are
(i) Long term Scheduler
(ii) Short term Scheduler
(iii) Medium time scheduler
Long Time Scheduler – It is also called as job scheduler or
high level scheduler. A long term scheduler determines which
processes are admitted to the system for processing. It selects
the processes from the queue and load them into the memory
for execution. The primary objective of the job scheduler is 71
Lecture - III BITS Pilani, Pilani Campus
PROCESS SCHEDULING
to provide a balanced mix of jobs, such as I/O bound and
processor bound
Short term Scheduler – It is also called as CPU scheduler. Its
main objective is to increase system performance in
accordance with some criteria. Short term schedulers are also
known as dispatchers , makes the decision of which process to
execute. Short term schedulers are faster than long – term
scheduler.
Medium Scheduler – Medium schedule is part of swapping. It
removes the processes from the memory. It reduces the
degree of multi programming. The medium term scheduler is
in charge of handling swapped – out processes.
72
Lecture - III BITS Pilani, Pilani Campus
PROCESS SCHEDULING
A running process may become suspended if it makes an I/O
request. A suspended process can not make any progress
towards completion. The suspended process is moved to the
secondary storage. This process is called swapping. The
process is said to be swapped out or rolled out.
Comparison between Schedulers
Long term Short term Medium Term
Job Scheduler CPU scheduler Process swapping scheduler
Selects process from pool Selects processes which Reintroduce the process
and loads into memory are ready execute into memory and execution
is continued.
73
Lecture - III BITS Pilani, Pilani Campus
CONTEXT SWITCHING
Context Switching
It is the mechanism to store and restore or context of CPU in
process control block so that process execution can be
resumed for the same point at a later time. Using this
technique, a context switch controls multiples processes to
share a single CPU. Context Switching is an essential part of
multi tasking operating system features.
When the scheduler switches the CPU from executing one
process to execute another process , the state from the current
running process is stored into the PCB. After this, the ready
state e process is allowed to execute / run. It is loaded into the
memory from its PCB, set the program counter and register.
74
Lecture - III BITS Pilani, Pilani Campus
CONTEXT SWITCHING
75
Lecture - III BITS Pilani, Pilani Campus
CONTEXT SWITCHING
In the above figure, you can see that initially, the process P1 is
in the running state and the process P2 is in the ready state.
Now, when some interruption occurs then you have to switch
the process P1 from running to the ready state after saving the
context and the process P2 from ready to running state. The
following steps will be performed:
1. Firstly, the context of the process P1 i.e. the process present
in the running state will be saved in the Process Control Block
of process P1 i.e. PCB1.
2. Now, you have to move the PCB1 to the relevant queue i.e.
ready queue, I/O queue, waiting queue, etc.
3. From the ready state, select the new process that is to be
executed i.e. the process P2. 76
Lecture - III BITS Pilani, Pilani Campus
CONTEXT SWITCHING
4. Now, update the Process Control Block of process P2 i.e.
PCB2 by setting the process state to running. If the process P2
was earlier executed by the CPU, then you can get the position
of last executed instruction so that you can resume the
execution of P2.
5. Similarly, if we want to execute the process P1 again, then
we have to follow the same steps as mentioned above(from
step 1 to 4).
77
Lecture - III BITS Pilani, Pilani Campus
Learning Objectives
78
Lecture - IV BITS Pilani, Pilani Campus
PROCESS CONCEPT
Processes executing concurrently in the operating system may
be either independent processes or coordinating processes.
Independent Processes – They can not affect or be affected
by other processes executing in the system
Coordinating Processes – They can affect or can affected by
other processes executing in the system.
Any process that shares data with other processes is a
coordinating process
There are several reasons for providing an environment that
allows process coordination
1. Information Sharing – Several processes want to share the
information
79
Lecture - IV BITS Pilani, Pilani Campus
PROCESS CONCEPT
2. Modularity – The complex problem can broken down into
several tasks. Each task is the process. The process of breaking
the system into multiple modules is called as Modularity.
There are various advantages of modularity. Some of them are
- Debugging is easy
- Work load can be shared
- Reducing the cost
3. Computation Speed – Concurrent execution of multiple
parts of a program reduces the time and computation speed is
maximized.
4. Convenience – If we allow the processes to cooperate with
each other , it will be convenient to the user to multi tasking
80
Lecture - IV BITS Pilani, Pilani Campus
PROCESS CONCEPT
Cooperating processes require an inter process
communication (IPC) mechanism that will allow them to
exchange data and information between them.
There are two fundamental models inter process communication
are
1. Shared memory
2. Message Passing
Shared Memory
In the shared memory model, a region of memory that is
shared by coordinating processes is established.
Processes can then exchange information by reading and
writing data to the shared region.
The following picture represents is 81
Lecture - IV BITS Pilani, Pilani Campus
PROCESS CONCEPT
Process A
Writing
Shared Memory
Process B Reading
Kernel
Process A M
Process B M
Kernel M
83
Lecture - IV BITS Pilani, Pilani Campus
PROCESS CONCEPT
The other inter process communication are
(i) Pipe
(ii) Socket
(iii) File
Kernel
Kernel is the essential part of the operating system. It
provides basic services for all other parts of the operating
system. It is the main layer between operating system and the
Hardware and it helps with process and memory management,
file system, device control and networking
84
Lecture - IV BITS Pilani, Pilani Campus
THREAD
A thread is a basic unit of CPU utilization; it comprises a thread
ID, a program counter, a register set, and a stack. It shares with
other threads belonging to the same process its code section,
data section, and other operating-system resources, such as
open files and signals. A traditional (or heavyweight) process
has a single thread of control. If a process has multiple threads
of control, it can perform more than one task at a time.
The following figure illustrates the difference between a
traditional single- threaded process and a multithreaded
process.
Most software applications that run on modern computers are
multithreaded. An application typically is implemented as a
separate process with several threads of control. 85
Lecture - IV BITS Pilani, Pilani Campus
THREAD
Stack Stack
Stack
Thread
Thread
86
Single thread process Multiple
Lecture - IV thread process
BITS Pilani, Pilani Campus
THREAD
A web browser might have one thread display images or text
while another thread retrieves data from the network, for
example. A word processor may have a thread for displaying
graphics, another thread for responding to keystrokes from the
user, and a third thread for performing spelling and grammar
checking in the background. In certain situations, a single
application may be required to perform several similar tasks.
For example, a web server accepts client requests for web
pages, images, sound, and so forth. A busy web server may
have several (perhaps thousands of) clients concurrently
accessing it. If the web server ran as a traditional single-
threaded process, it would be able to service only one client at
a time, and a client might have to wait a very long time for 87
Lecture - IV BITS Pilani, Pilani Campus
THREAD
its request to be serviced.
One solution is to have the server run as a single process that
accepts requests. When the server receives a request, it
creates a separate process to service that request. In fact, this
process-creation method was in common use before threads
became popular. Process creation is time consuming and
resource intensive, however. If the new process will perform
the same tasks as the existing process, why incur all that
overhead? It is generally more efficient to use one process that
contains multiple threads. If the web-server process is
multithreaded, the server will create a separate thread that
listens for client requests. When a request is made, rather than
creating another process, the server creates a new thread to 88
Lecture - IV BITS Pilani, Pilani Campus
THREAD
service the request and resume listening for additional
requests. It is illustrated in the following diagram:
92
Lecture - IV BITS Pilani, Pilani Campus
THREAD
Multithreading Models
Support for threads may be provided either at the user level,
for user threads, or by the kernel, for kernel threads. User
threads are supported above the kernel and are managed
without kernel support, whereas kernel threads are supported
and managed directly by the operating system. Virtually all
contemporary operating systems— including Windows, Linux,
Mac OS X, and Solaris— support kernel threads.
Ultimately, a relationship must exist between user threads and
kernel threads. In this section, we look at three common ways
of establishing such a relationship: the many-to-one model, the
one-to-one model, and the many-to- many model.
93
Lecture - IV BITS Pilani, Pilani Campus
THREAD
Many – to – One Model
The many-to-one model (See the figure ) maps many user-
level threads to one kernel thread. Thread management is
done by the thread library in user space, so it is efficient.
However, the entire process will block if a thread makes a
blocking system call.
Also, because only one thread can access the kernel at a time,
multiple threads are unable to run in parallel on multicore
systems. Green threads — a thread library available for
Solaris systems and adopted in early versions of Java— used
the many-to-one model. However, very few systems continue
to use the model because of its inability to take advantage of
multiple processing cores. 94
Lecture - IV BITS Pilani, Pilani Campus
THREAD – Many –to - One
Model
User Thread
K Kernel Thread
95
BITS Pilani, Pilani Campus
THREAD – One – to One
Model
One – to – One Model
The one-to-one model (See the Figure ) maps each user thread
to a kernel thread. It provides more concurrency than the
many-to-one model by allowing another thread to run when a
thread makes a blocking system call. It also allows multiple
threads to run in parallel on multiprocessors. The only
drawback to this model is that creating a user thread requires
creating the corresponding kernel thread. Because the
overhead of creating kernel threads can burden the
performance of an application, most implementations of this
model restrict the number of threads supported by the system.
Linux, along with the family of Windows operating systems,
implement the one-to-one model. 96
Lecture - IV BITS Pilani, Pilani Campus
THREAD
User Thread
K K K K Kernel Thread
97
Lecture - IV BITS Pilani, Pilani Campus
THREAD
Many-to-Many Model
The many-to-many model (See the Figure ) multiplexes many
user-level threads to a smaller or equal number of kernel
threads. The number of kernel threads may be specific to
either a particular application or a particular machine (an
application may be allocated more kernel threads on a
multiprocessor than on a single processor).
Let’s consider the effect of this design on concurrency.
Whereas the many- to-one model allows the developer to
create as many user threads as she wishes, it does not result in
true concurrency, because the kernel can schedule only one
thread at a time. The one-to-one model allows greater
concurrency, but the developer has to be careful not to create 98
Lecture - IV BITS Pilani, Pilani Campus
THREAD
too many threads within an application (and in some instances
may be limited in the number of threads she can
create). The many-to-many model suffers from neither of these
shortcomings: developers can create as many user threads as
necessary, and the corresponding kernel threads can run in
parallel on a multiprocessor. Also, when a thread performs a
blocking system call, the kernel can schedule another thread
for execution.
99
Lecture - IV BITS Pilani, Pilani Campus
THREAD – Many – to – Many
Model
User
Thread
K K K Kernel
Thread
100
Lecture - IV BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus
Learning Objectives
Ø CPU Scheduling
- What is Process Scheduling?
Ø Types of Scheduling algorithms
Ø Various Methods of Process Scheduling
- First Come First Served
- Shortest Job Next
- Priority Scheduling
- Round Robin Scheduling
- Multiple Queue Scheduling
102
Lecture - V BITS Pilani, Pilani Campus
THREAD LIBARARIES
Thread libraries are the APIs to be used for creating ,
executing and terminating the threads.
There are two types of threads. They are
1. PTHREAD (POSIX)
2. Java Threads
PTHREAD
It is an API to create and run a thread. The API is written in C
language.
The following is the code written for finding the sum of first ‘n’
numbers.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
103
Lecture - V BITS Pilani, Pilani Campus
THREAD LIBARARIES
int sum=0;
void *run(void *p);
int main(int ac,char *argv[])
{
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid,&attr,run,argv[1]);
pthread_join(tid,NULL);
printf("\n Summation is %d",sum);
return 0;
}
104
Lecture - V BITS Pilani, Pilani Campus
THREAD LIBARARIES
void *run(void *p)
{
int i,up=atoi(p);
for(i=1;i<=up;i++)sum+=i;
pthread_exit(0);
}
Java Thread libraries have lot of built –in- methods for
managing the threads. The important thread methods are:
Start() – Making the thread to be ready
Run() – Execute the thread
105
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
CPU Scheduling is a process of determining which process will own
CPU for execution while another process is on hold. The main task of
CPU scheduling is to make sure that whenever the CPU remains idle,
the OS at least select one of the processes available in the ready
queue for execution. The selection process will be carried out by the
CPU scheduler. It selects one of the processes in memory that are
ready for execution.
Types of CPU Scheduling
Here are two kinds of Scheduling methods:
106
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Preemptive Scheduling
In Preemptive Scheduling, the tasks are mostly assigned with their
priorities. Sometimes it is important to run a task with a higher
priority before another lower priority task, even if the lower priority
task is still running. The lower priority task holds for some time and
resumes when the higher priority task finishes its execution.
Non-Preemptive Scheduling
In this type of scheduling method, the CPU has been allocated to a
specific process. The process that keeps the CPU busy will release
the CPU either by switching context or terminating. It is the only
method that can be used for various hardware platforms. That’s
because it doesn’t need special hardware (for example, a timer) like
preemptive scheduling.
107
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
When scheduling is Preemptive or Non-Preemptive?
To determine if scheduling is preemptive or non-preemptive,
consider these four parameters:
• A process switches from the running to the waiting state.
• Specific process switches from the running state to the ready state.
• Specific process switches from the waiting state to the ready state.
• Process finished its execution and terminated.
Only conditions 1 and 4 apply, the scheduling is called non-
preemptive.
All other scheduling are preemptive.
Important CPU scheduling Terminologies
Burst Time/Execution Time: It is a time required by the process to
complete execution. It is also called running time.
108
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Arrival Time(AT): when a process enters in a ready state
Completion Time (CT): It is the finishing or completion time of the
process in the system
Turnaround Time (TA): It is the time difference between
Completion Time and Arrival Time
TA = CT - AT
Waiting Time (WT): It is the time difference between Turnaround
Time and Burst Time
WT = TA - BT
CPU Scheduling Criteria
A CPU scheduling algorithm tries to maximize and minimize the
following:
109
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Maximizing:
CPU utilization: CPU utilization is the main task in which the
operating system needs to make sure that CPU remains as busy as
possible. It can range from 0 to 100 percent. However, for the RTOS, it
can be range from 40 percent for low-level and 90 percent for the
high-level system.
Throughput: The number of processes that finish their execution per
unit time is known Throughput. So, when the CPU is busy executing
the process, at that time, work is being done, and the work
completed per unit time is called Throughput.
Minimizing:
Waiting time: Waiting time is an amount that specific process needs
to wait in the ready queue.
110
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Response time: It is an amount to time in which the request was
submitted until the first response is produced.
Turnaround Time: Turnaround time is an amount of time to execute
a specific process. It is the calculation of the total time spent waiting
to get into the memory, waiting in the queue and, executing on the
CPU. The period between the time of process submission to the
completion time is the turnaround time.
First Come First Serve (FCFS)
• Jobs are executed on first come, first serve basis.
• It is a non-preemptive, pre-emptive scheduling algorithm.
• Easy to understand and implement.
• Its implementation is based on FIFO queue.
• Poor in performance as average wait time is high.
111
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Example:- The following table represents the time of arrival and
burst time of 4 processes
P0 0 5 P0 P1 P2 P3
P1 1 3 0 5 8 16 22
P2 2 8
P3 3 6
112
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
P0 0 5 5 5 0
P1 1 3 8 7 4
P2 2 8 16 14 6
P3 3 6 22 19 13
113
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Shortest Job Next (SJN)
• This is also known as shortest job first, or SJF
• This is a non-preemptive, pre-emptive scheduling algorithm.
• Best approach to minimize waiting time.
• Easy to implement in Batch systems where required CPU time is
known in advance.
• Impossible to implement in interactive systems where required
CPU time is not known.
• The processer should know in advance how much time process will
take.
The problem mentioned for FCFS is solved as follows:
114
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
P0 0 5 P0 P1 P3 P2
P1 1 3 0 5 8 14 22
P2 2 8
P3 3 6
Note:- Important Point is that though P1 has shortest time than P0, P0 arrives
at time 0 (When the entire system begins) and P1 comes after 1 unit of time
115
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
P0 0 5 5 5 0
P1 1 3 8 7 4
P2 2 8 22 20 12
P3 3 6 14 11 5
116
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Priority Based Scheduling
• Priority scheduling is a non-preemptive algorithm and one of the
most common scheduling algorithms in batch systems.
• Each process is assigned a priority. Process with highest priority is
to be executed first and so on.
• Processes with same priority are executed on first come first
served basis.
• Priority can be decided based on memory requirements, time
requirements or any other resource requirement.
117
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
P0 0 5 1
P1 1 3 2
P2 2 8 1
P3 3 6 3
P0 P3 P1 P2
0 5 11 14 22
118
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
P0 0 5 5 5 0
P1 1 3 11 10 7
P2 2 8 14 12 4
P3 3 6 22 19 13
119
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Shortest Remaining Time
• Shortest remaining time (SRT) is the preemptive version of the SJN
algorithm.
• The processor is allocated to the job closest to completion but it can
be preempted by a newer ready job with shorter time to completion.
• Impossible to implement in interactive systems where required CPU
time is not known.
• It is often used in batch environments where short jobs need to give
preference.
Round Robin Scheduling
• Round Robin is the preemptive process scheduling algorithm.
• Each process is provided a fix time to execute, it is called
a quantum.
120
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
• Once a process is executed for a given time period, it is preempted
and other process executes for a given time period.
• Context switching is used to save states of preempted processes.
The problem is solved with the quantum time 3 as follows:
Process Arrival Burst
Time(AT) Time(BT)
P0 0 5
P1 1 3
P2 2 8 Solution: The Gantt Chart is
P3 3 6 drawn as follows:
P0 P1 P2 P3 P0 P2 P3 P2
0 3 6 9 12 14 17 20 22
121
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
P0 0 5 14 0+(12-3) = 9
P1 1 3 6 (3 - 1) = 2
P2 2 8 22 (6 – 2) + ( 14 – 9 ) +
(20 – 17 ) = 12
P3 3 6 20 (9 – 3 ) + (17 - 12) = 11
122
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
Multiple-Level Queues Scheduling
• Multiple-level queues are not an independent scheduling algorithm.
They make use of other existing algorithms to group and schedule
jobs with common characteristics.
• Multiple queues are maintained for processes with common
characteristics.
• Each queue can have its own scheduling algorithms.
• Priorities are assigned to each queue.
For example, CPU-bound jobs can be scheduled in one queue and
all I/O-bound jobs in another queue. The Process Scheduler then
alternately selects jobs from each queue and assigns them to the
CPU based on the algorithm assigned to the queue.
123
Lecture - V BITS Pilani, Pilani Campus
PROCESS SHEDULING
System Processes
Highest Priority FCFS
Interactive Processes
CPU
Medium Priority SJF
Batch Processes
Lowest Priority RR
124
Lecture - V BITS Pilani, Pilani Campus
Learning Objectives
126
Lecture - VI BITS Pilani, Pilani Campus
MULTIPLE-LEVEL QUEUES
SCHEDULING
Example of Multilevel queue scheduling:
Consider below table of four processes under Multilevel
queue scheduling. Queue number denotes the queue of the
process.
P4 10 5
1
127
Lecture - VI BITS Pilani, Pilani Campus
MULTIPLE-LEVEL QUEUES
SCHEDULING
Priority of queue 1 is greater than queue 2. queue 1 uses
Round Robin (Time Quantum = 2) and queue 2 uses FCFS.
Below is the Gantt chart of the problem :
P1 P2 P1 P2 P3 P4 P5
0 2 4 6 7 10 15 20
At starting both queues have process so process in queue 1
(P1, P2) runs first (because of higher priority) in the round
robin fashion and completes after 7 units then process in
queue 2 (P3) starts running (as there is no process in queue 1)
but while it is running P4 comes in queue 1 and interrupts P3
128
Lecture - VI BITS Pilani, Pilani Campus
MULTIPLE-LEVEL QUEUES
SCHEDULING
and start running for 5 second and after its completion P3 takes the
CPU and completes its execution.
129
Lecture - VI BITS Pilani, Pilani Campus
MULTIPLE PROCESSOR
SCHEDULING
MULTIPLE PROCESSOR SCHEDULING
In multiple-processor scheduling multiple CPU’s are
available and hence Load Sharing becomes possible.
However multiple processor scheduling is more complex as
compared to single processor scheduling. In multiple
processor scheduling there are cases when the processors are
identical i.e. HOMOGENEOUS, in terms of their functionality,
we can use any processor available to run any process in the
queue.
Approaches to Multiple-Processor Scheduling
One approach is when all the scheduling decisions and I/O
processing are handled by a single processor which is called
the Master Server and the other processors executes only the 130
Lecture - VI BITS Pilani, Pilani Campus
MULTIPLE PROCESSOR
SCHEDULING
user code. This is simple and reduces the need of data sharing. This
entire scenario is called Asymmetric Multiprocessing.
A second approach uses Symmetric Multiprocessing where each
processor is self scheduling. All processes may be in a common
ready queue or each processor may have its own private queue for
ready processes. The scheduling proceeds further by having the
scheduler for each processor examine the ready queue and select a
process to execute.
131
Lecture - VI BITS Pilani, Pilani Campus
ALGORITHM EVALUATION
133
Lecture - VI BITS Pilani, Pilani Campus
ALGORITHM EVALUATION
137
Lecture - VI BITS Pilani, Pilani Campus
THREAD SCHEDULING
Write Read
MEMORY
143
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Sections of a Program
Here, are four essential elements of the critical section:
• Entry Section: It is part of the process which decides the
entry of a particular process.
• Critical Section: This part allows one process to enter and
modify the shared variable.
• Exit Section: Exit section allows the other process that are
waiting in the Entry Section, to enter into the Critical
Sections. It also checks that a process that finished its
execution should be removed through this Section.
• Remainder Section: All other parts of the Code, which is not
in Critical, Entry, and Exit Section, are known as the
Remainder Section.
144
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Do
{
Entry Section
Exit Section
Remainder Section
} while(true);
145
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
147
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
while(flag[j]) ;
Critical Section;
flag[i]=false;
remainder section;
} While(1);
For Process Pi, sets Flag[i] to be true, signaling that it is ready
to enter into its critical section. Then Pi checks whether it can
enter into its critical section. If not, Pi waits till Pj complete its
[Flag[j] becomes False]. Then Pi is allowed to enter its critical
section. On exiting the critical sectionm Pi sets Flag[i] to be
false.
Mutual exclusion satisfied but Progress requirement is not
satisfied. 149
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
2.Peterson Solution
Peterson's solution is widely used solution to critical section
problems. This algorithm was developed by a computer
scientist Peterson that's why it is named as a Peterson's
solution.
In this solution, when a process is executing in a critical state,
then the other process only executes the rest of the code, and
the opposite can happen. This method also helps to make sure
that only a single process runs in the critical section at a
specific time.
Example :
150
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
P1 P2 P3 …… Pn
Flag[1]=False Flag[2]=False Flag[3]=False … Flag[n]=False
Do
{
Flag[j]=true;
turn=j;
while (Flag[j] && turn == j) ;
Critical Section
Flag[i]=False;
Remainder Section
} While (1);
151
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
• Assume there are N processes (P1, P2, ... PN) and every
process at some point of time requires to enter the Critical
Section
• A FLAG[] array of size N is maintained which is by default
false. So, whenever a process requires to enter the critical
section, it has to set its flag as true. For example, If Pi wants
to enter it will set FLAG[i]=TRUE.
• Another variable called TURN indicates the process number
which is currently wafting to enter into the CS.
• The process which enters into the critical section while
exiting would change the TURN to another number from the
list of ready processes.
Example: turn is 2 then P2 enters the Critical section and while
exiting turn=3 and therefore P3 breaks out of wait loop.
152
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Synchronization Hardware
Some times the problems of the Critical Section are also
resolved by hardware. Some operating system offers a lock
functionality where a Process acquires a lock when entering
the Critical section and releases the lock after leaving it.So
when another process is trying to enter the critical section, it
will not be able to enter as it is locked. It can only do so if it is
free by acquiring the lock itself.
Mutex Locks
Synchronization hardware not simple method to implement for
everyone, so strict software method known as Mutex Locks was
also introduced.
153
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Repeat
Wait(mutex) Entry section
Critical Section
Signal(mutex) Exit section
Remainder section
Until (True);
It specifies that any process is allowed to enter into critical
section if mutex is 1. Before executing any process, assume
that mutex=1
When P1 wants to enter into the critical section but P0 is
already in the critical section, the value of mutex is 0. So it can
not enter into the critical section. So it has to wait till mutex is
changed to 1. Mutex is changed to 1 only when the running 156
Lecture - VII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
157
Lecture - VII BITS Pilani, Pilani Campus
Learning Objectives
Ø Classical problem 1- Bounded Buffer problem / Producer
and Consumer problem
- Definition
- How the problem is synchronized with Semaphore?
- Structures of Producer and Consumer
Ø Classical problem 2 – Dining and Philosopher problem
- Definition
- Solving the problem with Semaphore
Ø What are monitors?
Ø Solving Dining and Philosopher problem using monitors
158
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION-
Bounded Buffer Problem
- This problem is also called as producer – consumer problem
- It is problem based on synchronization
- There are two enteritis such as Producer and Consumer
- Producer produces a product and it should be placed on the
container [buffer]
- Consumer consumes the product that is available in the container
- The container should be used by only one of them , either the
producer or the consumer
1 2 3 4 ……… N
Product Consumer
159
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Solution to the problem is ,
- Create two counting semaphores “Full” and “Empty” to track
whether the buffer/ container is full or empty
- When the container is full, the producer can not place the product
in it
- When the container is empty, the consumer can not take any
product to consume
The procedure for the problem is written as follows:
Structure of Producer
While (True)
{
wait(empty);
wait(mutex);
Add Item into the buffer
160
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
signal(mutex);
signal(empty);
}
Structure of the Consumer
While (True)
{
wait(full);
wait(mutex);
Delete Item from the buffer
signal(mutex);
signal(empty);
}
161
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
The following are the variables what we use,
• Full represents how many elements / products are in the container
/ buffer
• Empty represents how many elements / products can be inserted
into the container / buffer
• N is the size of the buffer/ container
Initially, mutex is = 1.
Case 1: if consumer tries to consume a product from the empty
container,
Mutex = 1, Full = 0 and Empty = N [ All the cells are free]
while(true) – Condition is true
wait(full) -> wait(0) : do no-operation;
Case 2: if producer tries to add a product ,
162
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
while (true ) // Initially true
waif(empty) -> wait(N); Here N is not <=0, so permits the
operation, N = N - 1
P Empty = n - 1
Full = 1
163
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Now if Consumer wants to consume the product, the code is
executed as follows:
while(true) – Condition is true
wait(full) -> wait(1) : Here 1 is not <=0, so permits the
operation, full= full-1 =0
wait(mutex) -> wait(1) : Here 1 is not <=0, so permits
the operation, mutex= mutex-1 =0
Removes the Product from the buffer
Signal(mutex) -> mutext = mutex + 1 = 1
Signal(empty) -> empty = empty + 1 = N – 1 + 1= N
164
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION –
Dining Philosopher Problem
What is Dining Philosopher Problem?
It states that there are 5 philosophers (may be more than 5 also)
sharing a circular table and they eat and think alternatively. Thre is a
bowl of rice for each of the philosophers and 5 chopsticks. A
philosopher needs both their right and left chopstick to eat.
A hungry philosopher only eat if there are both the chopsticks
available. Otherwise the philosopher puts down their chopstick and
begin thinking again.
It is a classical synchronization problem as it demonstrates a large
class of concurrency control problem.
Solution:
The Solution for this problem is to use a semaphore to represent a
chopstick. A chopstick can be picked up by executing a wait
operation on the semaphore and released by executing a signal
165
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Semaphore. The structure of the chopstick is
semaphore Chopstick [5];
Initially the elements of the chopstick are initialized to as they are on
the table and picked by any philosopher.
The Structure of random philosopher i to eat is given as follows:
While (True)
{
wait(Chopstick[i] );
wait(Chopstick[ (i+1) % 5 );
Eating Rice ;
Signal(Chopstick(i]);
Signal(Chopstick[( i + 1 ) % 5 );
}
166
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Working out the procedure:
Initially, all the chopsticks [i] = 1 , i = 0 to 4 [When chopstick[i]=1, it
is free that is un used now].
Now Philosopher [2] wants to eat. Then the procedure is executed as
follows:
while ( true ) // Initially True
{
wait(chopstick[i])->wait(chopstick [ 2 ] ) – wait[1]
- Here 1 is not <=0, so permits the operation,
Chopstick[2]= Chopstick[2]-1=1-1=0
wait(chopstick[(i+1)%5])->wait(chopstick [ 3 ] ) – wait[1]
- Here 1 is not <=0, so permits the operation,
Chopstick[3]= Chopstick[3]-1=1-1=0
167
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
The Philosopher can eat
Signal(Chopstick[i]) – Signal(Chopstick[2])
Chopstick[2]=Chopstick[2]+1 =1
Signal (Chopstick[(i+1) % 5 ])- Signal(Chopstick[2])
Chopstick[2]=Chopstick[2]+1 =1
Now both the chopsticks are available.
Note:- When Philosopher[2] was eating (Chopstick[2]=0 and
Chopstick[3]=0), if philosopher[1] also wants to eat ,
Executing the same procedure, we have
While (True)
{
wait(chopstick[1]) -> wait(1); No problem Chopstick is available
wait(chopstick[(i+1)%5]->wait(chopstick[2]); Stopped as
Chopstick[2]=0;
168
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
Monitors
- Are also used for synchronization
- High level abstraction that provides and effective mechanism for
process synchronization
- A monitor type presents a set of operations that provide mutual
exclusive within the monitor
- To enter into the critical section, wait( ) function is called whereas
the signal( ) function when we exit form the critical section. If the
wait() and signal() functions are not properly coded, it will lead to a
very big problem in the entire system
- The monitor type also contains the declaration of variables whose
values are accessed by the functions declared inside the
abstraction
The Syntax for a monitor is
169
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
monitor monitor_name
{
Shared variable declaration;
procedure P1()
{
______
______
}
procedure P2()
{
______
______
}
170
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
procedure P3()
{
______
______
}
initialization Code()
{
______
______
}
} // End of the Monitor
171
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
The monitor also consists of conditional construct and is declared as
condition x,y;
• The operation that can be invoked on a condition variable ae wait()
and Signal()
• The operation x.wait() means that the process invoking tjis is
suspended until another process invokes x.signal()
• X.signal() operation resumes exactly one suspended process.
The Dining Philosopher problem is solved with the monitor as
monitor DiningPhilosophers
{
enum { THINKING,HUNGRY,EATING } State [5];
condition self[5];
void PickUp(int i)
{
172
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
state[i]=HUNGRY;
test(i);
if (state[i]!=EATING) self[i].wait();
}
void putdown(int i)
{
state[i]=THINKING;
// Test the left and right neighbors
test((i+4)%5);
test((i+1)%5);
}
void test(int i)
{
173
Lecture - VIII BITS Pilani, Pilani Campus
PROCESS SYNCHRONIZATION
if((state[(i+4)%5] != EATING ) &&
(state[i]= = HUNGRY ) &&
(state[ (i+1) % 5 ] != EATING ) )
{
state[i]=EATING;
self[i].signal();
}
}
Initialization_Code()
{
for (i=0;i<5;i++)
state[i]=THINKING;
}
}
174
Lecture - VIII BITS Pilani, Pilani Campus
Learning Objectives
Ø What is Deadlock?
ØExample for Deadlock
ØNecessary conditions for deadlock
ØDeadlock handling mechanisms
- Deadlock Prevention
- Deadlock Avoidance
- Deadlock Prevention and Recovery
175
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
Deadlock
In an operating system, there are many processes (processes
are programs that are currently being executed) running
continuously. All of these processes are important for the
functioning of the computer. It defines the basic unit of work that
has to be implemented by the system. Processes follow
sequential execution.
These processes require some resources to run or finish their
execution. Sequential order is followed here. The process first
requests for a resource. If it is available, the OS grants the
resource. If not, the process has to wait. After the process has
used the resource, it is released. If a problem arises during the
waiting and releasing, it means that there is a deadlock situation.176
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
What is Deadlock?
A deadlock is a common situation in operating systems where a
process waiting for a resource can be executed because that
resource is currently held by another process and is being
utilised for its execution, therefore, the process does not get
executed. Moreover, many other processes may also be waiting
for a resource to be released. A deadlock situation is created
Let us assume that there are two processes called P1 and P2.
Resources R1 and R2 are assigned to them respectively. So if
P1 needs R2 to complete its execution, but it is held by P2, P1
has to wait. Similarly, P2 may be waiting for R1 that is held by
P1. Thus, P2 has to wait until P1 has released the resource. As
a result, a deadlock situation arises and both processes are not 177
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
178
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
Example of Deadlock
• A real-world example would be traffic, which is going only in
one direction.
• Here, a bridge is considered a resource.
• So, when Deadlock happens, it can be easily resolved if one
car backs up (Preempt resources and rollback).
• Several cars may have to be backed up if a deadlock situation
occurs.
• So starvation is possible.
179
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
180
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
Necessary conditions for deadlock
1. Mutual exclusion
The processes are permitted to use the shared resource in
mutual exclusive way. Only one process is permitted to use a
shared resource. When a resource is used by another process, a
new process is permitted to use it. If mutual exclusion is not
followed, there is a possibility of deadlock
2. Hold and Wait condition
The process which asks for a resource is holding a resource
already. If so, a deadlock may occur
3. Pre emption
When shared resource can be pre-empted, there is a possibility of
Deadlock. Pre emption allocates the resource held by a process to
another process.
181
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
4. Circular wait
If the processes are waiting in the circular fashion such as the
following diagram, deadlock may occur.
182
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
187
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
The above Figure shows the Safe, unsafe, and deadlocked state
spaces 190
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
Deadlock Avoidance Example
Let us consider a system having 12 magnetic tapes and three
processes P1, P2, P3. Process P1 requires 10 magnetic tapes,
process P2 may need as many as 4 tapes, process P3 may
need up to 9 tapes. Suppose at a time to, process P1 is holding
5 tapes, process P2 is holding 2 tapes and process P3 is
holding 2 tapes. (There are 3 free magnetic tapes)
Processes Maximum Needs Current Needs
P1 10 5
P2 4 2
P3 9 2
191
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
5 more tapes. If it does so, it will have to wait because they are
unavailable. Similarly, process P3 may request its additional 6
tapes and have to wait which then results in a deadlock.
The mistake was granting the request from P3 for one more
tape. If we made P3 wait until either of the other processes had
finished and released its resources, then we could have avoided
the deadlock
Note: In a case, if the system is unable to fulfill the request of all
processes then the state of the system is called unsafe.
The main key of the deadlock avoidance method is whenever
the request is made for resources then the request must only be
approved only in the case if the resulting state is a safe state.
193
Lecture - IX BITS Pilani, Pilani Campus
DEADLOCK
194
Lecture - IX BITS Pilani, Pilani Campus
Learning Objectives
P1 9 5
P2 5 2
P3 3 1
Let us assume that there are three processes P1, P2, P3. Some
more information on which the processes tells the Operating
System are :
• P1 process needs a maximum of 9 resources (Resources like
tape drive or printer etc..) to complete its execution. P1 is
currently allocated with 5 Resources and needs 4 more to
complete its execution.
197
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK AVOIDANCE
Step 1 - Assume work and finish as vectors of length 'm' and 'n'
respectively.
Work = Available
Finish[i] = 'false'
Step 2 - Find 'i' such that,
Finish[i] = 'false'
Needi ≤ Work
If no such 'i' is found jump to step four.
Step 3 - Work = Work + Allocation
Finish[i] = 'true'
Jump to step two.
Step 4 - If finish[i] = True for all then the system is in a safe
state.
207
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK AVOIDANCE
P0 1 1 2 4 3 3 2 1 0
P1 2 1 2 3 2 2
P2 4 0 1 9 0 2
P3 0 2 0 7 5 3
P4 1 1 2 1 1 2
208
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK AVOIDANCE
Do the following:
(i) Calculate the content of the need matrix?
(ii) Is the system in a safe state?
(iii) Determine the total amount of resources of each type?
Solution:
1. Content of the need matrix can be calculated by using the
below formula
Need = Max – Allocation
209
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK AVOIDANCE
Safe sequence:
For process P0, Need = (3, 2, 1) and
Available = (2, 1, 0)
Need ? Available = False
So, the system will move for the next process.
2. For Process P1, Need = (1, 1, 0)
Available = (2, 1, 0)
Need ? Available = True
Request of P1 is granted.
Available = Available +Allocation
= (2, 1, 0) + (2, 1, 2)
= (4, 2, 2) (New Available)
210
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
3. For Process P2, Need = (5, 0, 1)
Available = (4, 2, 2)
Need ? Available = False
So, the system will move to the next process.
4. For Process P3, Need = (7, 3, 3)
Available = (4, 2, 2)
Need ? Available = False
So, the system will move to the next process.
5. For Process P4, Need = (0, 0, 0)
Available = (4, 2, 2)
Need ? Available = True
Request of P4 is granted.
? Available = Available + Allocation 211
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK AVOIDANCE
= (4, 2, 2) + (1, 1, 2)
= (5, 3, 4) now, (New Available)
6. Now again check for Process P2, Need = (5, 0, 1)
Available = (5, 3, 4)
Need ? Available = True
Request of P2 is granted.
? Available = Available + Allocation
= (5, 3, 4) + (4, 0, 1)
= (9, 3, 5) now, (New
Available)
7. Now again check for Process P3, Need = (7, 3, 3)
Available = (9, 3, 5)
Need ? Available = True 212
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK AVOIDANCE
Request of P3 is granted.
Available = Available +Allocation
= (9, 3, 5) + (0, 2, 0) = (9, 5, 5)
8. Now again check for Process P0, = Need (3, 2, 1)
= Available (9, 5, 5)
Need ? Available = True
So, the request will be granted to P0.
Safe sequence: < P1, P4, P2, P3, P0>
The system allocates all the needed resources to each
process. So, we can say that system is in a safe state.
3. The total amount of resources = sum of columns of allocation
+ Available = [8 5 7] + [2 1 0] = [10 6 7]
213
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
If a system does not employ either a deadlock-prevention or
deadlock-avoidance algorithm, then there are chances of
occurrence of a deadlock. In this case, the system may provide
two things: An algorithm is used to examines the state of the
system in order to determine whether a deadlock has
occurred. An algorithm that is used to recover from the
deadlock. Thus order to get rid of deadlocks the operating
system periodically checks the system for any deadlock. After
Finding the deadlock the operating system will recover from it
using recovery techniques.
Now, the main task of the operating system is to detect the
deadlocks and this is done with the help of Resource Allocation
Graph. 214
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
215
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
Single Instance of Each Resource Type
If all the resources have only a single instance, then a deadlock-
detection algorithm can be defined that mainly uses the variant
of the resource-allocation graph and is known as a wait-for
graph. This wait-for graph is obtained from the resource-
allocation graph by removing its resource nodes and collapsing
its appropriate edges.
An edge from Pi to Pj in a wait-for graph simply implies that
process Pi is basically waiting for process Pj in order to release a
resource that it needs. An edge Pi, Pj exists in a wait-for graph if
and only if the corresponding resource allocation graph contains
two edges Pi,Rq and Rq,Pj for a resource Rq.
216
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
A deadlock exists in the system if and only if there is a cycle in
the wait-for graph. In order to detect the deadlock, the system
needs to maintain the wait-for graph and periodically system
invokes an algorithm that searches for the cycle in the wait-
for graph.
The algorithm that is used to detect the cycle in the graph mainly
requires n² operations; where n indicates the number of vertices
in the graph.
Multiple Instances of Each Resource Type
The above scheme that is a wait-for graph is not applicable to
the resource-allocation system having multiple instances of each
resource type. Now we will move towards a deadlock detection
algorithm that is is applicable for such systems. 217
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
This algorithm mainly uses several time-varying data structures
that are similar to those used in Banker's Algorithm.
Recovery From Deadlock
When a detection algorithm determines that a deadlock exists
then there are several available alternatives. There one
possibility and that is to inform the operator about the deadlock
and let him deal with this problem manually.
Another possibility is to let the system recover from the deadlock
automatically. These are two options that are mainly used to
break the deadlock.
218
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
219
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
Process Termination
In order to eliminate deadlock by aborting the process, we will
use one of two methods given below. In both methods, the
system reclaims all resources that are allocated to the
terminated processes.
Aborting all deadlocked Processes Clearly, this method is
helpful in breaking the cycle of deadlock, but this is an expensive
approach. This approach is not suggestible but can be used if
the problem becomes very serious. If all the processes are killed
then there may occur insufficiency in the system and all
processes will execute again from starting.
Abort one process at a time until the elimination of the
deadlock cycle This method can be used but we have to decide220
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
which process to kill and this method incurs considerable
overhead. The process that has done the least amount of work is
killed by the Operating system firstly.
Resource Pre-emption
In order to eliminate the deadlock by using resource preemption,
we will successively preempt some resources from processes
and will give these resources to some other processes until the
deadlock cycle is broken and there is a possibility that the
system will recover from deadlock. But there are chances that
the system goes into starvation.
221
Lecture - X BITS Pilani, Pilani Campus
DEADLOCK DETECTION &
RECOVERY
The issues in the pre emption are :
(i) Selecting a victim – Which process is to be selected which
may lead to starvation
(ii) Rollback – We have to rollback to the beginning of the
process
222
Lecture - X BITS Pilani, Pilani Campus
Learning Objectives
Ø Swapping
Ø Contiguous Memory allocation
- Fixed Size partition
- Variable size partition
- Block allocation list
- Bit Map
Ø Non Contiguous Memory allocation
- Segmentation
- Paging
- Segmentation with Paging
223
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
SWAPPING
We know that all the processes are executed in the memory. A
process can be swapped temporarily out of memory to a backing
store and then brought back into memory for continued
execution.
For example, assume that a multiprogramming environment with
a round-robin CPU algorithm. When a quantum expires, the
memory manager will swap out the process that has just
reached the quantum time and to swap in another process to the
memory. Like this, when each process finishes its quantum time,
it will be swapped with another process. The quantum time must
be sufficiently large that reasonable amounts of computing are
done between swaps. 224
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
Operating
System Process
1. Swapped out P1
2. Swapped In Process
P2
User Space
225
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
227
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
229
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
leaves the memory we will see the set of holes of variable sizes.
In the figure above, we can see that when file A and file C
release the memory allocated to them, creates the holes in the
memory of variable size.
In the variable size partition method, the operating system
analyses the memory requirement of the process and see
whether it has a memory block of the required size.
If it finds the match, then it allocates that memory block to the
process. If not, then it searches the ready queue for the process
that has a smaller memory requirement.
The operating system allocates the memory to the process until
it cannot satisfy the memory requirement of the next process in
the ready queue. It stops allocating memory to the process if it 231
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
232
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
Best-fit
This method needs the list of free holes to be sorted according to
their size. Then the smallest hole that is large enough for the
process to accommodate is selected from the list of free holes.
This strategy reduces the wastage of memory as it does not
allocate a hole of larger size which leaves some amount of
memory even after the process accommodates the space.
Worst-fit
This method requires the entire list of free holes to be sorted.
Here, again the largest hole among the free holes is selected.
This strategy leaves the largest leftover hole which may be
useful for the other process.
234
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
2. Bit Map
The bit map method only keeps track of the free or allocated
block. One block is represented by one bit, bit 0 resembles the
free block and bit 1 resembles that the block is allocated to a file
or a process.
235
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
237
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
238
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
ii) Segmentation
Segmentation is a programmer view of the memory where
instead of dividing a process into equal size partition we divided
according to program into partition called segments. The
translation is the same as paging but paging segmentation is
independent of internal fragmentation but suffers from external
fragmentation. Reason of external fragmentation is program can
be divided into segments but segment must be contiguous in
nature.
iii) Segmentation with paging
In segmentation with paging, we take advantages of both
segmentation as well as paging. It is a kind of multilevel paging
but in multilevel paging, we divide a page table into equal size 241
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
242
Lecture - XI BITS Pilani, Pilani Campus
MEMORY MANAGEMENT
243
Lecture - XI BITS Pilani, Pilani Campus
Learning Objectives
Ø Segmentation
• What is segmentation?
• Why segmentation is required?
Ø Translation of Logical address into physical
address by Segment table
Ø Advantages and disadvantages of segmentation
Ø Structure of the page table
• Hierarchical Paging
• Hashed Page Tables
• Inverted Page Tables
244
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
SEGMENTATION
Segmentation
• It is a memory allocation technique to store parts of a single
process in various locations
• It is a variable size partitioning scheme
• It is a technique in non contiguous memory allocation like
paging
• In segmentation, process is divided into variable sized
partitions called as segments
• Secondary and main memory are divided into unequal size
partitions
245
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
SEGMENTATION
In Operating Systems, Segmentation is a memory management
technique in which the memory is divided into the variable size
parts. Each part is known as a segment which can be allocated
to a process.
The details about each segment are stored in a table called a
segment table. Segment table is stored in one (or many) of the
segments.
Segment table contains mainly two information about segment:
Base: It is the base address of the segment
Limit: It is the length of the segment.
246
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
segmentation
What is the need of Segmentation?
Till now, we were using Paging as our main memory
management technique. Paging is more close to the Operating
system rather than the User. It divides all the processes into the
form of pages regardless of the fact that a process can have
some relative parts of functions which need to be loaded in the
same page.
Operating system doesn't care about the User's view of the
process. It may divide the same function into different pages and
those pages may or may not be loaded at the same time into the
memory. It decreases the efficiency of the system.
It is better to have segmentation which divides the process into
the segments. Each segment contains the same type of 247
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
segmentation
functions such as the main function can be included in one
segment and the library functions can be included in the other
segment.
MAIN SUB1 SUB2
Statement 1 Statement 1 Statement 1
Statement 2 Statement 2 Statement 2
------------- --------------- --------------
------------- --------------- Statement K
-------------- Statement L
--------------
Statement M
248
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
segmentation
Translation of Logical address into physical address by
Segment table
CPU generates a logical address which contains two parts:
1. Segment Number
2. Offset
For Example:
Suppose a 16 bit address is used with 4 bits for the segment
number and 12 bits for the segment offset so the maximum
segment size is 4096 and the maximum number of segments
that can be refereed is 16.
When a program is loaded into memory, the segmentation
system tries to locate space that is large enough to hold the first
segment of the process, space information is obtained from 249
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
segmentation
the free list maintained by memory manager. Then it tries to
locate space for other segments. Once adequate space is
located for all the segments, it loads them into their respective
areas.
The operating system also generates a segment map table for
each program.
250
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
segmentation
251
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
segmentation
With the help of segment map tables and hardware assistance,
the operating system can easily translate a logical address into
physical address on execution of a program.
The Segment number is mapped to the segment table. The limit
of the respective segment is compared with the offset. If the
offset is less than the limit then the address is valid otherwise it
throws an error as the address is invalid.
In the case of valid addresses, the base address of the segment
is added to the offset to get the physical address of the actual
word in the main memory.
The above figure shows how address translation is done in case
of segmentation.
252
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT –
segmentation
Advantages of Segmentation
• No internal fragmentation
• Average Segment Size is larger than the actual page size.
• Less overhead
• It is easier to relocate segments than entire address space.
• The segment table is of lesser size as compared to the page
table in paging.
Disadvantages
• It can have external fragmentation.
• It is difficult to allocate contiguous memory to variable sized
partition.
• Costly memory management algorithms.
253
Lecture - XII BITS Pilani, Pilani Campus
STRUCTURE OF PAGE TABLE
254
Lecture - XII BITS Pilani, Pilani Campus
STRUCTURE OF PAGE TABLE
255
Lecture - XII BITS Pilani, Pilani Campus
STRUCTURE OF PAGE TABLE
257
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT – PAGE
TABLE STRUCTURE
Two Level Page Table
Consider a system having 32-bit logical address space and a
page size of 1 KB and it is further divided into:
• Page Number consisting of 22 bits.
• Page Offset consisting of 10 bits.
As we page the Page table, the page number is further divided
into :
Page Number consisting of 12 bits.
Page Offset consisting of 10 bits.
Thus the Logical address is as follows:
258
Lecture - XII BITS Pilani, Pilani Campus
STRUCTURE OF PAGE TABLE
260
Lecture - XII BITS Pilani, Pilani Campus
MEMORY MANAGEMENT – PAGE
TABLE STRUCTURE
Three Level Page Table
For a system with 64-bit logical address space, a two-level
paging scheme is not appropriate. Let us suppose that the page
size, in this case, is 4KB.If in this case, we will use the two-page
level scheme then the addresses will look like this:
261
Lecture - XII BITS Pilani, Pilani Campus
STRUCTURE OF PAGE TABLE
263
Lecture - XII BITS Pilani, Pilani Campus
STRUCTURE OF PAGE TABLE
• There is one entry for each virtual page number and a real
page of memory
• And the entry mainly consists of the virtual address of the
page stored in that real memory location along with the
information about the process that owns the page.
• Though this technique decreases the memory that is needed
to store each page table; but it also increases the time that is
needed to search the table whenever a page reference
occurs.
The following figure shows the address translation scheme of the
Inverted Page Table:
265
Lecture - XII BITS Pilani, Pilani Campus
STRUCTURE OF PAGE TABLE
266
Lecture - XII BITS Pilani, Pilani Campus
Learning Objectives
ØPage replacement algorithms
ØWhat is a File?
ØFile Structure
ØFile types
ØFile Access mechanisms
Ø Space allocation for the files
ØFile system structure
ØDirectory
•Definition
•Structures - Single level, two level , hierarchical , tree structured and
Acyclic graph directory structures
267
Lecture - XIII BITS Pilani, Pilani Campus
PAGE REPLACEMENT
ALGORITHM
Page Fault in OS-
•A page fault occurs when a page referenced by the CPU is not
found in the main memory.
•The required page has to be brought from the secondary
memory into the main memory.
•A page has to be replaced if all the frames of main memory are
already occupied.
Page replacement is a process of swapping out an existing page
from the frame of a main memory and replacing it with the req
Page replacement is required when-
•All the frames of main memory are already occupied.
•Thus, a page has to be replaced to create a room for the
required page.
268
Lecture - XIII BITS Pilani, Pilani Campus
PAGE REPLACEMENT
ALGORITHM
Page Replacement Algorithms-
Page replacement algorithms help to decide which page must
be swapped out from the main memory to create a room for the
incoming page.
Various page replacement algorithms are-
•FIFO Page Replacement Algorithm
•LIFO Page Replacement Algorithm
•LRU Page Replacement Algorithm
•Optimal Page Replacement Algorithm
•Random Page Replacement Algorithm
A good page replacement algorithm is one that minimizes
the number of page faults.
269
Lecture - XIII BITS Pilani, Pilani Campus
PAGE REPLACEMENT
ALGORITHM
FIFO Page Replacement Algorithm
• As the name suggests, this algorithm works on the principle of
“First in First out“.
• It replaces the oldest page that has been present in the main
memory for the longest time.
• It is implemented by keeping track of all the pages in a queue.
275
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
File Type
File type refers to the ability of the OS to distinguish different
types of file such as text files, source files and binary files etc.
MS-DOS and UNIX operating system have the following types of
files:
(i) Ordinary files
• These files contain user information such as text, databases
or an executable program.
• Users can perform various operations on such files like add,
modify, delete or even remove the entire file.
(ii) Directory files
These files contain list of file names and other information
related to these files.
276
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
(iii) Special files
• These files are also known as device files.
• These files represent physical device like disks, terminals,
printers, networks, tape drive etc.
File Access Mechanisms
File access mechanism refers to the manner in which the
records of a file are be accessed. Some of the file mechanisms
are:
1. Sequential access
2. Direct/Random access
3. Indexed sequential access
277
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
Sequential access
A sequential access is that in which the records are accessed
sequentially, i.e., the information in the file is processed in order,
one record after the other. This access method is the most
primitive one.
Direct/Random access
• Random access file organization provides, accessing the
records directly.
• The records need not be in any sequence within the file and
they need not be in adjacent locations on the storage
medium.
Indexed sequential access
• This mechanism is built up on base of sequential access.
278
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
• An index is created for each file which contains address of
various records.
• Index is searched sequentially and its pointer is used to
access the file directly.
Space Allocation
OS allocates the disk spaces for the files. OS deploy following
three methods to allocate disk space to files.
1. Contiguous Allocation
2. Linked Allocation
3. Indexed Allocation
Contiguous Allocation
• Each file occupies a contiguous address space on disk.
• Easy to implement.
279
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
• External fragmentation is a major issue for this technique.
280
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
Linked Allocation
• Each file contains a list of links to disk blocks.
• Directory contains link / pointer to first block of a file.
• There is no external fragmentation
• Effectively used in sequential access.
• Inefficient in case of direct accessing
281
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
282
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
Indexed Allocation
• Provides solutions to problems for contiguous and linked
allocation.
• An index block is created having all pointers to files.
• Each file has its own index block which stores the addresses
of disk space occupied by the file.
• Directory contains the addresses of index blocks of files.
283
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
284
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
File System Structure
File System provides efficient access to the disk by allowing data
to be stored, located and retrieved in a convenient way. A file
System must be able to store the file, locate the file and retrieve
the file.
Most of the Operating Systems use layering approach for every
task including file systems. Every layer of the file system is
responsible for some activities.
The diagram shown below, elaborates how the file system is
divided in different layers, and also the functionality of each
layer.
285
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
286
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
• When an application program asks for a file, the request is
directed to the logical file system.
• The logical file system contains the Meta data of the file and
directory structure. If the application program doesn't have the
required permissions of the file then this layer will throw an
error. Logical file systems also verify the path to the file.
• Generally, files are divided into various logical blocks. Files
are to be stored in the hard disk and to be retrieved from the
hard disk. Hard disk is divided into various tracks and sectors.
So, in order to store and retrieve the files, the logical blocks
need to be mapped to physical blocks. This mapping is done
by File organization module. It is also responsible for free
space management.
• Once File organization module has identified the physical
block of the application program needs, it passes this 287
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
BASICS
information to basic file system. The basic file system is
responsible for issuing the commands to I/O control to
fetch those blocks.
•I/O controls contain the codes by using which it can access hard
disk. These codes are known as device drivers.
Directory
•Directory can be defined as the listing of the related files on the
disk
• A directory can be viewed as a file which contains the Meta
data of the bunch of files.
•Every Directory permits the user to do a number of common
operations on the file:
- File Creation
288
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
- Search for the file
- File deletion
- Renaming the file
- Traversing Files
- Listing of files
Types of Directory Structures
The following are the most common types of directories
1. Single-level directory structure
Single level directory structure has only one directory which is
called the root directory. The users are not allowed to create
subdirectories under the root directory. All the files created by the
several users are present in the root directory only.
289
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
As we can see in the diagram below all the file F1, F2, F3, F4
created by the different users are present at the root directory.
290
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
There is one drawback of Single-level directory structure, a
user cannot use the same file name used by another user in
the system. Even if the file with the same name is created the
old file will get destroyed first and replaced by the new file having
the same name.
2. Two-level directory structure
In Two-level directory structure, the users create directory
directly inside the root directory. But once a user creates such
directory, further he cannot create any subdirectory inside that
directory. Observe the figure below, 4 users have created their
separate directory inside the root directory. But further, no
subdirectory is created by the users.
291
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
292
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
This two-level structure allows each user to keep their files
separately inside their own directory. This structure allows to use
the same name for the files but under different user directories.
3. Hierarchical Directory Structure
In Hierarchical directory structure, the users can create
directories under the root directory and can also create sub-
directories under this structure. As the user is free to create
many sub-directories, it can create different sub-directories for
different file types.
293
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
294
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
Here, the files are accessed by their location using the path.
There are two types of paths to locate the file in this directory
structure
Absolute Path
Here, the path for the desired file is described by considering the
root directory as the base directory.
Relative Path
Here, either the user’s directory is considered as the base
directory or the desired file directory is considered as the base
directory.
295
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
4. Acyclic-Graph Directory Structure
This problem can be solved by the acyclic-graph directory
structure. As this directory structure allows a directory or a file to
have many parent directories. So, a shared file in a directory can
be pointed by the other user directories who have access to that
shared file using the links.
In the diagram below we can see that the directory having file
F7 and F8 have two parent directories.
296
Lecture - XIII BITS Pilani, Pilani Campus
FILE MANAGEMENT –
Directory
297
Lecture - XIII BITS Pilani, Pilani Campus
Learning Objectives
ØWhat is Free space management?
Ø Types of free space management methods
- Bit Vector
- Linked List
- Grouping
- Counting
Ø Recovery
Ø What is NFS?
ØBenefits of NFS
298
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
What is free space management?
The operating system manages the free space in the hard disk.
This is known as free space management. The operating system
maintains a free space list to keep track of the free disk space.
The free space list consists of all free disk blocks that are not
allocated to any file or directory. For saving a file in the disk, the
operating system searches the free space list for the required
disk space and then allocates that space to the file. When a file
is deleted, the space allocated to it is added to the free space
list.
There are four methods of doing free space management. These
are -
299
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
300
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
Bit Vector
The first method that we will discuss is the bit vector method.
Also known as the bit map, this is the most frequently used
method to implement the free space list. In this method, each
block in the hard disk is represented by a bit (either 0 or 1). If a
block has a bit 0 means that block is allocated to a file, and if a
block has a bit 1 means that block is not allocated to any file, i.e.,
the block is free.
For example, consider a disk having 16 blocks where block
numbers 2, 3, 4, 5, 8, 9, 10, 11, 12 and 13 are free, and the rest
of the blocks, i.e., block numbers 0, 1, 6, 7, 14 and 15 are
allocated to some files. The bit vector for this disk will look like
this- 301
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
We can find the free block number from the bit vector using the
following method-
We will now find the first free block number in the above
example.
302
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
The first group of 8 bits (00111100) constitutes a non-zero word
since all bits are not 0. After finding the non-zero word, we will
look for the first 1 bit. This is the third character of the non-zero
word. Hence, offset = 3.
Therefore, the first free block number = 8 * 0 + 3 = 3.
Advantages
The advantages of the bit vector method are-
• It is simple to understand.
• It is an efficient method.
• It occupies less memory.
Disadvantages
The disadvantages of the bit vector method are-
For finding a free block, the operating system may need to 303
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
search the entire bit vector.
Keeping the bit vector in the main memory is possible for smaller
disks but not for larger ones. For example, a 1.3 GB disk with
512-byte blocks would need a bit vector of over 332 KB to track
its free blocks. Giving away 332 KB just to maintain its free block
space is not so efficient in the long run.
Linked List
Another method of doing free space management is a linked list.
In this method, all the free blocks existing in the disk are linked
together in a linked list. The address of the first free block is
stored somewhere in the memory. Each free block contains a
pointer that contains the address to the next free block. The last
free block points to null, indicating the end of the linked list. 304
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
For example, consider a disk having 16 blocks where block
numbers 3, 4, 5, 6, 9, 10, 11, 12, 13 and 14 are free, and the rest
of the blocks, i.e., block numbers 1, 2, 7, 8, 15 and 16 are
allocated to some files. If we maintain a linked list, then Block 3
will contain a pointer to Block 4, Block 4 will contain a pointer to
Block 5. Similarly, Block 5 will point to Block 6, Block 6 will point
to Block 9, Block 9 will point to Block 10, Block 10 will point to
Block 11, Block 11 will point to Block 12, Block 12 will point to
Block 13 and Block 13 will point to Block 14. Block 14 will point
to null. The address of the first free block, i.e., Block 3, will be
stored somewhere in the memory. This is also represented in the
following figure-
305
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
306
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
Advantages
The advantages of the linked list method is
•There is no wastage of space in this method.
Disadvantages
The disadvantages of the linked list method are-
•This method is inefficient since we need to read each block to
traverse the list, which takes more I/O time.
•There is an overhead of maintaining the pointer.
Grouping
The third method of free space management is grouping. This
method is the modification of the linked list method. In this
method, the first free block stores the addresses of the n free
blocks. The first n-1 of these blocks are free. The last block in 307
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
these n free blocks contains the addresses of the next n free
blocks, and so on.
For example, consider a disk having 16 blocks where block
numbers 3, 4, 5, 6, 9, 10, 11, 12, 13 and 14 are free, and the rest
of the blocks, i.e., block numbers 1, 2, 7, 8, 15 and 16 are
allocated to some files.
If we apply the Grouping method considering n to be 3, Block 3
will store the addresses of Block 4, Block 5 and Block 6.
Similarly, Block 6 will store the addresses of Block 9, Block 10
and Block 11. Block 11 will store the addresses of Block 12,
Block 13 and Block 14. This is also represented in the following
figure-
308
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
311
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
318
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
Network File System (NFS)
The Network File System (NFS) is an IP-based file-sharing
protocol that is used by NAS systems to allow multiple remote
systems to connect to a shared file system. NFS uses file-level
data access and the target (or destination) NAS device controls
the storage device.
319
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
It is a “distributed” file system protocol, which means that its data
is stored on a server and that it uses a network protocol to share
– and restrict – access to the file system, using the same coding
that is used for local files. NFS has three components: a client,
a server, and the protocol that enables the two to communicate.
It allows a user on Computer 1 (the “client”) to access File A on
Computer 2 over a network in much the same way they would
access a file on Computer 1’s own hard drive. To Computer 1,
NFS is ‘invisible’; while NFS is keeping track of where files are
located and transporting data, Computer 1 ‘sees’ a file system
that looks local. The naming convention used by NFS makes it
impossible to tell from File A’s name that it’s being accessed
remotely. 320
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
And if File A is being modified on Computer 2, those
modifications will be seen on Computer 1. Similarly, if the file is
moved to a different server, the user of Computer 1 won’t know
it.
While NFS is OS- (operating system) independent, it is typically
used on Unix systems, macOS, and Linux. It is also hardware-,
network architectures, and transport protocol independent, and
works well in both small and large environments.
Distributed file systems such as NFS offer many benefits.
Storing data on servers frees up the resources of client
machines. Distributing data (e.g., important administrative data)
to multiple clients is easier, and it is even possible to transfer
files between computers that use different operating systems 321
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
(i.e., between computers in “heterogeneous environments”). For
example, you could use a Windows NFS file server in a Linux
environment to give Linux client computers access to files on
that Windows NFS server. And rather than every user in an
organization having their home directory on their individual
network machine, all the home directories could be set up on an
NFS server and then accessed as appropriate by everyone on
the network.
The benefits of the NFS service are
• Multiple clients can use the same files, which allows everyone
on the network to use the same data, accessing it on remote
hosts as if it were accessing local files.
322
Lecture - XIV BITS Pilani, Pilani Campus
FILES AND DIRECTORY
MANAGEMENT
• Computers share applications, which eliminates the needs for
local disk space and reduces storage costs.
• All users can read the same files, so data can remain up-to-
date, and it’s consistent and reliable.
• Mounting the file system is transparent to all users.
• Support for heterogeneous environments allows us to run
mixed technology from multiple vendors and use
interoperable components.
• System admin overhead is reduced due to centralization of
data.
323
Lecture - XIV BITS Pilani, Pilani Campus
Learning Objectives
Ø Storage Structure
Ø Disk structure
Ø SAN and NAS
Ø Disk Scheduling algorithms
- First Come First Serve
- Shortest seek time first
- SCAN
- LOOK
- C-SCAN
- C-LOOK
324
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – STORAGE
STRUCTURE
Basically we want the programs and data to reside in main
memory permanently. This arrangement is usually not possible
for the following two reasons:
1. Main memory is usually too small to store all needed
programs and data permanently.
2. Main memory is a volatile storage device that loses its
contents when power is turned off
There are two types of storage devices:-
Volatile Storage Device –
It loses its contents when the power of the device is removed.
Non-Volatile Storage device –
It does not loses its contents when the power is removed. It
holds all the data when the power is removed.
325
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – STORAGE
STRUCTURE
Secondary storage is used as an extension of main memory.
Secondary storage devices can hold the data permanently.
Storage devices consists of registers, cache,
Electronic-Disk, Magnetic disk , optical disk , Magnetic Tapes.
Each storage system provides the basic system of storing a
datum and of holding the datum until it is retrieved at a later time.
All the storage devices differ in speed, cost, size and volatility.
The most common Secondary-storage device is a Magnetic-disk,
which provides storage for both programs and data.
The following figure shows the hierarchy of storage
326
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – STORAGE
STRUCTURE
327
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – STORAGE
STRUCTURE
In this hierarchy all the storage devices are arranged according
to speed and cost. The higher levels are expensive, but they are
fast. As we move down the hierarchy, the cost per bit generally
decreases, where as the access time generally increases.
The storage systems above the Electronic disk are Volatile,
where as those below are Non-Volatile.
An Electronic disk can be either designed to be either Volatile or
Non-Volatile. During normal operation, the electronic disk stores
data in a large DRAM array, which is Volatile. But many
electronic disk devices contain a hidden magnetic hard disk and
a battery for backup power. If external power is interrupted, the
electronic disk controller copies the data from RAM to the
magnetic disk. When external power is restored, the 328
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – STORAGE
STRUCTURE
controller copies the data back into the RAM.
The design of a complete memory system must balance all the
factors. It must use only as much expensive memory as
necessary while providing as much inexpensive, Non-Volatile
memory as possible. Caches can be installed to improve
performance where a large access-time or transfer-rate disparity
exists between two components.
329
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – STORAGE
STRUCTURE
Secondary storage devices are those devices whose storage is
non volatile. It means that the stored data will be intact even if
the system is turned off. Here are a few things worth noting
about secondary storage.
• Secondary storage is also called auxiliary storage.
• Secondary storage is less expensive when compared to
primary memory like RAMs.
• The speed of the secondary storage is also lesser than that of
primary storage.
• Hence, the data which is less frequently accessed is kept in
the secondary storage.
330
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT –
MAGNETIC DISK STRUCTURE
Magnetic Disk Structure
In modern computers, most of the secondary storage is in the
form of magnetic disks. Hence, knowing the structure of a
magnetic disk is necessary to understand how the data in the
disk is accessed by the computer.
Structure of a magnetic disk
A magnetic disk contains several platters. Each platter is divided
into circular shaped tracks. The length of the tracks near the
centre is less than the length of the tracks farther from the
centre. Each track is further divided into sectors.
Tracks of the same distance from centre form a cylinder. A read-
write head is used to read data from a sector of the magnetic
Disk. 331
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT –
MAGNETIC DISK STRUCTURE
332
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT –
MAGNETIC DISK STRUCTURE
The speed of the disk is measured as two parts:
Transfer rate: This is the rate at which the data moves from disk
to the computer.
Random access time: It is the sum of the seek time and
rotational latency.
Seek time is the time taken by the arm to move to the required
track. Rotational latency is defined as the time taken by the
arm to reach the required sector in the track.
Even though the disk is arranged as sectors and tracks
physically, the data is logically arranged and addressed as an
array of blocks of fixed size. The size of a block can
be 512 or 1024 bytes. Each logical block is mapped with a sector
on the disk, sequentially. 333
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – SAN AND
NAS
Storage Area Network (SAN) is used for transferring the data
between the servers and the storage devices’ fiber channels and
switches. In SAN (Storage Area Network), data is identified by
disk block. Protocols that are used in SAN are SCSI (Small
Computer System Interface), SATA (Serial Advanced Technology
Attachment), etc.
Components of Storage Area Network (SAN):
1.Node ports
2. Cables
3. Interconnect devices such as Hubs, switches, directors
4. Storage arrays
5. SAN management Software
334
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – SAN AND
NAS
Network Attached Storage (NAS), data is identified by file
name as well as byte offset. In-Network Attached Storage, the
file system is managed by Head units such as CPU and Memory.
In this for backup and recovery, files are used instead of the
block-by-block copying technique.
Components of Network Attached Storage (NAS):
1. Head unit: CPU, Memory
2. Network Interface Card (NIC)
3. Optimized operating system
4. Protocols
5. Storage protocols: ATA (Advanced Technology Attachment),
SCSI, FC (Fibre Channel)
335
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – SAN AND
NAS
The difference between Storage Area Network (SAN) and
Network Attached Storage (NAS) are as follows:
SAN NAS
SAN stands for Storage Area Network. NAS stands for Network Attached Storage.
Data is identified by disk block Data is identified by file name as well as byte offset.
File system is managed by servers File system is managed by Head unit.
It is more costly. It is less expensive than SAN.
It is more complex than NAS. It is less complex than SAN.
Protocols used in SAN are: SCSI, SATA, etc. Protocols used in NAS are: File server, CIFS
(Common Internet File System), etc.
For backups and recovery Block by block For backups and recovery in NAS, Files are used.
copying technique is used.
Gives high performance in high-speed for Not suitable for that environment
high-speed traffic systems.
It has lower latency. Compared to SAN, NAS has higher latency.
SAN supports virtualization. NAS does not support virtualization.
336
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
Disk Scheduling Algorithms
On a typical multiprogramming system, there will usually be
multiple disk access requests at any point of time. So those
requests must be scheduled to achieve good efficiency. Disk
scheduling is similar to process scheduling. Some of the disk
scheduling algorithms are
1. First Come First Serve
2. Shortest Seek time first
3. SCAN algorithm
4. LOOK
5. C-SCAN
6. C-LOOK
337
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
First Come First Serve
This algorithm performs requests in the same order asked by the
system. Let's take an example where the queue has the
following requests with cylinder numbers as follows:
98, 183, 37, 122, 14, 124, 65, 67
Assume the head is initially at cylinder 56. The head moves in
the given order in the queue i.e., 56→98→183→...→67.
338
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
339
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
Shortest Seek Time First (SSTF)
Here the position which is closest to the current head position is
chosen first. Consider the previous example where disk queue
looks like,
98, 183, 37, 122, 14, 124, 65, 67
Assume the head is initially at cylinder 56. The next closest
cylinder to 56 is 65, and then the next nearest one is 67,
then 37, 14, so on.
340
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
341
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
SCAN algorithm
This algorithm is also called the elevator algorithm because of
it's behavior. Here, first the head moves in a direction (say
backward) and covers all the requests in the path. Then it moves
in the opposite direction and covers the remaining requests in
the path. This behavior is similar to that of an elevator. Let's take
the previous example,
98, 183, 37, 122, 14, 124, 65, 67
Assume the head is initially at cylinder 56. The head moves in
backward direction and accesses 37 and 14. Then it goes in the
opposite direction and accesses the cylinders as they come in
the path.
342
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
343
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
LOOK
In this algorithm, the disk arm moves in a particular direction till
the last request is found in that direction and serves all of them
found in the path, and then reverses its direction and serves the
requests found in the path again up to the last request found.
The only difference between SCAN and LOOK is, it doesn't go to
the end it only moves up to which the request is found.
Eg. Suppose the order of requests are 70, 140, 50, 125, 30, 25,
160 and the initial position of the Read-Write head is 60. And it is
given that the disk arm should move towards the larger value.
344
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
346
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
347
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
C-LOOK
This algorithm is also the same as the LOOK algorithm. The only
difference between LOOK and C-LOOK is, it moves in a
particular direction till the last request is found and serves the
requests in its path. Then, it returns in the opposite direction till
the last request is found in that direction and doesn't serve the
request while returning. Then, again reverses the direction and
serves the requests found in the path. It also moves circularly.
Eg. Suppose the order of requests are 70, 140, 50, 125, 30, 25,
160 and the initial position of the Read-Write head is 60. And it is
given that the disk arm should move towards the larger value.
348
Lecture - XV BITS Pilani, Pilani Campus
DISK MANAGEMENT – DISK
SCHEDULING ALGORITHMS
349
Lecture - XV BITS Pilani, Pilani Campus
Learning Objectives
back into the main memory for continued execution. This action
of moving a process out from main memory to secondary
memory is called Swap Out. The action of moving a process out
from secondary memory to main memory is called Swap In.
Paging systems may simply store pages that have been pushed
out of the main memory. The need for swap space on a system
can vary from megabytes to gigabytes. Still, it also depends on
the amount of physical memory, the virtual memory it is backing,
and how it uses the virtual memory.
It is safer to overestimate than to underestimate the amount of
swap space required because if a system runs out of swap
space, it may be forced to abort the processes or may crash
entirely. Overestimation wastes disk space that could be used for357
Lecture - XVI BITS Pilani, Pilani Campus
SWAP SPACE MANAGEMENT
files, but it does not harm others. The following table shows
different systems using the amount of swap space:
S.No. System Swap Space
359
Lecture - XVI BITS Pilani, Pilani Campus
RAID
360
Lecture - XVI BITS Pilani, Pilani Campus
RAID
362
Lecture - XVI BITS Pilani, Pilani Campus
RAID
Non-Redundant Configuration
363
Lecture - XVI BITS Pilani, Pilani Campus
RAID
364
Lecture - XVI BITS Pilani, Pilani Campus
RAID
Mirrored Configuration
365
Lecture - XVI BITS Pilani, Pilani Campus
RAID
RAID – 3 Configuration
367
Lecture - XVI BITS Pilani, Pilani Campus
RAID
368
Lecture - XVI BITS Pilani, Pilani Campus
RAID
369
Lecture - XVI BITS Pilani, Pilani Campus
RAID
370
Lecture - XVI BITS Pilani, Pilani Campus
RAID
RAID 6 Configuration
371
Lecture - XVI BITS Pilani, Pilani Campus
RAID
Advantages of RAID
The advantages are:
• Transfer of large sequential files and graphic images is easier.
• Hardware based implementation is more robust.
• Software based implementation is cost-effective.
• Highest performance and Data protection can be achieved.
• Fault tolerance capacity is high.
• They require less power.
Disadvantages of RAID
The disadvantages include:
• In spite of using this technology, backup software is a must.
• Mapping Logic blocks onto physical locations is complex.
• Data chunk size affects the performance of disk array. 372
Lecture - XVI BITS Pilani, Pilani Campus
RAID - Problems
Problem 1:What is the average access time for transferring 512 bytes
of data with the following specifications-
Average seek time = 5 msec
Disk rotation = 6000 RPM
Data rate = 40 KB/sec
Controller overhead = 0.1 msec
Problem 2:A certain moving arm disk storage with one head has the
following specifications-
Number of tracks per surface = 200
Disk rotation speed = 2400 RPM
Track storage capacity = 62500 bits
Average latency = P msec
Data transfer rate = Q bits/sec
What is the value of P and Q?
373
Lecture - XVI BITS Pilani, Pilani Campus
RAID
Transfer time
= (512 bytes / 40 KB) sec
= 0.0125 sec
= 12.5 msec
375
Lecture - XVI BITS Pilani, Pilani Campus
RAID
377
Lecture - XVI BITS Pilani, Pilani Campus