Operating Systems
Subject 2 of 10 ยท Exact transcription of the original notes, Chapters 1 to 9.
1. OS Basics
1.1 Functions of Operating System
Multiprogramming
Multiprogramming keeps the CPU busy by running multiple processes concurrently. When one process waits for I/O operations, another process can use the CPU.
Core principle: Never let the CPU sit idle when there's work to be done.
How it works:
- Multiple processes loaded in memory simultaneously
- Operating system switches between processes when current process blocks
- Blocked process (waiting for disk, network, etc.) releases CPU to ready process
CPU utilization formula:
CPU Utilization = 1 - p^n
where:
- p = probability that a process is waiting for I/O
- n = number of processes in memory
Example: With 3 processes, each spending 80% time in I/O wait (p = 0.8):
- CPU utilization = 1 - 0.8^3 = 1 - 0.512 = 48.8%
Key benefit: Higher throughput compared to uniprogramming where CPU idles during I/O operations.
Note: Multiprogramming focuses on CPU utilization, while multitasking emphasizes user responsiveness through time-sharing.
Protection and Security
Protection implements the actual mechanisms to enforce access policies, while Security defines the policies for authorizing system access.
Key distinction:
- Security: Prevents intentional misuse through policy definition
- Protection: Prevents both accidental and intentional misuse through mechanism implementation
Security Goals
A secure system must achieve three fundamental objectives:
- Data Confidentiality: Sensitive information remains accessible only to authorized users
- Data Integrity: Unauthorized users cannot modify data without proper permissions
- System Availability: The system remains operational and accessible to legitimate users
Security Components
Security implementation requires three essential components:
- Authentication: Verifies user identity ("Who are you?")
- Confirms the claimed identity of system users
- Uses credentials like passwords, biometrics, or tokens
- Authorization: Determines access permissions ("What can you do?")
- Defines which resources each authenticated user can access
- Specifies the level of access (read, write, execute)
- Enforcement: Ensures compliance with security policies ("Making sure you do only what you're allowed")
- Monitors user actions in real-time
- Blocks unauthorized operations before they occur
Remember: Authentication answers "who", authorization answers "what", and enforcement ensures "compliance".
Security Threat: Superuser Abuse
One of the key functions of an operating system is to protect against security threats. One such threat is Superuser Abuse.
The superuser (root) has unrestricted access to all system resources and can bypass any security mechanism. If a superuser account is compromised or misused, the entire system becomes vulnerable.
Why superuser abuse is critical:
- Can modify any file, including system files and security configurations
- Can access all user data regardless of permissions
- Can disable logging and audit trails to hide malicious activity
- Can install backdoors or malware with system-level privileges
Common abuse scenarios:
- Malicious insider with legitimate superuser access
- Compromised superuser credentials through password attacks
- Privilege escalation exploits that grant unauthorized root access
- Social engineering targeting system administrators
Mitigation strategies:
- Limit the number of users with superuser privileges
- Use 'sudo' for specific administrative tasks instead of full root access
- Implement strong authentication (multi-factor) for privileged accounts
- Regular audit of superuser activities through system logs
- Principle of least privilege - grant minimum necessary permissions
Remember: No technical control can protect against a malicious superuser. Prevention through proper access management and monitoring is essential.
Security Threat: Impostor Attacks
Another security threat is Impostor Attacks.
An impostor attack occurs when an unauthorized user gains system access by masquerading as a legitimate user. The attacker uses stolen credentials, session tokens, or other authentication mechanisms to bypass security controls.
Common impostor techniques:
- Credential theft (passwords, tokens, certificates)
- Session hijacking after legitimate login
- Privilege escalation using compromised accounts
- Social engineering to obtain access credentials
Behavioral monitoring countermeasures:
- Track user activity patterns (login times, locations, commands)
- Monitor resource usage deviations from normal behavior
- Detect unusual file access or system calls
- Flag suspicious network connections or data transfers
Detection indicators:
- Login from unusual locations or devices
- Access to files outside normal user scope
- Commands executed at atypical times
- Abnormal data download volumes
Note: Behavioral monitoring works by establishing baseline user patterns, then alerting on significant deviations that suggest account compromise.
Security Threat: Trojan Horse
A Trojan horse is malicious software disguised as legitimate, harmless programs. Unlike viruses, Trojans don't replicate themselves but rely on users voluntarily executing them.
Key characteristics:
- Appears as useful software (games, utilities, documents)
- Contains hidden malicious payload
- Executes unauthorized actions once run
- Often used for data theft, system access, or installing backdoors
Common attack vectors:
- Email attachments with enticing names
- Software downloads from untrusted sources
- Fake system updates or security alerts
- USB drives with auto-run programs
Defense mechanisms:
Integrity checking - Primary countermeasure that verifies program authenticity:
- Digital signatures validate software origin
- Hash verification detects unauthorized modifications
- Checksum comparison ensures file integrity
Additional protections:
- Antivirus scanning with real-time monitoring
- Application whitelisting (only approved programs run)
- User education about suspicious downloads
- Regular system updates and patches
Example scenario: A user downloads what appears to be a PDF reader, but it secretly installs keylogger software to capture passwords and banking credentials.
Remember: Trojans exploit user trust - always verify software sources and use integrity checking before installation.
Security Threat: Salami Attack
A Salami Attack is a cybersecurity threat where an attacker steals small amounts of data or resources repeatedly, making detection difficult due to the minimal impact of each individual theft.
Attack Method:
- Extract tiny portions of data or computational resources over time
- Each theft is so small it goes unnoticed by monitoring systems
- Accumulates significant gains through repeated micro-thefts
Common Targets:
- Financial systems (stealing fractions of cents from transactions)
- Database records (copying small data chunks)
- System resources (CPU time, memory allocation)
Example: An attacker modifies a banking system to round down all interest calculations and transfer the fractional cents to their account. Each theft is < $1, but across millions of transactions, it becomes substantial.
Detection Challenges:
- Individual incidents fall below audit thresholds
- Appears as normal system variance or rounding errors
- Long-term pattern recognition required
Countermeasures:
- Code reviews: Regular examination of all software modifications
- Audit trails: Log all data access and modifications
- Statistical monitoring: Track patterns in small-value transactions
- Access controls: Limit who can modify critical system components
Remember: The attack succeeds because each slice is too thin to notice, but the whole salami eventually disappears.
Security Threat: Logic Bombs
A logic bomb is malicious code secretly embedded in a legitimate program by an insider. The code remains dormant until triggered by a specific condition, then executes harmful actions.
Common triggers:
- Specific date or time
- User action or system event
- Absence of regular input (like programmer's login)
- File deletion or modification
Typical payloads:
- Data deletion or corruption
- System shutdown or crash
- Unauthorized data access
- Network disruption
Example scenario: A disgruntled programmer inserts code that deletes critical files if they don't log in for 30 consecutive days, ensuring damage occurs after they leave the company.
Prevention measures:
- Code reviews: Multiple developers examine all code changes
- Access controls: Limit who can modify production systems
- Version control: Track all code changes with author identification
- Automated scanning: Use tools to detect suspicious code patterns
- Separation of duties: Different people write, review, and deploy code
Note: Logic bombs are particularly dangerous because they come from trusted insiders with legitimate system access, making them harder to detect than external attacks.
2. Processes and Threads
2.1 Process Concept
Process Concepts
System Call: A request from a user program to the operating system to access system services or resources.
Process: An active instance of a program currently executing in memory. Each process represents a running program with its own memory space and system resources.
| Program | Process |
|---|---|
| Passive entity stored on disk | Active entity in |
| Static code and data | Dynamic execution |
Process Memory Layout
A process in memory consists of four main segments:
Stack:
- Stores function parameters, return addresses, and local variables
- Grows and shrinks dynamically during function calls
- Typically grows downward in memory
Heap (Dynamic Data):
- Used for dynamic memory allocation during runtime
- Memory allocated using malloc(), new, etc.
- Grows upward toward the stack
Data Segment:
- Contains global variables and static data
- Initialized and uninitialized data sections
- Fixed size determined at compile time
Code Segment (Text):
- Contains the actual program instructions
- Read-only machine code
- Shared among multiple instances of the same program
Note: Stack and heap grow toward each other, with available free memory between them.
Process Operations
The operating system performs three main operations on processes:
- Create - Allocate memory, initialize PCB, load program
- Manage - Schedule execution, block/suspend, resume operations
- Terminate - Deallocate resources, remove from memory
Dual Mode Operation
User Mode (Non-privileged):
- Normal program execution environment
- Preemption allowed - OS can interrupt anytime
- Limited access to system resources
- Cannot execute privileged instructions
Kernel Mode (Privileged):
- Operating system execution environment
- Atomic execution - no preemption during critical operations
- Full access to all system resources
- Can execute any processor instruction
Mode switching occurs during system calls, interrupts, or exceptions.
Process Control Block (PCB): Data structure maintained by the OS for each process containing:
- Process ID - Unique identifier
- Memory management - Page table base address, memory limits
- CPU state - Register values, program counter
- I/O information - Open files, allocated devices
- Scheduling data - Priority, state, CPU time used
- Security attributes - User ID, permissions
The PCB enables the OS to suspend and resume processes by saving/restoring their complete execution context.
Inter-process Communication
Independent Processes execute without affecting each other's output or execution order.
Characteristics:
- No shared state between processes
- Scheduling order has no impact on results
- Output remains consistent regardless of execution sequence
Cooperating Processes influence or are influenced by other processes during execution.
Key features:
- Require Inter-Process Communication (IPC) mechanisms for data exchange
- Communication methods include messages, pipes, shared memory, and shared variables
- Enable resource sharing, performance speedup through parallelism, and modular design
Competing Processes simultaneously attempt to access the same shared resource. This creates race conditions where the final outcome depends on the timing of process execution. Proper synchronization mechanisms are needed to manage concurrent access and prevent data corruption.
IPC Benefits:
- Resource sharing: Multiple processes can utilize common data or hardware
- Speedup: Parallel execution of cooperating tasks reduces total time
- Modularity: Complex systems can be broken into communicating components
Note: The distinction between cooperating and competing processes is crucial - cooperation involves intentional data sharing, while competition involves contention for limited resources.
IPC Models
Inter-Process Communication (IPC) enables processes to exchange data and coordinate activities. Two fundamental models exist:
Shared Memory Model:
Processes communicate by reading and writing to a common memory region. The operating system establishes the shared memory segment, then processes access it directly.
Characteristics:
- Fast communication (no system call overhead after setup)
- Requires synchronization mechanisms (semaphores, mutexes)
- Processes must coordinate access to avoid race conditions
Example: Producer writes data to buffer at memory address 0x100, consumer reads from same location. Both processes see updates immediately.
Message Passing Model:
Processes exchange information by sending and receiving messages through the operating system's kernel.
Characteristics:
- Slower than shared memory (system call overhead)
- Built-in synchronization (OS handles message delivery)
- No shared data structure needed
Communication Types
Synchronous vs Asynchronous:
| Type | Sender Behavior |
|---|---|
| Synchronous | Blocks until message delivered |
| Asynchronous | Continues immediately |
Direct vs Indirect:
- Direct Communication: Processes explicitly name each other
send(ProcessId, message)andreceive(ProcessId, message)- Creates point-to-point links between specific processes
- Indirect Communication: Messages sent through intermediate objects (mailboxes, ports)
send(Mailbox, message)andreceive(Mailbox, message)- Multiple processes can share the same mailbox
Note: Indirect communication allows many-to-many relationships, while direct communication creates one-to-one links.
Concurrency
Concurrency enables a system to handle multiple tasks simultaneously, creating the illusion that programs run at the same time even on single-core processors.
Key Benefits:
- Resource Utilization: CPU remains busy while one process waits for I/O operations
- Responsiveness: Users can interact with multiple applications without blocking
- Throughput: More tasks completed per unit time compared to sequential execution
- Performance: Overall system efficiency improves through parallel task execution
How it works: The operating system rapidly switches between processes using time-slicing, giving each process small time intervals to execute. This context switching happens so quickly that users perceive simultaneous execution.
Example: While a text editor saves a file to disk (I/O operation), the OS can switch to a web browser loading a page, then to a music player decoding audio - all appearing to run simultaneously.
Note: True parallelism requires multiple CPU cores, while concurrency can be achieved on single-core systems through intelligent scheduling.
2.2 Process States (New, Ready, Running, Waiting, Terminated)
Process State Diagram
A process transitions through multiple states during its lifecycle in an operating system. Understanding these states and transitions is crucial for process management.
Process States:
New: Process is being created and initialized by the OS.
Ready: Process has all required resources and waits for CPU allocation. Multiple processes can be in ready state simultaneously.
Running: Process is currently executing on the CPU. Only one process per CPU core can be in this state.
Waiting (Blocked): Process waits for an event completion (I/O operation, resource availability, or signal). Multiple processes can wait simultaneously for different events.
Terminated: Process has completed execution and is being cleaned up by the OS.
Suspend Ready: Ready process moved to secondary storage due to memory constraints. Process can be brought back to ready state when memory becomes available.
Suspend Wait: Waiting process moved to secondary storage. Process remains blocked for the event it was waiting for.
State Transitions:
The following transitions control process movement between states:
- Admitted: New -> Ready (OS allocates initial resources)
- Dispatch: Ready -> Running (scheduler assigns CPU)
- Interrupt: Running -> Ready (time slice expires or higher priority process arrives)
- I/O Request: Running -> Waiting (process requests I/O operation)
- I/O Complete: Waiting -> Ready (requested operation finished)
- Exit: Running -> Terminated (process completes or terminates)
- Suspend: Ready -> Suspend Ready OR Waiting -> Suspend Wait (memory pressure)
- Resume: Suspend Ready -> Ready OR Suspend Wait -> Waiting (memory available)
Memory Location:
Main Memory: Processes in Ready, Running, or Waiting states reside in RAM for quick access.
Secondary Storage: Processes in New, Suspended states, or Terminated (cleanup phase) may reside on disk.
Note: Suspended processes are swapped to disk to free main memory for active processes. The suspend/resume mechanism enables multiprogramming with limited physical memory.
Example: A text editor process moves from Ready -> Running when scheduled, then Running -> Waiting when saving a file, and finally Waiting -> Ready when disk write completes.
2.3 Process Control Block (PCB)
Attributes of PCB
The Process Control Block (PCB) stores essential information about each process. Key attributes include:
Process Identification:
- Process ID (PID): Unique identifier assigned to each process
- Parent Process ID (PPID): ID of the process that created this process
Execution State:
- Process State: Current status (new, ready, running, waiting, terminated)
- Program Counter: Address of the next instruction to execute
- CPU Registers: Contents of all processor registers when process was last interrupted
Scheduling Data:
- CPU Scheduling Information: Priority level, scheduling queue pointers, and algorithm-specific parameters
- Accounting Information: CPU time used, time limits, process start time
Memory Details:
- Memory Management Information: Base and limit registers, page tables, or segment tables
- Address Space: Virtual memory layout including code, data, heap, and stack regions
Resource Management:
- I/O Status: List of allocated I/O devices and pending I/O requests
- Open Files: File descriptors and pointers to open file table entries
- User Identification: User ID and group ID of the process owner
Example: When process P1 with PID 1024 gets interrupted, the OS saves its program counter value (0x402C) and register contents in the PCB. When P1 resumes, these values are restored to continue execution from the exact point of interruption.
Note: PCB size varies by operating system - typically 1KB to several KB per process.
2.4 Context Switching
Context Switch
Context Switch is the process of saving the current process state and loading another process state when the CPU switches between processes.
Process involves two steps:
- State Save - Store current process's CPU registers, program counter, and memory management info
- State Restore - Load the new process's saved state back into CPU registers
Context Switch Time = Save Time + Restore Time
Key Characteristic: Context switching is pure overhead - the system performs no useful computation during the switch. The CPU is busy but not doing productive work for any application.
What gets saved/restored:
- Program counter and CPU registers
- Memory management registers (page tables, segment tables)
- Process control block (PCB) information
- Stack pointers and process priority
Performance Impact: Frequent context switches reduce overall system throughput since more time is spent switching than executing actual process code.
Note: Modern processors include hardware support to minimize context switch overhead, but it remains a significant cost in multitasking systems.
2.3 Thread Concept
Problems With Traditional Processes
Traditional processes face several performance and complexity challenges:
Isolated Address Spaces
Each process operates in its own memory space, completely separated from other processes. While this provides security and stability, it creates barriers for inter-process communication and resource sharing.
High Creation and Context Switch Costs
- Process creation requires allocating new memory space, copying page tables, and initializing system resources
- Context switching involves saving/restoring entire process state, including memory mappings
- These operations consume significant CPU cycles and memory bandwidth
Complex Memory Sharing
Sharing data between processes requires explicit mechanisms:
- Shared memory segments with complex setup procedures
- Inter-process communication (IPC) mechanisms like pipes or message queues
- Memory mapping techniques that add overhead
Performance Impact
The combination of these factors makes traditional processes:
- Slow to create compared to lighter alternatives
- Expensive to switch between during multitasking
- Inefficient for applications requiring frequent communication between execution units
Note: These limitations led to the development of threads, which share address space within a process while maintaining separate execution contexts.
Thread
A thread is a lightweight unit of execution within a process. Multiple threads in the same process share common resources while maintaining their own execution context.
Shared Resources
Threads within the same process share:
- Code section (program instructions)
- Data section (global variables)
- Heap memory
- Open files and file descriptors
- Signal handlers
- Process ID and other process attributes
Thread-Specific Resources
Each thread maintains its own:
- Register set (CPU state)
- Stack (local variables and function calls)
- Program counter (current instruction pointer)
- Stack pointer
Key Characteristics
Lightweight execution: Threads require less memory and system resources compared to full processes.
Fast context switching: Switching between threads is faster than switching between processes since threads share the same memory space.
Concurrent execution: Multiple threads can execute simultaneously on multi-core systems, improving performance for parallelizable tasks.
Example Usage
Consider a web browser process:
- One thread handles user interface updates
- Another thread downloads files in background
- A third thread renders web pages
All threads share the same browser code and settings, but each maintains its own execution stack for independent operation.
Remember: Thread creation and switching overhead is significantly lower than process operations, making threads ideal for concurrent programming within a single application.
Benefits of Multithreading
Responsiveness: A multithreaded application can continue running even when part of it is blocked. While one thread waits for I/O operations, other threads can still respond to user input or handle other tasks.
Resource Sharing: Threads within the same process share memory space and system resources by default. This eliminates the need for complex inter-process communication mechanisms required by separate processes.
Economy: Creating and switching between threads requires significantly less overhead than process operations. Thread context switching involves fewer CPU cycles since threads share the same address space.
Multiprocessor Utilization: On systems with multiple CPUs or cores, different threads can execute simultaneously on separate processors, achieving true parallelism and better performance.
Example: In a web browser, one thread handles user interface interactions while another downloads files in the background. The UI remains responsive even during large downloads.
Remember: Thread creation is typically 10-100 times faster than process creation, making multithreading ideal for applications requiring frequent task spawning.
2.4 User-level vs Kernel-level Threads
Difference Between Ult and Klt
User Level Threads (ULT) are managed entirely by application libraries without OS involvement, while Kernel Level Threads (KLT) are managed directly by the operating system.
| Aspect | User Level Threads (ULT) | Kernel Level Threads (KLT) |
|---|---|---|
| Creation | Created by application libraries | Created by the operating system kernel |
| Management | Thread operations handled by the application / thread library | Thread operations handled by the kernel |
| Context Switching | Fastest - no kernel involvement | Slower - requires kernel involvement / system calls |
| Blocking Behavior | Entire process blocks when one thread blocks | Only the blocking thread blocks; other threads continue |
Key Trade-offs
ULT Advantages:
- Extremely fast thread creation and switching
- No system call overhead for thread operations
- Portable across different operating systems
ULT Disadvantages:
- Cannot utilize multiple CPU cores effectively
- One blocking thread stops the entire process
- No true parallelism within a process
KLT Advantages:
- True parallelism on multi-core systems
- Individual thread blocking doesn't affect others
- Better for I/O-intensive applications
KLT Disadvantages:
- Higher overhead for thread operations
- More memory consumption per thread
- System call required for thread management
Example: In a web server with ULT, if one thread waits for disk I/O, all request handling stops. With KLT, other threads continue serving requests while one waits for I/O.
2.5 Multithreading Models (One-to-One, Many-to-One, Many-to-Many)
Multithreading Models
Many-to-One Model
- Maps multiple user-level threads to a single kernel thread
- All user threads share one kernel thread for execution
- Limitation: Cannot achieve true parallelism on multicore systems since only one thread can access the kernel at a time
- Advantage: Low overhead for thread creation and management
One-to-One Model
- Each user thread has a dedicated kernel thread
- Direct mapping provides better concurrency support
- Advantage: True parallelism on multiprocessor systems - threads can run simultaneously on different cores
- Limitation: Higher overhead due to kernel thread creation for each user thread
Many-to-Many Model
- Maps m user threads to n kernel threads where
| Model | User Threads | Kernel Threads |
|---|---|---|
| Many-to-One | Many | 1 |
| One-to-One | Many | Many |
| Many-to-Many | Many | Few |
Note: The choice depends on whether you prioritize performance (one-to-one) or resource efficiency (many-to-one), with many-to-many offering a balanced approach.
3. CPU Scheduling
3.1 Scheduling Criteria (Turnaround, Waiting, Response Time)
Scheduler
A scheduler manages which process runs on the CPU by removing the currently executing process and selecting the next process from the ready queue.
Primary objectives of CPU scheduling:
- Minimize waiting time: Reduce the total time processes spend waiting in the ready queue
- Maximize throughput: Increase the number of processes completed per unit time
- Ensure fairness: Provide equitable CPU access to all processes, preventing starvation
Key scheduler responsibilities:
- Process selection from ready queue
- Context switching between processes
- Maintaining scheduling queues
- Enforcing time quantum limits (in preemptive scheduling)
Performance metrics schedulers optimize:
- Average waiting time
- Average turnaround time
- CPU utilization percentage
- Response time for interactive systems
Note: Different scheduling algorithms prioritize different objectives. For example, Round Robin emphasizes fairness, while Shortest Job First minimizes average waiting time.
Scheduling Criteria
CPU scheduling algorithms are evaluated based on five key performance metrics:
CPU Utilization
Percentage of time the CPU is actively executing processes. Higher utilization means better resource usage.
- Target: Keep CPU busy 40-90% in real systems
- Idle time reduces overall system efficiency
Throughput
Throughput = Processes Completed / Time Period
- Higher throughput indicates better system performance
- Measured in processes per second or per minute
Turnaround Time
Total time from process arrival to completion:
Turnaround Time = Completion Time - Arrival Time
- Includes waiting time, execution time, and I/O time
- Lower turnaround time means faster process completion
Waiting Time
Time a process spends in the ready queue waiting for CPU:
Waiting Time = Turnaround Time - Burst Time
- Does not include actual execution time
- Key metric for user satisfaction
Response Time
Time from process arrival until it first gets CPU access:
Response Time = First Response Time - Arrival Time
- Critical for interactive systems
- Different from turnaround time in preemptive scheduling
Note: Burst Time is the actual CPU execution time required by a process.
3.2 Priority Scheduling
Starvation
Starvation occurs when a process waits indefinitely for CPU time and never gets scheduled to run.
Common causes:
- High-priority processes continuously arriving, blocking low-priority ones
- Unfair scheduling algorithms that favor certain process types
- Resource allocation policies that consistently bypass some processes
Which algorithms cause starvation:
- Priority Scheduling (non-preemptive) - low priority processes may never execute
- Shortest Job First (SJF) - long processes starved by continuous short jobs
Prevention techniques:
- Aging: Gradually increase priority of waiting processes over time
- Fair share scheduling: Guarantee minimum CPU time for all processes
- Time limits: Set maximum wait time before forced scheduling
Example scenario: Process P1 has priority 1 (low), but processes with priority 5 (high) might keep arriving. Without aging, P1 may wait forever while high-priority processes execute first.
Note: Starvation is different from deadlock - starved processes can potentially run if conditions change, while deadlocked processes cannot proceed at all.
3.3 Round Robin Scheduling
Time Sharing
Time sharing enables multiple users to interact with their programs simultaneously by rapidly switching CPU time between processes.
Primary Goals:
- Minimize response time for interactive tasks
- Provide illusion that each user has dedicated system access
- Maintain system responsiveness under multi-user load
Key Principle: CPU switches between processes so quickly (typically every 10-100 milliseconds) that users perceive their programs as running continuously.
Response Time Requirements:
- Interactive commands: < 1 second
- Simple queries: < 10 milliseconds
- Complex operations: Progress indication within seconds
Implementation: Uses preemptive scheduling algorithms like Round Robin, where each process gets a small time slice before CPU switches to the next process.
Trade-off: Frequent context switching overhead vs. improved user experience and system utilization.
3.4 Preemptive vs Non-preemptive Scheduling
Scheduling Queues
CPU scheduling uses three main queues to organize processes based on their current state:
Job Queue
Contains all processes in the system, regardless of their current state. When a new process is created, it enters the job queue first before moving to other queues.
Ready Queue
Holds processes that are loaded in main memory and ready for CPU execution. These processes are waiting for the CPU scheduler to allocate processor time. The ready queue is typically organized as a priority queue or FIFO queue depending on the scheduling algorithm.
Device Queues
Each I/O device maintains its own queue of processes waiting for that specific device. When a process requests I/O operation, it moves from the ready queue to the appropriate device queue.
Process Flow:
- New process -> Job queue
- Admitted to memory -> Ready queue
- CPU allocated -> Running state
- I/O request -> Device queue -> Back to ready queue when I/O completes
Note: A process may move between ready queue and device queues multiple times during its execution, but remains in the job queue until termination.
Types of Schedulers
Operating systems use three types of schedulers to manage process execution at different levels:
Long-term Scheduler (Job Scheduler)
Controls the degree of multiprogramming - the number of processes allowed in memory simultaneously.
Function: Moves processes from New -> Ready state.
Key decisions:
- Which jobs from the job pool should be loaded into memory
- Maintains optimal balance between CPU-bound and I/O-bound processes
- Executes less frequently (seconds or minutes)
Example: If system has 4GB RAM and each process needs 500MB, long-term scheduler ensures only 6-7 processes are in memory, keeping 1-2GB free for OS operations.
Short-term Scheduler (CPU Scheduler)
Decides which process from the ready queue gets CPU time next.
Function: Moves processes from Ready -> Running state.
Characteristics:
- Executes very frequently (milliseconds)
- Must be extremely fast since it runs after every time slice
- Uses scheduling algorithms like Round Robin, Priority, SJF
Example: With processes P1, P2, P3 in ready queue, CPU scheduler picks P2 based on priority or time slice completion.
Medium-term Scheduler (Swapper)
Manages memory by temporarily removing processes to reduce multiprogramming degree.
Functions:
- Running -> Suspended Ready (process swapped out while running)
- Waiting -> Suspended Waiting (blocked process moved to disk)
- Later resumes processes to continue execution from where they stopped
Purpose: Frees memory when system is overloaded, then brings processes back when resources are available.
Note: Uses swapping technique - stores process image on disk and reloads it later without losing execution context.
Dispatcher
The dispatcher is the OS module that transfers CPU control to the process chosen by the CPU scheduler.
Core Functions:
- Context switching: Save current process state, load new process state
- Mode switching: Change from kernel mode to user mode
- Program restart: Jump to the correct instruction in the user program
Dispatch Latency is the time overhead required to:
- Stop the currently running process
- Start the newly selected process
This latency directly impacts system performance - lower dispatch latency means more efficient process switching and better overall throughput.
Key Point: The dispatcher executes during every context switch, making it one of the most frequently called OS components. Minimizing its execution time is critical for system responsiveness.
CPU Scheduling Algorithms
CPU scheduling algorithms determine how processes are allocated processor time. Each algorithm has different characteristics regarding preemption, priority, and fairness.
Non-Preemptive Algorithms
First Come First Serve (FCFS)
- Processes execute in arrival order
- Simple but can cause convoy effect (short jobs wait behind long running processes)
- Average waiting time increases significantly when long processes arrive first
Shortest Job First (SJF)
- Selects process with shortest burst time
- Minimizes average turnaround time (optimal for this metric)
- Starvation risk: Long processes may never execute
- Solution: Aging - gradually increase priority of waiting processes
Longest Job First (LJF)
- Opposite of SJF, selects longest burst time first
- Poor performance, mainly used for comparison
Highest Response Ratio Next (HRRN)
- Selects process with highest response ratio:
Response Ratio = (Waiting Time + Burst Time) / Burst Time
- Prevents starvation by considering waiting time
- Balances between SJF efficiency and fairness
Preemptive Algorithms
Shortest Remaining Time First (SRTF)
- Preemptive version of SJF
- Switches to newly arrived shorter jobs
- Optimal for average waiting time but causes starvation
Longest Remaining Time First (LRTF)
- Preemptive version of LJF
- Poor performance, rarely used in practice
Round Robin (RR)
- Each process gets fixed time quantum
- Time quantum effects:
- Smaller quantum -> more context switches, better response time
- Larger quantum -> approaches FCFS behavior
- Fair allocation, prevents starvation
Priority Scheduling
- Can be preemptive or non-preemptive
- Higher priority processes execute first
- Risk of starvation for low-priority processes
Advanced Scheduling
Multilevel Queue Scheduling
- Separate queues for different process types
- Queue 1: System processes (highest priority)
- Queue 2: Interactive processes (medium priority)
- Queue N: Background processes (lowest priority)
- Each queue uses different scheduling algorithm
- Fixed priorities between queues
Multilevel Feedback Queue
- Processes can move between priority levels:
- New jobs start in highest priority queue
- If time slice expires -> demote to lower queue
- If job completes within slice -> promote to higher queue
- Adapts to process behavior automatically
Lottery Scheduling
- Assigns lottery tickets to processes
- Random selection proportional to ticket count
- Provides probabilistic fairness guarantee
Starvation Analysis
Read as: Algorithm can cause indefinite postponement of processes.
| Algorithm | Starvation Risk |
|---|---|
| FCFS | No |
| SJF | Yes |
| SRTF | Yes |
| Round Robin | No |
| LJF | Yes |
| LRTF | Yes |
| Priority (both types) | Yes |
| HRRN | No |
| Multilevel Queue | Yes |
| Multilevel Feedback | No |
Note: Algorithms with starvation risk need aging or similar techniques to ensure fairness.
4. Process Synchronization
4.1 Critical Section Problem
Synchronization
Process synchronization uses atomic operations to coordinate access to shared resources between multiple processes.
Critical Section Problem
A critical section is any portion of code where processes access shared resources like files, variables, or hardware devices.
The synchronization mechanism acts as a gatekeeper:
- Checks if the critical section is available
- Allows only one process to enter at a time
- Notifies waiting processes when the section becomes free
Flow: Process requests access -> Synchronization check -> Enter critical section -> Execute -> Exit and notify others
Race Condition
When multiple processes access shared data simultaneously, the final result depends on the timing of their execution. This unpredictable outcome is called a race condition.
Example: Two processes incrementing a shared counter x = 5:
- Process A reads x = 5, calculates 5 + 1 = 6
- Process B reads x = 5, calculates 5 + 1 = 6
- Both write 6 instead of the expected 7
Synchronization Requirements
1. Mutual Exclusion
Only one process can be in the critical section at any time.
2. Progress
If the critical section is empty, any interested process should be able to enter immediately. No process outside the critical section should block others.
3. Bounded Waiting
Every process must eventually get access to the critical section. No process should wait indefinitely.
Consequences of Poor Synchronization
- Data inconsistency: Shared variables contain incorrect values
- Data loss: Updates get overwritten by concurrent access
- Deadlock: Processes wait indefinitely for each other
Basic Locking Mechanisms
Test-and-Set Operation: Atomic instruction that reads a lock variable and sets it to true in one step.
Busy Waiting: Process continuously checks if the critical section is available (wastes CPU cycles).
Spin Locks: Lock mechanism where waiting processes "spin" in a loop, repeatedly checking the lock status.
Note: While simple, busy waiting and spin locks are inefficient as they consume CPU time even when waiting.
Test and Set Hardware Instructions
Test-and-Set is a hardware-supported atomic instruction used for mutual exclusion in concurrent systems. It combines two operations into a single, indivisible unit.
Operations: Test: Check if the resource lock is currently held Set: Atomically acquire the lock if it's free
How Test-and-Set Works The process follows this flow:
- Test the lock status
- If busy โ enter wait state and retry
- If free โ atomically set the lock and proceed
- Enter critical section with exclusive access
Implementation The Test-and-Set function returns the previous lock value while setting it:
Boolean Test_And_Set(lock) {
if (lock == TRUE) {
return TRUE; // Lock was
}
else {
lock = TRUE; // Acquire
return FALSE; // Lock was
}
}
Usage Pattern Processes use busy-waiting to acquire the lock:
while (Test_And_Set(lock)) {
// Busy wait - do nothing
}
// Critical section access
execute_critical_code();
lock = FALSE; // Release lock
Key Properties
- Atomic: Test and set operations happen as one indivisible instruction
- Returns previous state: Function returns TRUE if lock was busy, FALSE if successfully acquired
- Busy waiting: Process continuously polls until lock becomes available
- Hardware support: Requires special CPU instruction for atomicity
Note: The atomicity guarantee prevents race conditions where multiple processes might simultaneously see the lock as free and both acquire it.
4.2 Peterson's Solution
Petersons Solution for Two Processes and One Shared Resource
Peterson's Solution is a software-based approach to achieve mutual exclusion between two processes sharing a single resource. It uses two shared variables to coordinate access without requiring hardware support.
Shared Variables
boolean flag[2] = {false, false}; //
int turn = 0; //
flag[i]indicates if process i wants to enter critical sectionturndetermines whose turn it is when both processes want access
Algorithm Structure Process i (where j = 1 - i):
// Entry section
flag[i] = true; // Show interest
turn = j; // Give priority
while(flag[j] && turn == j); // Wait
// Critical section
// ... critical code ...
// Exit section
flag[i] = false; // No longer interested
How It Works
- Declare interest: Process sets its flag to 'true'
- Be polite: Process sets 'turn' to favor the other process
- Wait if needed: Process waits only if:
- Other process is interested (
flag[j] == true) AND - It's the other process's turn (
turn == j)
- Enter safely: If other process isn't interested OR it's our turn, proceed
- Exit cleanly: Reset flag to 'false' when done
Key Properties
Mutual Exclusion: Guaranteed because both processes can't satisfy the while condition simultaneously. If both are interested, only one will have turn in its favor.
Progress: No deadlock occurs. If one process isn't interested (flag[j] == false), the other proceeds immediately.
Bounded Waiting: A process waits at most one turn. After the other process exits, turn will eventually favor the waiting process.
Example Scenario:
- Process 0 wants access: sets
flag[0] = true,turn = 1 - Process 1 also wants access: sets
flag[1] = true,turn = 0 - Process 1 waits (since
flag[0] == trueandturn == 0) - Process 0 enters critical section
- Process 0 exits: sets
flag[0] = false - Process 1 now proceeds (condition
flag[0] && turn == 0becomes false)
Note: Peterson's solution assumes atomic read/write operations on shared variables and may not work correctly on modern processors without memory barriers due to instruction reordering.
Peterson's Algorithm
Peterson's Algorithm is a software-based solution for mutual exclusion between two processes accessing a shared resource.
Algorithm Structure
int turn;
int interested[2] = {FALSE, FALSE};
void entry_section(int process) {
int other = 1 - process;
interested[process] = TRUE;
turn = process;
while (interested[other] == TRUE && turn == process)
{
}
}
// Critical section executes here
void exit_section(int process) {
interested[process] = FALSE;
}
How It Works
Entry protocol:
- Process declares interest:
interested[process] = TRUE - Process gives turn to other:
turn = process - Process waits if other is interested AND it's still the process's turn
Exit protocol:
- Process declares no interest:
interested[process] = FALSE
The algorithm ensures that if both processes want to enter, the one that set turn last will wait, giving priority to the other process.
Key Properties
- Mutual exclusion: Only one process in critical section at a time
- Progress: If no process is in critical section, one waiting process will enter
- Bounded waiting: Each process waits at most one turn
Limitations
- Two processes only: Cannot extend to n > 2 processes
- Busy waiting: Process continuously checks condition in loop, wasting CPU cycles
- Priority inversion: High priority process may wait for low-priority process
- No OS support: Relies purely on software logic without hardware assistance
Note: Modern systems prefer hardware-based solutions like atomic operations or OS primitives like semaphores to avoid busy waiting.
4.3 Semaphores (Binary and Counting)
Semaphore
A semaphore is a synchronization primitive that controls access to shared resources through a counter variable.
Types of Semaphores
Binary Semaphore: Takes values 0 or 1, acts like a mutex lock
Counting Semaphore: Takes non-negative integer values, manages multiple resource instances
Semaphore Operations
Wait (P/Down): Executed before entering critical section
- Decrements semaphore value by 1
- Blocks process if resource unavailable
Signal (V/Up): Executed after leaving critical section
- Increments semaphore value by 1
- Releases acquired resource
Both operations execute atomically to prevent race conditions.
Binary Semaphore Initial value: s = 1
wait(S): signal(S):
while (S == 0); S++;
S--;
Limitations:
- Uses busy waiting (spin lock) - wastes CPU cycles
- Works only for single resource instance
- Only one process can complete wait operation [from continuation in next image]
Counting Semaphore Initial value: s = n (number of available resource instances)
wait(S): signal(S):
S--; S++;
if (S < 0) { if (S <= 0)
// block process and place in waiting queue
}
- 'negative' n processes waiting in queue [line positioned directly below the code block in the screenshot]
Semaphore Value Interpretation:
- Positive: Number of free resource instances, no waiting processes
- Zero: All resources allocated, no waiting processes
- Negative: 'n' processes waiting in queue
Example: Printer pool with 3 printers
- Initial: s = 3
- After 2 allocations: s = 1 (1 printer free)
- After 4 allocation requests: s = -1 (1 process waiting)
Key Points
Atomic execution: Semaphore operations cannot be interrupted, preventing race conditions
Proper ordering: When using multiple semaphores, maintain consistent order across all processes to avoid deadlock
No busy waiting: Counting semaphores block processes instead of spinning, improving CPU efficiency
4.4 Mutex Locks
Spinlock and Busy Waiting
A spinlock is a synchronization mechanism where a thread attempting to acquire a lock continuously polls (spins) in a loop until the lock becomes available.
Mechanism When a thread requests a spinlock:
- Check if lock is free
- If locked, keep checking repeatedly
- Continue until lock is acquired
The thread remains active throughout this process but performs no useful work - this is called busy waiting.
Characteristics
- CPU-intensive: Consumes processor cycles while waiting
- No context switching: Thread stays scheduled and running
- Fast acquisition: No overhead when lock becomes free
- Polling-based: Continuously tests lock status
When to Use Effective for:
- Short critical sections (microseconds)
- Multiprocessor systems with spare CPU cores
- Real-time systems requiring predictable timing
Avoid when:
- Long wait times expected
- Single processor systems
- Limited CPU resources available
Implementation Pattern
while (lock == LOCKED) {
// Spin - do nothing but check
}
lock = LOCKED; // Acquire lock
// Critical section
lock = UNLOCKED; // Release lock
Note: Modern implementations use atomic operations like Test_And_Set() to avoid race conditions during acquisition.
Trade-offs Advantages: No scheduling overhead, immediate response when lock frees Disadvantages: Wastes CPU cycles, can cause priority inversion on single-core systems
4.5 Producer-Consumer Problem
Classical Problems on Synchronization Using Semaphore
The Producer-Consumer Problem demonstrates synchronization between processes that share a bounded buffer.
Setup:
- Producer processes generate data items
- Consumer processes consume data items
- Shared buffer with fixed capacity n
- Multiple producers and consumers can exist
Synchronization Requirements:
- Producer must wait if buffer is full
- Consumer must wait if buffer is empty
- Only one process can access buffer at a time (mutual exclusion)
Semaphore Solution:
semaphore mutex = 1 // Mutual exclusion
semaphore empty = n // count of empty slots
semaphore full = 0 // count of filled slots
Producer Process:
wait(empty)- ensure empty slot availablewait(mutex)- acquire exclusive buffer access- Add item to buffer
signal(mutex)- release buffer accesssignal(full)- increment filled slot count
Consumer Process:
wait(full)- ensure filled slot availablewait(mutex)- acquire exclusive buffer access- Remove item from buffer
signal(mutex)- release buffer accesssignal(empty)- increment empty slot count
Key Insight: The empty and full semaphores track resource availability, while mutex ensures atomic buffer operations.
Deadlock Prevention: Always acquire counting semaphores (empty / full) before the mutex semaphore to avoid circular wait conditions.
4.6 Readers-Writers Problem
Reader Writer Problem
The Reader-Writer Problem manages concurrent access to shared data where multiple readers can access simultaneously, but writers need exclusive access.
Access Rules
Multiple readers allowed: Any number of readers can access the shared resource simultaneously since reading doesn't modify data.
Reader priority over writer: When readers are active, new readers can join immediately, but writers must wait.
Writer exclusivity: When a writer is active, no other readers or writers are permitted.
Lock Types
- Shared Lock: Used by readers - multiple processes can hold this simultaneously
- Exclusive Lock: Used by writers - only one process can hold this at a time
Dining Philosophers Problem A classic synchronization problem with N (5) philosophers sitting around a circular table, each needing two forks to eat.
Solution Strategies Strategy 1: Sequential Fork Acquisition
- First N - 1 philosophers using left-then-right fork order
- Remaining 1 philosopher uses right-then-left fork order
- Prevents circular wait by breaking symmetry
Strategy 2: Parity-Based Approach
- Odd-numbered philosophers: Pick left fork first, then right fork
- Even-numbered philosophers: Pick right fork first, then left fork
- Achieves maximum concurrency by alternating acquisition patterns
Key Insight: Both solutions prevent deadlock by ensuring at least one philosopher uses a different fork acquisition order, breaking the circular dependency that causes all philosophers to wait indefinitely.
Remember: The core principle is asymmetry - having different acquisition orders prevents the circular wait condition that leads to deadlock.
4.7 Monitors
Monitor
A monitor is a high-level synchronization construct that encapsulates shared data and the operations that manipulate it, ensuring thread-safe access through built-in mutual exclusion.
Key Properties
- Mutual exclusion: Only one process can execute inside the monitor at any time
- Data encapsulation: Internal variables are accessible only through monitor procedures
- Condition synchronization: Built-in condition variables handle waiting and signaling
Structure A monitor consists of:
- Shared variables: Data structures protected by the monitor
- Procedures: Operations that can access the shared variables
- Condition variables: For process coordination and waiting
External processes cannot directly access monitor variables - they must call monitor procedures to interact with the data.
How It Works
Monitor = Lock + Condition Variables + Shared Data
The monitor automatically provides:
- Lock acquisition when a process enters any monitor procedure
- Lock release when the process exits or waits on a condition
- Condition queuing for processes that need to wait
Condition Variables Condition variables allow processes to:
- Wait: Suspend execution until a condition becomes true
- Signal: Wake up one waiting process
- Broadcast: Wake up all waiting processes
Example: Buffer monitor with condition variables not_full and not_empty to coordinate producer-consumer operations.
Advantage Over Semaphores Monitors separate concerns:
- Mutual exclusion: Handled automatically by monitor entry/exit
- Condition synchronization: Managed explicitly through condition variables
This reduces programming errors compared to manual semaphore coordination.
5. Deadlocks
5.1 Deadlock Conditions (Mutual Exclusion, Hold & Wait, No Preemption, Circular Wait)
What is Deadlock?
A deadlock occurs when two or more processes are permanently blocked, each waiting for an event that can only be triggered by another process in the same set.
Key characteristics:
- Minimum 2 processes required
- Each process holds resources while waiting for others
- No process can proceed without external intervention
- The waiting condition forms a circular dependency
Simple example: Process A holds Resource 1 and waits for Resource 2, while Process B holds Resource 2 and waits for Resource 1. Neither can proceed.
Note: Deadlock is different from starvation - in deadlock, NO process makes progress, while in starvation, some processes advance but others are indefinitely delayed.
Necessary Conditions for Deadlock
For deadlock to occur in a system, all four conditions must be present simultaneously:
- Mutual Exclusion
Only one process can use a resource at any given time. The resource cannot be shared among multiple processes concurrently.
- Hold and Wait
A process holds at least one resource while waiting to acquire additional resources that are currently held by other processes. Example: Process A has allocated printer and waits for scanner, while process B has scanner and waits for printer.
- No Preemption
Resources cannot be forcibly taken away from a process. A process must voluntarily release its resources only after completing its task.
- Circular Wait
A circular chain of processes exists where each process holds a resource needed by the next process in the chain. Formal representation:
P1 โ R1 โ P2 โ R2 โ P3 โ ... โ Rn โ P1
Circular dependency pattern:
- Process P1 holds resource R1 and waits for R2
- Process P2 holds resource R2 and waits for R3
- Process P3 holds resource R3 and waits for R1
- This continues until process Pn holds Rn and waits for R1
Key insight: Breaking any one of these four conditions prevents deadlock. Most deadlock prevention algorithms work by ensuring at least one condition cannot occur.
Remember: All four conditions are necessary - if any single condition is absent, deadlock cannot happen.
5.2 Deadlock Prevention
Strategies for Deadlock Handling
Operating systems handle deadlocks using four main strategies:
- Prevention
Eliminate one of the four necessary conditions for deadlock:
- Mutual Exclusion: Make resources shareable (not always possible)
- Hold and Wait: Require processes to request all resources at once
- No Preemption: Allow forcible resource removal from processes
- Circular Wait: Impose ordering on resource types
Trade-off: Prevention reduces system efficiency and resource utilization.
- Avoidance
Use algorithms to ensure the system never enters an unsafe state:
- Banker's Algorithm: Check if resource allocation leads to safe state
- Resource Allocation Graph: Detect potential cycles before they form
Requirement: Must know maximum resource needs in advance Example: If Process A needs 3 printers max and currently holds 1, only allocate 2 more if system remains in safe state.
- Detection and Recovery
Allow deadlocks to occur, then detect and resolve them:
Detection methods:
- Wait-for graphs for single-instance resources
- Resource allocation matrices for multiple-instance resources
Recovery options:
- Terminate one or more deadlocked processes
- Preempt resources from selected processes
- Rollback processes to earlier safe state
- Ignore (Ostrich Algorithm)
Assume deadlocks are rare and ignore the problem entirely. Rationale: Cost of prevention/detection exceeds cost of occasional system restart. Usage: Common in personal computers where user can manually restart if needed.
Note: Most modern operating systems use a combination of these strategies depending on the resource type and system requirements.
Prevention
Deadlock prevention eliminates at least one of the four necessary conditions for deadlock to occur.
Prevention Strategies
Mutual Exclusion Prevention
- Provide infinite resources so no competition exists
- Make all resources shareable when possible
- Limitation: Some resources like printers cannot be shared
Hold and Wait Prevention
- All-or-nothing allocation: Process must request all needed resources at once
- No partial allocation: If any resource unavailable, release all held resources
- Example: Database transaction requests all required locks before starting
No Preemption Prevention
- Allow forcible removal of resources from processes
- If process P2 needs resource held by P1, preempt from P1
- Limitation: Only works with resources that can save/restore state (CPU, memory)
Circular Wait Prevention
- Resource ordering: Assign unique numbers to all resource types
- Ordering rule: Process can only request resource Ri if i > highest numbered resource currently held
- Example: If holding printer (resource 3), can only request scanner (resource 5), not keyboard (resource 1)
Implementation Notes: Combined approach often used in practice:
- Banker's algorithm for some resources
- Resource ordering for others
- Preemption for CPU scheduling
Trade-off: Prevention reduces system efficiency but guarantees deadlock-free operation.
5.3 Banker's Algorithm
Avoidance Through Banker's Algorithm
The Banker's Algorithm prevents deadlock by checking if resource allocation requests lead to safe states.
Safe State: A state where all processes can complete execution by finding at least one safe sequence.
Algorithm Steps:
- Request Check: When process Pi requests resources, verify if request < available resources
- Tentative Allocation: Temporarily allocate the requested resources
- Safety Check: Run safety algorithm to check if system remains in safe state
- Decision: If safe, grant request; otherwise, make process wait
Safety Algorithm:
- Initialize work vector = available resources
- Mark all processes as unfinished
- Find process Pi where Need โค Work
- If found: Work = Work + Allocation of Pi, mark Pi as finished
- Repeat until all processes finished (safe) or no such process exists (unsafe)
Data Structures:
- Available: Vector of available instances for each resource type
- Max: Matrix defining maximum demand of each process
- Allocation: Matrix defining currently allocated resources
- Need: Matrix where Need[i][j] = Max[i][j] - Allocation[i][j]
Example: 3 processes, 3 resource types
- If P1 requests (1,0,2) and available = (3,3,2)
- Check: (1,0,2) < (3,3,2) โ
- Tentatively allocate and verify safe sequence exists
Key Insight: Algorithm ensures that granting a request won't lead to a state where processes are permanently blocked waiting for resources.
Limitation: Requires advance knowledge of maximum resource requirements for all processes.
Safe State and Safe Sequence
A system is safe if all processes can complete execution using available resources in some sequential order.
Safe Sequence: An ordering of processes where each process can obtain its required resources and finish execution without causing deadlock.
Key Properties:
- Multiple safe sequences may exist at any time
- If no safe sequence exists, the system is in an unsafe state
- Unsafe state doesn't guarantee deadlock, but makes it possible
Resource Need Calculation
Need = Max โ Allocation
where:
- Max = maximum resources a process may request
- Allocation = resources currently allocated to the process
- Need = additional resources required for completion
Banker's Algorithm Components (for multiple resource instances):
- Resource Request Algorithm: Checks if a resource request can be safely granted
- Verifies request doesn't exceed declared maximum
- Simulates allocation and tests system safety
- Safety Algorithm: Determines if current system state is safe
- Finds processes that can complete with available resources
- Iteratively marks processes as finished until all complete or deadlock detected
Remember: Safety check must be performed before granting any resource request to prevent deadlock.
5.4 Deadlock Detection
Cycles in Resource Allocation Graph
Resource Allocation Graph (RAG) and Deadlock Detection
The relationship between cycles in RAG and deadlock depends on resource instance counts:
Single Instance Resources:
- Cycle in RAG = Deadlock guaranteed
- Cycle is both necessary AND sufficient condition
- If cycle exists โ deadlock present
- If no cycle โ no deadlock
Multiple Instance Resources:
- Cycle in RAG = Possible deadlock (not guaranteed)
- Cycle is only a necessary condition
- Deadlock can exist without visible cycle in RAG
- Additional analysis needed beyond cycle detection
Key Insight: With single instances, processes form simple wait chains. With multiple instances, a process might wait for one instance while another instance of the same resource becomes available, breaking the deadlock.
Example: Process P1 waits for resource R1 (2 instances), P2 holds 1 instance of R1 and waits for R2. Even if this forms a cycle, P1 might get the second instance of R1, avoiding deadlock.
Detection and Recovery
Deadlock detection and recovery is used when prevention and avoidance are not feasible. The system periodically checks for deadlocks and takes corrective action when found.
Detection Methods:
Single Instance Resources: Use wait-for graph
- Simplified version of resource allocation graph
- Shows only process dependencies
- Deadlock exists if cycle is found
Multiple Instance Resources: Use resource allocation matrix
- Track available, allocated, and requested resources
- Apply Banker's algorithm in reverse
- More complex but handles multiple resource instances
When to Run Detection:
Detection algorithms consume CPU time, so timing matters:
- CPU utilization drops significantly - processes may be blocked waiting
- Most processes are in blocked state - strong deadlock indicator
- Periodic intervals - every few seconds or minutes
- On resource request - check before granting resources
Recovery Strategies:
Once deadlock is detected, the system must break it:
Process Termination:
- Abort all deadlocked processes (drastic but simple)
- Abort one process at a time until deadlock breaks
Resource Preemption:
- Select a victim process and take its resources
- Rollback the victim to a safe state
- Restart the victim process later
Selection Criteria for victim process:
- Priority level (terminate lower priority first)
- Computation time completed
- Resources currently held
- Resources needed to complete
Note: Recovery often involves restarting processes, so the system must maintain checkpoints or safe states for rollback.
5.5 Deadlock Recovery
Deadlock Recovery
When a deadlock occurs, the system must recover by breaking the deadlock cycle. Two main approaches exist:
Process Termination
Method 1: Abort all deadlocked processes
- Immediate solution but wasteful
- All work done by terminated processes is lost
- Simple to implement
Method 2: Abort one process at a time
- Continue until deadlock cycle breaks
- Less wasteful but requires repeated deadlock detection
- Choose victim based on priority, completion time, or resource usage
Resource Preemption
Forcibly take resources from some processes and reassign them to break the cycle.
Three key considerations:
- Victim Selection: Choose which process loses its resources
- Consider process priority and execution time
- Minimize cost of preemption
- Avoid repeatedly selecting the same victim
- Rollback: Return the preempted process to a safe state
- Process must restart from a checkpoint
- May lose significant computation work
- Requires maintaining process state snapshots
- Starvation Prevention: Ensure no process is repeatedly victimized
- Track preemption count per process
- Include preemption history in victim selection
- Set maximum preemption limits
Deadlock-Free Resource Allocation:
To guarantee no deadlocks occur, ensure sufficient resources:
r โฅ p(s โ 1) + 1
where:
- r = total available resources of one type
- p = number of processes
- s = maximum resources each process needs
Example: If 4 processes each need at most 3 units of a resource:
- r = 4(3 โ 1) + 1 = 9 units required
- With 8 units, deadlock is possible
- With 9 units, deadlock cannot occur
Note: Recovery methods are expensive. Prevention and avoidance are preferred when possible.
---
CHAPTER 6
6. Memory Management
6.1 Logical vs Physical Address Space
Dynamic Loading
Dynamic loading is a memory management technique where program routines and libraries are loaded into memory only when needed, rather than at program startup.
Key characteristics:
- Routines remain in relocatable format on disk until called
- Memory is allocated only when a function is actually invoked
- Unused routines never consume memory space
How it works:
- Program starts with minimal memory footprint
- When a routine is called for the first time, the loader fetches it from disk
- Routine is loaded into available memory space
- Subsequent calls use the already-loaded routine
Benefits:
- Reduced initial memory usage
- Better memory utilization for large programs
- Faster program startup time
- Supports programs larger than available physical memory
Example: A text editor with spell-check feature
- Main editing functions load immediately
- Spell-check library loads only when user runs spell-check
- Dictionary files load only for specific languages being checked
Note: Different from dynamic linking - dynamic loading happens at runtime based on program flow, while dynamic linking resolves external references at load time.
Dynamic Linking
Dynamic linking postpones the linking process until program execution, rather than creating all connections when the executable file is built.
Key Characteristics:
- Links occur during program load time or runtime
- Requires operating system support for memory management
- Uses Dynamic Link Libraries (DLLs) as shared code modules
How it works:
The executable contains references to external functions but not their actual code. When the program runs, the OS locates the required DLL in memory and establishes the connection.
Memory efficiency:
Multiple programs can share the same DLL in memory simultaneously. For example, if 5 programs use the same graphics library, only one copy exists in RAM.
Runtime flexibility:
Programs can load different versions of libraries or optional modules based on system configuration or user preferences.
Note: The OS maintains a reference count for each loaded DLL - it remains in memory as long as at least one program is using it.
Non-contiguous Allocation
Non-contiguous allocation allows programs to be loaded into memory in separate, non-adjacent blocks rather than requiring one continuous memory segment.
Key principle: Logical Address Space (LAS) โ Physical Address Space (PAS)
- LAS: Virtual memory space seen by the CPU and programs
- PAS: Actual physical memory (RAM) available in the system
This relationship enables:
Efficient multiprogramming: Multiple programs can share physical memory simultaneously by loading only their active portions.
Large program execution: Programs larger than available RAM can run by keeping frequently used parts in memory and swapping others to disk as needed.
Memory utilization: Physical memory is used more effectively since programs don't need to occupy contiguous blocks, reducing fragmentation.
Example: A 6GB program can run on a system with 4GB RAM by loading different program segments into available memory slots and using virtual memory techniques for the rest.
Note: The mapping between logical and physical addresses is handled by the Memory Management Unit (MMU) through techniques like paging or segmentation.
6.2 Contiguous Memory Allocation
Static Linking
Static linking combines all program modules into a single executable file during compilation. The linker resolves all external references and creates one complete binary.
Key characteristics:
- All required libraries and modules are embedded in the executable
- No external dependencies needed at runtime
- Larger executable file size
- Faster program startup (no runtime linking overhead)
Memory allocation:
- Complete program loaded into memory at startup
- All code and data segments allocated together
- No dynamic loading during execution
Advantages:
- Self-contained executable
- Predictable memory usage
- No version conflicts with shared libraries
Disadvantages:
- Increased disk space usage
- Memory waste when multiple programs use same libraries
- Updates require recompiling entire program
Example: A program using math functions gets the entire math library compiled into its executable, even if it only uses sin() and cos() functions.
Contiguous (CG)
Contiguous memory allocation stores a program's entire code and data in a single, uninterrupted block of memory. This centralised approach keeps all program components together in consecutive memory addresses.
Types of Contiguous Allocation:
- Multiprogramming with Fixed Task (MFT)
- Memory divided into fixed-size partitions
- Each partition holds one program
- Partition sizes determined at system boot
- Simple but leads to Internal Fragmentation
- Multiprogramming with Variable Task (MVT)
- Memory partitions created dynamically based on program size
- Partitions vary in size to fit different programs
- Reduces internal fragmentation but causes external fragmentation
- Requires compaction to merge free spaces
- Overlays
- Technique for running programs larger than available memory
- Program divided into modules that share the same memory space
- Only active module loaded; inactive modules stored on disk
- Programmer manually manages which modules to load/unload
- Buddy System (Dynamic Merging)
- Memory allocated in power-of-2 sized blocks
- When memory freed, system checks if adjacent "buddy" block is also free
- Free buddies automatically merge into larger block
- Reduces external fragmentation through systematic merging
Key Advantage: Simple memory management with fast access since entire program is in one location.
Main Limitation: External fragmentation creates unusable memory gaps between allocated blocks.
Contiguous Memory Allocation
Contiguous Memory Allocation refers to allocating a single continuous block of memory to each process. This approach has limitations but forms the foundation for understanding memory management.
Key Characteristics:
- Each process gets one unbroken memory segment
- Process size cannot exceed available physical memory
- Simple to implement and manage
Limitations:
- External fragmentation: Free memory scattered in small, unusable blocks
- Internal fragmentation: Allocated memory larger than process needs
- Limited multiprogramming: Large processes may not fit in available memory
Solutions to Overcome Limitations:
Overlays: Manually divide program into segments that can share memory space
- Only active code segments loaded at any time
- Programmer responsibility to manage overlay structure
- Reduces memory footprint but increases complexity
Virtual Memory: Allows processes larger than physical memory
- Creates illusion of unlimited memory space
- Automatic management by operating system
- Enables higher degree of multiprogramming
Benefits of These Solutions:
- Increased multiprogramming: More processes can run simultaneously
- Higher CPU utilization: Less idle time waiting for memory
- Better throughput: More processes completed per unit time
Note: Virtual memory has largely replaced overlays in modern systems due to automatic management and better performance.
Overlays
Overlays are a memory management technique where only parts of a program are kept in memory at any given time, with other parts stored on disk and loaded when needed.
Key characteristics:
- Only one process active in RAM at a time
- Program must be divided into independent modules
- Modules are swapped in/out of memory as required
- Programmer must explicitly manage which modules to load
How it works:
- Program is split into a main module (always in memory) and overlay modules
- When a function in an overlay module is needed, the module is loaded from disk
- Previously loaded overlay modules may be replaced to make space
- Control returns to main module after overlay execution
Example: A compiler with phases:
- Main module: symbol table, memory manager (always loaded)
- Overlay 1: lexical analyzer
- Overlay 2: syntax analyzer
- Overlay 3: code generator
Only the active phase stays in memory alongside the main module.
Limitations:
- No support for multitasking or multiprogramming
- Suitable only for sequential processing
- Programmer must manually design overlay structure
- Frequent disk I/O can slow execution
Note: Largely obsolete due to virtual memory systems that provide automatic overlay functionality.
Buddy System
The buddy system manages memory allocation using fixed-size segments of contiguous physical pages. All allocations are rounded up to the nearest power of 2.
Core mechanism: Memory blocks are allocated in sizes 2^k, where k is chosen such that 2^k โฅ requested size.
Key properties:
- Each block has a "buddy" - another block of the same size at a specific address
- Buddy address for block at address x of size 2^k is: x โ 2^k (XOR operation)
- Two buddies can merge into a larger block of size 2^(k+1)
Allocation process:
- Find smallest available block โฅ request size
- If block is too large, split it recursively until proper size
- Mark allocated block as used
Deallocation and coalescing:
- Mark block as free
- Check if buddy is also free
- If yes, merge both blocks into larger block
- Repeat merging with new buddy until no more merging possible
Example: For 1MB segment starting at address 0:
- Request 100KB โ allocate 128KB block (next power of 2)
- Available sizes: 128KB, 256KB, 512KB
- Buddies of 128KB block at 0: block at 128KB
Advantage: Fast coalescing prevents external fragmentation by quickly combining adjacent free blocks.
Limitation: Internal fragmentation due to power-of-2 sizing requirement.
6.3 Fixed and Variable Partitioning
Partitions
Memory partitioning divides physical memory into separate sections to manage multiple processes efficiently.
Core Functions:
Allocation: Assigns memory blocks to processes based on their size requirements and available partitions.
Protection: Uses limit registers to prevent processes from accessing memory outside their allocated partition boundaries.
Free space management: Tracks which partitions are available and maintains lists of free memory blocks.
Deallocation: Returns memory blocks to the free pool when processes terminate or release memory.
Primary Goals:
Minimize fragmentation: Reduce wasted memory space that occurs when allocated blocks don't perfectly match process requirements.
- Internal fragmentation: unused space within allocated partitions
- External fragmentation: free space scattered in small, unusable chunks
Enable larger programs: Allow processes with memory requirements exceeding available RAM to execute through techniques like overlays and virtual memory.
Partition Types:
Fixed partitions: Memory divided into predetermined, equal sized blocks. Simple but causes internal fragmentation.
Variable partitions: Dynamic allocation creates partitions matching exact process sizes. Reduces internal fragmentation but increases external fragmentation over time.
Note: Effective partition management balances memory utilization against allocation overhead and fragmentation costs.
Multiprogramming With Fixed Task
Fixed Partitioning divides memory into predetermined, non-overlapping regions of fixed sizes.
Key Characteristics:
- Process size limit: Maximum process size equals the largest available partition size
- Multiprogramming degree: Limited by the total number of partitions created
- Dual fragmentation problem: Experiences both internal and external fragmentation
Internal Fragmentation occurs when a process is smaller than its assigned partition, leaving unused space within the partition.
External Fragmentation happens when free partitions exist but are too small for waiting processes.
Example: Memory divided into partitions of 100K, 200K, 400K:
- A 110K process uses the 200K partition โ 90K Internal Fragmentation
- A 500K process cannot fit in any partition โ external fragmentation despite 700K total space
Trade-off: More partitions increase multiprogramming but create smaller partition sizes, limiting individual process capacity.
Multiprogramming With Variable Tasks
Variable Partition Allocation allows partitions of different sizes to accommodate processes of varying memory requirements.
Key Characteristics:
- Degree of multiprogramming changes dynamically based on available memory and process sizes
- Memory is divided into partitions of unequal sizes as needed
- Partitions are created and destroyed based on process arrival and departure
Fragmentation:
- Suffers from external fragmentation only
- Internal fragmentation is eliminated since partition size matches process size exactly
- External fragmentation occurs when free memory blocks are too small for incoming processes
Allocation Policies:
| Policy | Description |
|---|---|
| Best Fit | Allocate smallest suitable block |
| Worst Fit | Allocate largest available block |
Why Worst Fit Works Best:
- Allocating the largest block leaves behind a large free block
- Large remaining blocks are more likely to satisfy future requests
- Reduces external fragmentation compared to other policies
Example: Memory has blocks of 100K, 200K, 300K, Process needs 150K:
- Best Fit: Uses 200K block, leaves 50K, too small for most processes
- Worst Fit: Uses 300K block, leaves 150K, just accommodate another similar process
Note: This contradicts the general rule where Best Fit typically performs better in fixed partition schemes.
6.4 First Fit Allocation
Allocation Policies
Memory allocation policies determine how the operating system assigns free memory blocks to processes requesting memory.
First Fit
Allocates the first available free block that is large enough to satisfy the request. The search starts from the beginning of the memory list.
- Advantage: Fast allocation - stops at first suitable block
- Disadvantage: Creates small unusable fragments at the beginning of memory
Example: For a 100KB request with free blocks 150KB, 90KB, 200KB, allocates the 150KB block.
Best Fit
Allocates the smallest available free block that can accommodate the request. Searches the entire memory list to find the optimal fit.
- Advantage: Minimizes wasted space in each allocation
- Disadvantage: Slower search time, creates many tiny fragments
Example: For a 100KB request with free blocks (150KB, 120KB, 200KB), allocates the 120KB block.
Worst Fit
Allocates the largest available free block. Always chooses the biggest block from all available options.
- Advantage: Leaves larger remaining fragments that may be useful later
- Disadvantage: Quickly exhausts large blocks, poor memory utilisation
Example: For a 100KB request with free blocks (150KB, 120KB, 200KB), allocates the 200KB block.
Next Fit
Similar to First Fit, but continues the search from where the last allocation ended, rather than starting from the beginning each time.
- Advantage: Distributes allocations more evenly across memory
- Disadvantage: May skip over suitable blocks that appeared earlier
Note: Next Fit maintains a pointer to the last allocated position and wraps around to the beginning when it reaches the end of memory.
Internal and External Fragmentation
Internal Fragmentation
Internal fragmentation occurs in fixed-size partitioning when a process is allocated to a partition larger than its actual memory requirement.
Definition: The unused space left within an allocated partition when the process size is smaller than the partition size.
Internal Fragmentation = Partition Size - Process Size
Key characteristics:
- Happens only in fixed-size partitioning schemes
- Memory is allocated but remains unused within the partition
- Cannot be used by other processes since the entire partition is marked as allocated
- Reduces overall memory utilisation
Example:
- Partition size: 100KB
- Process requirement: 75KB
- Internal fragmentation: 25KB (wasted within the partition)
Total internal fragmentation across the system is the sum of unused space in all allocated partitions.
Note: This fragmentation is "internal" because the wasted space exists inside allocated memory blocks, unlike external fragmentation which occurs between allocated blocks.
External Fragmentation
External fragmentation occurs in variable-size partitioning when free memory blocks become scattered throughout the system. As processes terminate, they leave behind gaps that may be too small for new processes, even though the total free memory is sufficient.
Problem: Memory becomes fragmented into small, unusable chunks between allocated blocks.
Example: If a system has three 50KB free blocks scattered across memory, it cannot allocate a single 100KB process, despite having 150KB total free space.
Solutions to External Fragmentation
Two main approaches address this issue:
- Compaction
- Relocates all allocated processes to one end of memory
- Consolidates all free space into a single large block
- Requires relocatable code and significant overhead
- Similar to disk defragmentation
- Non-contiguous Memory Allocation
- Allows processes to occupy multiple separate memory blocks
- Eliminates need for large contiguous spaces
- Implemented through techniques like paging and segmentation
- More flexible but requires additional hardware support
Trade-off: Compaction is simple but expensive in CPU time. Non-contiguous allocation is efficient but requires more complex memory management hardware.
Note: Modern systems primarily use non-contiguous allocation (paging) as it provides better memory utilisation with acceptable overhead.
Compaction
Compaction
Memory compaction is a technique to consolidate free memory by moving allocated blocks together, creating one large contiguous free space.
Process: All allocated memory blocks are moved to one end (typically lower addresses), leaving all free space consolidated at the other end.
Compaction Steps:
- Block processes - Suspend all processes that will be relocated
- Relocate memory - Move process blocks toward lower memory addresses
- Update references - Adjust all memory pointers and addresses
- Allocate memory - Satisfy pending allocation requests from the new free space
- Resume processes - Restart the relocated processes
Requirements:
- Dynamic relocation support - Programs must use relative addressing or relocatable code
- Address binding - Must occur at execution time, not compile/load time
Trade-offs:
- Benefit: Eliminates external fragmentation completely
- Cost: High CPU overhead during compaction process
- Timing: All affected processes must be suspended during relocation
When used: Typically triggered when free memory is too fragmented to satisfy large allocation requests, despite having sufficient total free space.
Note: Modern systems often prefer paging over compaction due to the significant performance overhead.
Paging Basics
Non-contiguous (NCS)
Non-contiguous memory allocation allows programs to be stored in scattered memory locations rather than requiring a single continuous block.
Key characteristic: Program components are distributed across available memory spaces, improving memory utilisation and reducing fragmentation.
Types of Non-contiguous Allocation:
- Paging
- Divides program into fixed-size pages
- Memory divided into frames of same size
- Pages can be loaded into any available frames
- Uses page table for address translation
- Segmentation
- Divides program into logical segments (code, data, stack)
- Segments have variable sizes based on logical boundaries
- Each segment allocated independently in memory
- Uses segment table for address mapping
- Segmented Paging
- Combines benefits of both paging and segmentation
- Program first divided into segments, then segments into pages
- Two-level address translation: segment table -> page table
- Reduces external fragmentation while maintaining logical structure
- Virtual Memory (Demand Paging)
- Pages loaded into memory only when accessed
- Allows programs larger than physical memory to execute
- Uses page replacement algorithms when memory is full
- Provides illusion of unlimited memory space
Advantage: Eliminates need for contiguous memory blocks, enabling better memory utilisation and support for larger programs.
Multilevel Paging
Multilevel Paging
Large page tables consume excessive memory, creating a bottleneck in system performance. Two primary solutions address this issue:
Solution 1: Increase Page Size
Approach: Use larger page sizes to reduce the total number of pages needed.
Logic: If each page covers more memory, fewer pages are required to map the same address space, resulting in a smaller page table.
Example:
- 4KB pages for 1GB memory = 262,144 pages
- 64KB pages for 1GB memory = 16,354 pages (84% reduction in page table entries)
Major drawback: Severe internal fragmentation occurs when processes don't fully utilise the larger pages, wasting significant memory.
Solution 2: Multilevel Paging
Approach: Create a hierarchical page table structure with multiple levels.
Key principle: Page table entries are created only when needed, not for the entire virtual address space upfront.
How Multilevel Paging Works:
The virtual address is divided into multiple parts:
- Level 1 Index: Points to a second-level page table
- Level 2 Index: Points to the actual page frame
- Offset: Location within the page
Memory efficiency: If a process doesn't use certain address ranges, the corresponding second-level page tables are never created, saving substantial memory.
Example: A process using only 10% of its virtual address space will have page tables for only that 10%, not the entire space.
Advantage over larger pages: Eliminates internal fragmentation while still reducing page table memory overhead.
Trade-off: Slightly increased address translation time due to multiple memory accesses, but modern systems use Translation Lookaside Buffers (TLBs) to minimise this impact.
Inverted Page Table
Inverted Page Table
An inverted page table uses a reverse mapping approach - instead of mapping virtual pages to physical frames, it maps physical frames to virtual pages.
Structure: One entry per physical frame in memory.
Table Size = Number of Physical Frames
Each entry contains:
- Virtual page number stored in this frame
- Process ID that owns this page
- Additional control bits (valid, dirty, etc.)
Entry format: (process-id, page-number)
The process ID acts as an address space identifier, distinguishing between pages from different processes that might have the same virtual page number.
Key advantage: Fixed table size regardless of virtual address space size. A system with 1GB physical memory needs only 256K entries (assuming 4KB pages), even if processes use terabytes of virtual space.
Translation process:
- Hash the virtual address (PID + page number)
- Search inverted table for matching entry
- If found, frame number = table index
- If not found, page fault occurs
Trade-off: Better space efficiency but slower lookups compared to traditional page tables. Hash tables or associative memory often used to speed up searches.
Remember: One table for entire system vs. one table per process in traditional paging.
Segmentation
Difference Between Paging and Segmentation
Paging vs Segmentation - key differences in memory management approaches:
| Aspect | Paging | Segmentation |
|---|---|---|
| Internal Fragmentation | Only in the last page | None - segments are exactly sized |
| External Fragmentation | None - all pages are the same size | Yes - variable-size segments create holes over time |
| Programmer Visibility | Transparent - programmer is unaware | Visible - programmer must manage segments |
Paging characteristics:
- Fixed-size blocks (typically 4KB pages)
- Hardware handles address translation automatically
- Simple allocation but wastes space in final page
Segmentation characteristics:
- Variable-size blocks matching program structure (code, data, stack)
- Reflects logical program organization
- Perfect fit but creates external holes over time
Example: A 10KB program in 4KB pages uses 3 pages (12KB total) - 2KB internal fragmentation. Same program as segments uses exactly 10KB but may not fit in available memory gaps.
Remember: Paging = Fixed size = internal waste; Segmentation = variable size = external gaps.
7. Virtual Memory
Demand Paging
Logical Address Space
A logical address space is partitioned into fixed-size blocks called pages. Each page has uniform size for efficient memory management.
Page Size: Typically a power of 2 (e.g., 4KB, 8KB) for binary alignment.
Key Formulas:
Number of pages in logical address space:
N = Logical Address Space Size / Page Size
Bits required for page number:
Page Number bits = ceil(log2 N)
Bits required for page offset:
Page Offset bits = ceil(log2 Page Size)
Address Structure: A logical address splits into two parts:
- Page Number (P): Identifies which page
- Page Offset (d): Position within that page
Example: 32KB logical address space with 4KB pages:
- Number of pages: N = 32KB / 4KB = 8
- Page number bits: log2 8 = 3 bits
- Page offset bits: log2 4096 = 12 bits
- Total address bits: 3 + 12 = 15 bits
Remember: Page offset determines maximum page size, while page number determines how many pages can exist in the address space.
Physical Address Space
Physical memory is organised into fixed-size blocks called frames (or page frames). Each frame can hold exactly one page from a process.
Key Properties:
- Frame size equals page size
- All frames are the same size
- Frames are numbered sequentially starting from 0
Frame Calculations:
Total number of frames in physical memory:
M = Physical Address Space / Page Size
Bits needed to represent frame number:
Frame bits = ceil(log2 M)
Address Structure:
A physical address consists of two parts:
- Frame number (f): Identifies which frame
- Frame offset (d): Position within the frame (same as page offset)
Example: 16 KB physical memory with 4 KB pages:
- Number of frames: M = 16KB / 4KB = 4 frames
- Frame number bits: log2 4 = 2 bits
- Frame offset: 12 bits (since 4KB = 2^12 bytes)
Remember: Frame offset is identical to page offset - both represent the position within a 4 KB block.
Page Table
A page table maps logical page numbers to physical frame numbers in memory. Each process maintains its own page table stored in main memory.
Page Table Structure:
Each page table entry contains:
- Frame number (physical location)
- Control bits for memory management
Page table size: PT_size = N x e bytes
- N = number of entries
- e = entry size in bytes (e = ?)
Control Bits:
Each page table entry uses four control bits:
- Use bit: Set when page is accessed, cleared by clock replacement algorithm
- Modified bit: Set when page is written to, cleared after page is saved to disk
- Valid bit: Set when page table entry is legitimate for current process
- Read-only bit: Set to allow read access only, prevents write operations
Address Translation Process:
The CPU generates a logical address split into two parts:
- Page number (p): Index into the page table
- Displacement (d): Offset within the page
Translation steps:
- Extract page number p from logical address
- Use p to index into page table in main memory
- Retrieve frame number f from page table entry
- Combine frame number f with original displacement d
- Result is physical address = f + d [as shown: frame number concatenated with displacement]
Example: Logical address 1025 with page size 1024 bytes
- Page number: p = 1025 / 1024 = 1
- Displacement: d = 1025 mod 1024 = 1
- If page table entry 1 contains frame 5, physical address = 5 x 1024 + 1 = 5121
Note: The displacement remains unchanged during translation - only the page number gets converted to a frame number.
Performance of Paging
Paging Performance Analysis
Memory access time varies significantly based on whether Translation Lookaside Buffer (TLB) is used.
Without TLB:
- Main memory access time = m
- Page table lookup requires one memory access
- Actual data access requires another memory access
- Effective Memory Access Time (EMAT) = 2m
With TLB:
- TLB access time = c (where c << m)
- TLB hit ratio: alpha = Number of TLB hits / Total memory references
EMAT Formula:
EMAT = alpha(c + m) + (1 - alpha)(c + 2m)
Breaking down the formula:
- TLB Hit (alpha probability): Access TLB (c) + Access data (m) = c + m
- TLB Miss (1 - alpha probability): Access TLB (c) + Access page table (m) + Access data (m) = c + 2m
Simplified form:
EMAT = c + m + (1 - alpha)m = c + m(2 - alpha)
Example: If m = 100ns, c = 10ns, TLB hit ratio = 90%
- EMAT = 0.9(10 + 100) + 0.1(10 + 200) = 120ns
- Without TLB: 200ns
- Performance gain: 40% faster
Note: Higher TLB hit ratios dramatically improve performance since c << m.
Optimal Page Size
Optimal Page Size minimises total memory overhead by balancing page table size against internal fragmentation.
Given:
- Logical Address Space (LAS) = S bytes
- Page Table entry size = e bytes
- Page size = P bytes
Memory overhead components:
Page Table size = (S / P) x e
Total overhead to minimise:
Overhead = P/2 + (S x e)/P
Finding optimal page size:
Differentiate with respect to P and set to zero:
d/dP (P/2 + Se/P) = 1/2 - Se/P^2 = 0
Solving for P:
Se/P^2 = 1/2
P = sqrt(2Se)
Key insight: Optimal page size increases with larger address spaces and page table entries.
Multilevel Paging Performance:
Effective Memory Access Time with n-level paging:
EMAT = alpha(c + m) + (1 - alpha)(c + (n + 1)m)
where:
- alpha = cache hit ratio
- c = cache access time
- m = memory access time
- n = number of paging levels
Note: Cache miss requires (n + 1) memory accesses - one for each page table level plus the final data access.
Performance of Virtual Memory
The Effective Memory Access Time (EMAT) measures the average time to access data in a virtual memory system with demand paging:
EMAT = P x s + (1 - P) x m
Parameters:
- P = Page fault rate (probability of page fault)
- s = Page fault service time (includes disk access, typically in milliseconds)
- m = Main memory access time (typically in nanoseconds)
- (1 - P) = Page hit ratio (probability page is in memory)
Key insight: Since s >> m (page fault service time is much larger than memory access), even a small page fault rate significantly impacts performance.
Example Calculation:
- Memory access time: m = 100 ns
- Page fault service time: s = 10 ms = 10^7 ns
- Page fault rate: P = 0.001 (0.1%)
EMAT = 0.001 x 10^7 + 0.999 x 100 = 10,000 + 99.9
Performance impact: A 0.1% fault rate increases access time by 100x, showing why keeping pages in memory is critical for system performance.
Remember: EMAT grows linearly with fault rate, but disk access dominates the equation.
Demand Paging
Demand paging loads pages into memory only when they are actively referenced, creating the illusion of unlimited physical memory while allowing more processes to run simultaneously.
Core Mechanism:
Each page table entry includes a present bit (valid bit) that indicates:
- Present: Page is in physical memory
- Not present: Page resides on disk
When a process references a page not in memory, a page fault occurs, triggering the OS to handle the request.
Page Fault Handling:
When a page fault occurs, the OS performs these steps:
- Select victim page - Choose an existing page in memory to replace
- Write back if dirty - If the victim page was modified, save it to disk
- Update page table - Mark victim page as not present, invalidate TLB entry
- Load new page - Read the requested page from disk into the freed frame
- Update page table - Mark new page as present with correct frame address
- Resume process - Continue execution from the faulting instruction
Implementation Strategies:
Pure Demand Paging (default approach):
- All frames start empty when process begins
- Pages loaded only upon first access
- Higher initial page fault rate, but efficient memory usage
Pre-paging:
- Loads anticipated pages before they are referenced
- Reduces page faults during execution startup
- May waste memory if predictions are incorrect
Benefits:
- Larger virtual address spaces - Programs can exceed physical memory size
- Better multiprogramming - More processes can coexist in limited physical memory
- Efficient memory utilisation - Only active pages consume physical memory
Note: The page table must handle both memory addresses (for present pages) and disk locations (for pages stored on secondary storage).
Optimal Frame Allocation
When a process requires r frames and the operating system allocates exactly r frames to it simultaneously, page replacement becomes unnecessary.
Why no replacement needed:
- All required pages fit in allocated memory
- No page faults occur during execution
- Process runs without swapping pages to disk
Key insight: This scenario represents optimal memory allocation where demand equals supply. Contrast: If allocated frames < r, the OS must use page replacement algorithms (LRU, FIFO, etc.) to manage limited memory by swapping pages between RAM and disk.
Note: This ideal allocation is rarely possible in multi-process environments due to memory constraints.
Page Fault Handling
Virtual Memory
Virtual memory creates the illusion of unlimited memory space, allowing programs larger than physical RAM to execute by storing inactive portions on disk.
Page Fault Handling:
When a program accesses a page not in physical memory, a page fault occurs:
- Process suspension: The requesting process is blocked
- Mode switch: System switches to kernel mode
- Page retrieval: Virtual Memory Manager (VMM) locates the page on disk
- Frame allocation: System finds space in physical memory
- Page loading: Disk controller transfers the page to RAM
- Process resumption: Blocked process continues execution
Virtual Memory Manager Flow:
The VMM coordinates with system components in this sequence:
Frame Allocation Scenarios:
Case 1: Free frame available
- Page loads directly into empty frame
- Process resumes quickly
Case 2: No free frames
- Page replacement algorithm selects a victim page
- Victim page written to disk (if modified)
- New page loads into freed frame
- Higher service time due to additional disk operations
Performance Impact:
Page Fault Service Time (PFST) directly affects system performance:
- More page faults = longer PFST
- Increased execution time for programs
- Reduced overall system throughput
Note: Virtual memory relies on demand paging - pages load only when accessed, not preemptively.
Key Insight:
Virtual memory trades memory space for execution time. Programs can exceed physical RAM limits, but frequent page faults create performance bottlenecks.
Key constraint:
Allocation Strategies:
- Equal allocation: Each process gets m/n frames
- Proportional allocation: Process i gets (s_i / S) ร m frames
- Priority-based allocation: High-priority processes get more frames
Note: Since demand exceeds supply, page replacement becomes essential when processes need more frames than allocated.
Example: System with m = 100 frames, n = 4 processes
- Process demands: s_1 = 45, s_2 = 10, s_3 = 85, s_4 = 30
- Total demand: S = 170 frames (exceeds available 100)
- Equal allocation: 25 frames per process
- Proportional allocation: P_1 gets (45 / 170) ร 100 = 26 frames
First-In First-Out (FIFO)
FIFO (First-In First-Out) page replacement algorithm replaces the oldest page in memory when a page fault occurs.
Normal expectation: More page frames should reduce page faults, as more pages can stay in memory simultaneously.
Belady's Anomaly: Counter-intuitive behavior where increasing the number of page frames actually increases the page fault rate for certain reference strings.
More frames โ More page faults
Key characteristics:
- FIFO maintains pages in order of arrival
- Oldest page gets replaced regardless of usage frequency
- No consideration for page access patterns
Algorithms affected by Belady's Anomaly:
- Pure FIFO
- Second Chance Algorithm (degenerates to FIFO when all reference bits are 1)
- Clock Algorithm variants based on FIFO ordering
Example scenario: Reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5
- With 3 frames: 9 page faults
- With 4 frames: 10 page faults (anomaly evident)
Note: LRU and Optimal algorithms are stack-based and never exhibit Belady's Anomaly - they guarantee monotonic behavior where more frames never increase page faults.
LRU Page Replacement
Least Recently Used (LRU)
Least Recently Used (LRU) replaces the page that hasn't been accessed for the longest time period.
Key principle: Among all pages in memory, remove the one with the oldest "last access" timestamp.
Performance: LRU achieves near-optimal results because recently used pages are likely to be reused again soon (temporal locality principle).
Selection criteria: Time of last reference - Track when each page was most recently accessed.
Example: Memory contains pages with last access times:
- Page A: accessed 5 seconds ago
- Page B: accessed 2 seconds ago
- Page C: accessed 8 seconds ago
LRU selects Page C for replacement (oldest access time).
Implementation challenge: Requires tracking access time for every page, making it expensive to implement perfectly in hardware.
Note: LRU approximates optimal replacement by assuming past access patterns predict future needs.
Most Recently Used (MRU)
Most Recently Used (MRU) is a page replacement algorithm that removes the page accessed most recently when memory is full.
Selection criteria: Time of last reference - the page with the most recent access time is chosen for replacement.
Logic: Assumes that a recently accessed page is likely to be accessed again soon, so removing it frees up space while potentially causing a page fault if the assumption is wrong.
Implementation: Maintain timestamps or counters for each page frame to track access times.
Example: Memory frames contain pages A, B, C. Access sequence: A, B, C, A, B
- When D needs to be loaded and memory is full
- Page A was accessed most recently, so A is replaced by D
- Final state: B, C, D
Note: MRU is rarely used in practice as it contradicts the principle of temporal locality - recently used pages are typically more likely to be referenced again.
Comparison with LRU: While LRU removes the least recently used page (more common), MRU removes the most recently used page (counterintuitive for most workloads).
Counting Algorithms
Least Frequently Used (LFU): Replaces the page that has been accessed the fewest times since it was loaded into memory.
Most Frequently Used (MFU): Replaces the page that has been accessed the most times, based on the assumption that a heavily used page may not be needed again soon.
Implementation characteristics:
- Requires maintaining access counters for each page
- Counter increments on every page reference
- High overhead due to counter updates and searches
- More complex than LRU or FIFO algorithms
Example: Pages in memory with access counts:
- Page A: 5 accesses
- Page B: 7 accesses
- Page C: 1 access
LFU would replace Page C (lowest count), while MFU would replace Page B (highest count).
Note: MFU is rarely used in practice due to poor performance. LFU performs better but still has high implementation costs compared to simpler algorithms like LRU.
Optimal Page Replacement
Optimal
The Optimal Page Replacement Algorithm replaces the page that will remain unused for the longest time in the future.
Key Properties:
- Guarantees minimum number of page faults
- Does not suffer from Belady's Anomaly
- Theoretically optimal performance
Practical Limitation:
Cannot be implemented in real systems because it requires knowledge of future page references, which is impossible to predict.
Purpose:
Serves as a theoretical benchmark to evaluate the performance of other page replacement algorithms like LRU, FIFO, and LFU.
Example: Given reference string 7, 0, 1, 2, 0, 3, 0, 4 with 3 frames
- When frames are full and a page is referenced
- Algorithm checks future: page 1 won't be used again, page 2 will be used soon
- Replace page 1 (longest future distance)
Note: Also called Farthest-in-Future algorithm. Any practical algorithm achieving close to optimal performance is considered highly efficient.
LRU Approximation (Clock, Second Chance)
Variation of LRU / LRU Approximation
LRU approximation algorithms simulate LRU behavior without the overhead of tracking exact access order. They use hardware-supported bits to make replacement decisions.
Reference Bit (R):
The reference bit tracks page access within time periods called epochs:
- R = 0: Page not accessed during current epoch
- R = 1: Page accessed at least once during current epoch
The OS periodically resets all reference bits to start a new epoch.
Second Chance Algorithm (Clock Algorithm):
Combines FIFO ordering with reference bit checking.
Process:
- Check oldest page's reference bit
- If R = 0: Replace this page
- If R = 1: Set R = 0, move to next oldest page
- Repeat until finding a page with R = 0
Example: Pages in FIFO order: A(R=1), B(R=0), C(R=1)
- Check A: R = 1, so set R = 0 and skip
- Check B: R = 0, so replace B
- New order: C(R=1), A(R=0), E (new page)
Note: If all pages have R = 1, algorithm makes full circle and degenerates to pure FIFO.
Enhanced Second Chance (Not Recently Used):
Uses both reference bit and modify bit for smarter decisions.
Modify Bit (M):
- M = 0: Clean page (matches disk copy)
- M = 1: Dirty page (modified, needs write-back)
Replacement Priority (best to worst):
- (R = 0, M = 0): Not used, clean - best choice
- (R = 0, M = 1): Not used, dirty - needs write-back
- (R = 1, M = 0): Recently used, clean
- (R = 1, M = 1): Recently used, dirty - worst choice
Advantage: Avoids costly disk writes by preferring clean pages when possible.
Thrashing
Thrashing
Thrashing occurs when a system spends more time swapping pages between memory and disk than executing actual processes. The system becomes inefficient as CPU utilisation drops dramatically.
Definition:
Thrashing: Excessive paging activity where processes spend more time handling page faults than performing useful work.
CPU Utilisation vs Multiprogramming:
The relationship between multiprogramming degree and CPU utilisation follows a bell curve:
- Low multiprogramming: CPU under-utilised due to insufficient active processes
- Optimal point: Peak CPU utilisation with balanced process concurrency
- High multiprogramming: Performance degrades due to memory contention and excessive paging
- Extreme multiprogramming: System approaches deadlock with minimal useful work
Beyond the optimal point, adding more processes triggers thrashing, causing CPU utilisation to plummet despite high system activity.
Root Causes:
Primary causes:
- Insufficient memory frames allocated to processes
- Excessive degree of multiprogramming beyond system capacity
Secondary causes:
- Poor page replacement algorithms (e.g., replacing frequently used pages)
- Suboptimal page size selection
Page Size Impact:
| Page Size | Advantages |
|---|---|
| Large | Fewer page faults, reduced overhead |
| Small | Better memory utilisation, good for |
Trade-off: Large pages reduce fault frequency but waste memory through fragmentation. Small pages improve memory efficiency but increase paging overhead.
Control Strategies:
Prevention:
Limit the degree of multiprogramming to prevent memory overcommitment. Use admission control to reject new processes when memory pressure is high.
Detection:
Monitor these indicators:
- CPU utilisation drops below despite high system load
- Page fault rate exceeds normal thresholds
- Disk I/O for paging consumes nearly all of bandwidth
Recovery:
Immediate actions:
- Suspend or swap out selected processes to reduce memory pressure
- Temporarily reduce multiprogramming degree
Long-term solutions:
- Increase physical RAM capacity
- Optimize page replacement algorithms
- Adjust process working set sizes
Note: Recovery must be swift - prolonged thrashing can make the system unresponsive to corrective actions.
8. File Systems
File Concepts and Attributes
File System
File systems provide structured access to data stored on secondary storage devices. There are two primary access methods:
- Sequential access: Data is read or written in order from beginning to end
- Random access: Any byte can be accessed directly without reading preceding data
File System Components
A complete file system includes four essential components:
- Disk management: Organizes physical disk blocks into logical files and manages free space allocation
- Naming: Provides human-readable file names and directory structures instead of raw block and sector addresses
- Protection: Controls access permissions to prevent unauthorised users from reading or modifying files
- Reliability: Implements mechanisms like journaling and backups to prevent data loss during system failures
System Architecture
The file system operates through multiple layers that abstract hardware complexity:
Software Layer:
- File system provides device-independent operations (open, read, write, close)
- Device drivers handle hardware-specific communication protocols
Hardware Layer:
- CPU processes requests using electrical signals
- Controller cards (IDE, SCSI, SATA) manage data transfer protocols
- Secondary storage devices use magnetic or electronic storage technology
Data Flow: Applications interact with the file system, which communicates through device drivers to controller hardware, which then manages the physical storage devices. This layered approach allows the same file operations to work across different storage technologies.
Note: The file system layer shields applications from hardware details like track positioning, sector addressing, and device-specific timing requirements.
File System Structure
A file system provides organized storage, location, and retrieval of data on storage devices. It acts as an interface between applications and physical storage hardware.
File System Architecture
File systems are organized in a layered hierarchy, where each layer provides specific functionality and communicates only with adjacent layers:
Application Programs
- User applications that request file operations (read, write, create, delete)
- Interact with the file system through system calls
Logical File System
- Provides the file system interface to applications
- Manages file metadata (names, permissions, timestamps)
- Handles directory operations and file naming
- Maintains file control blocks and directory structures
File Organization Module
- Manages file allocation methods (contiguous, linked, indexed)
- Handles free space management and allocation algorithms
- Translates logical file addresses to physical block addresses
- Implements file access methods
Basic File System
- Issues generic read/write commands to device drivers
- Manages buffer cache for performance optimization
- Handles block-level operations on storage devices
- Provides uniform interface regardless of storage type
I/O Control Layer
- Contains device drivers for specific hardware
- Handles interrupt processing and error recovery
- Manages device-specific communication protocols
- Controls timing and synchronization of I/O operations
Physical Devices
- Actual storage hardware (hard disks, SSDs, optical drives)
- Provides raw storage capacity in blocks or sectors
Key Benefits
- Abstraction: Applications don't need to know hardware details
- Modularity: Each layer has specific responsibilities
- Portability: Same logical interface works across different devices
- Performance: Caching and optimization at appropriate layers
Remember: Data flows down through layers for write operations and up through layers for read operations, with each layer adding its specific processing.
File Usage Patterns
File systems exhibit predictable usage patterns that influence design decisions:
Small Files Dominate Access
- Most files in a system are small (under 10KB)
- Small files account for the majority of file operations (open, read, write, close)
- File system metadata structures are optimized for handling many small files efficiently
Large Files Consume Space
- A few large files (databases, videos, logs) occupy most available disk space
- The 80/20 rule applies: ~20% of files use ~80% of storage capacity
- Storage allocation strategies must handle both scenarios effectively
I/O Transfer Patterns
- Large files generate most data movement between disk and memory
- Bulk transfers from large files dominate bandwidth usage
- Sequential access patterns are common for large file operations
Design Implications
- Fast metadata access for small files (inodes, directory entries)
- Efficient block allocation for large files (extent-based allocation)
- Separate optimization strategies for different file size categories
Example: In a typical system with 1000 files:
- 900 files are < 1MB (small files, frequent access)
- 100 files are > 1MB (large files, consume 96% of disk space)
- Large files handle 96% of total I/O bytes despite being 10% of file count
File Structure and Operations
A file is a collection of logically related data records. From a programmer's perspective, a file is a data structure with defined representation, operations, and attributes.
File Structure Types
Files can be organized using three main structural approaches:
Flat Structure
- Simple series of bytes stored sequentially
- No internal organization or hierarchy
- Direct byte-level access
Record Structure
- Data organized as discrete records
- Supports structured operations like push/pop and read/write
- Each record can contain multiple fields
Tree Structure
- Hierarchical organization using B-trees or B+-trees
- Efficient for searching and indexing
- Common in database systems and file indexes
File Operations
Standard operations available on files:
- Create: Establish a new file in the system
- Open: Prepare file for access and load metadata
- Read: Retrieve data from file
- Write: Store data to file
- Modify: Update existing file content
- Seek: Move to specific position within file
- Copy: Duplicate file to another location
- Move: Transfer file to different location
- Rename: Change file identifier
- Close: Release file resources and save changes
- Delete: Remove file from system
File Attributes
Key properties that describe a file:
- Name: Human-readable identifier
- Type: File format or extension (e.g., .txt, .exe)
- Size: Amount of storage space occupied
- Owner: User or process that created the file
- Path: Complete location within directory structure
- Location: Physical storage address on device
Directory
A directory is a special type of file that stores metadata about other files. It acts as a catalog containing information such as file names, locations, sizes, and permissions. Directories enable hierarchical file organization and provide the structure for file system navigation.
Logical Structure of Disk
Disk Partitions
A disk is divided into partitions to organize storage:
- Primary Partition: Contains the operating system and can be made bootable. At least one primary partition is required per disk.
- Extended Partition: A secondary partition that can be subdivided into multiple logical drives for additional storage.
File Control Block (FCB)
The FCB stores metadata about each file, including ownership, permissions, and location information. Different file systems implement this differently:
- UNIX: Uses inode blocks in the UNIX File System
- Windows: Stores information in the Master File Table (MFT, NTFS)
- Linux: Uses Extended File Systems (ext2, ext3, ext4)
File Allocation Methods
Contiguous Allocation
Files are stored in consecutive disk blocks.
- Suffers from internal and external fragmentation
- Difficult to expand file size once allocated
- Provides fast random access since blocks are sequential
Linked Allocation
Each file block contains a pointer to the next block in the file.
- Allows flexible file size expansion
- Only supports sequential access, making it slower
- Requires extra space for storing pointers
- Eliminates external fragmentation
- Used by MS-DOS with File Allocation Table (FAT)
Indexed Allocation
Uses an index block to track all file block locations directly.
- Eliminates fragmentation issues
- Supports flexible file size changes
- Enables direct access to any block
- May waste space if index block is not fully utilized
Multilevel Indexed Allocation
Uses multiple levels of index blocks for large files. The inode structure contains pointers that work hierarchically:
- Direct pointers: Point directly to data blocks
- Single Indirect: Points to a block containing data block addresses
- Double Indirect: Points to a block containing single indirect block addresses
- Triple Indirect: Points to a block containing double indirect block addresses
Free Space Management
Bitmap Method
Uses a bit vector where each bit represents one disk block.
- Bit value 0 = free block, bit value 1 = allocated block
- Memory requirement grows with disk size
- Efficient for finding consecutive free blocks
To find the first free block:
Block Number = (bits per word ร number of zero words) + bit position of the first set bit
For a disk with n total blocks, f free blocks, D-bit disk addresses, and b bytes per block: Bitmap uses less space than free list when: f ร D > n
Linked List Method
Links all free blocks together in a chain.
- Simple to implement
- Difficult to traverse efficiently
- No wasted space for tracking
Grouping Method
Stores addresses of n free blocks in the first free block.
- First (n โ 1) blocks are actually free
- Last block contains addresses of next n free blocks
- Allows quick access to many free block addresses
Counting Method
Stores pairs of (starting block number, count of consecutive blocks).
- Efficient when files are allocated/freed in contiguous chunks
- Reduces list size compared to individual block tracking
Disk Scheduling Algorithms
First-Come First-Served (FCFS)
- Processes requests in arrival order
- Fair to all processes
- May result in long seek times due to random disk access patterns
- Does not optimize for performance
Shortest Seek Time First (SSTF)
- Selects the request closest to current disk head position
- Minimizes seek time for each request
- May cause starvation of requests far from current position
- Can include rotational delay in calculations for better optimization
9. Disk Scheduling
9.1 FCFS Disk Scheduling
Disk Access Time
Disk access time consists of three sequential components that determine how long it takes to read or write data:
Disk Access Time = Seek Time + Rotational Delay + Transfer Time
Seek Time: Time required to move the read/write head to the correct cylinder (track). Depends on the distance the head must travel.
Rotational Delay (Latency): Time waiting for the target sector to rotate under the head after reaching the correct track. Average rotational delay is half the rotation period.
Transfer Time: Time to actually read or write the data once the head is positioned over the target sector.
Example: For a disk with 7200 RPM:
- Rotation period = 60 / 7200 = 8.33 ms
- Average rotational delay = 8.33 / 2 = 4.17 ms
- If seek time = 6 ms and transfer time = 0.5 ms
- Total access time = 6 + 4.17 + 0.5 = 10.67 ms
Note: Seek time typically dominates for random access patterns, while rotational delay becomes significant for sequential access.
9.2 SCAN (Elevator) Disk Scheduling
SCAN (Elevator)
The SCAN algorithm moves the disk head continuously in one direction, servicing requests along the way until reaching the disk boundary, then reverses direction.
How it works:
- Head moves in current direction (inward or outward)
- Services all requests encountered in that direction
- At disk boundary, reverses direction and repeats
- Continues this back-and-forth motion like an elevator
Key characteristics:
- Eliminates starvation - every request gets serviced eventually
- Better than SSTF for fairness while maintaining reasonable seek times
- Head movement is predictable and systematic
Example: Requests at tracks [23, 89, 132, 42, 124], head at track 53, moving outward
- Services: 89 โ 124 โ 132 (outward to end)
- Then reverses: 42 โ 23 (inward)
- Total head movement follows elevator pattern
Trade-off: Requests at disk edges wait longer than those in middle, but maximum wait time is bounded by one full disk traversal.
9.3 C-SCAN Disk Scheduling
C-scan
The C-SCAN (Circular SCAN) disk scheduling algorithm serves requests by scanning in only one direction, then jumping back to start.
How C-SCAN works:
- Disk arm moves in one direction (typically 0 to highest track)
- Services all requests encountered during the scan
- Upon reaching the end, arm immediately returns to track 0
- Begins next scan in the same direction
Key characteristic: The return journey to track 0 does not service any requests - it's a pure seek operation.
Advantage over SCAN: Provides more uniform wait times since all tracks get serviced in the same directional pattern.
Example: For requests at tracks [98, 183, 37, 122, 14, 124, 65, 67] with head at 53:
- Scan direction: 53 โ 65 โ 67 โ 98 โ 122 โ 124 โ 183
- Jump back: 183 โ 0 (no service during return)
- Continue: 0 โ 14 โ 37
Note: Called "circular" because the algorithm treats the disk as if track 0 follows the highest track, though physically the head must seek back to the beginning.
Trade-off: Eliminates the bias of SCAN algorithm where middle tracks get serviced more frequently, but increases total seek time due to the return journey.
9.4 LOOK Disk Scheduling
LOOK Disk Scheduling
The LOOK disk scheduling algorithm optimizes head movement by scanning in one direction until the last request, then reversing direction.
Algorithm:
- Services requests in the current direction of head movement
- Continues until no more requests exist in that direction
- Reverses direction and services remaining requests
- Does NOT go to disk extremes (unlike SCAN)
Key difference from SCAN: LOOK stops at the last request in each direction, while SCAN always goes to the disk boundaries.
Example: Requests at cylinders [23, 89, 132, 42, 187], head at cylinder 53, moving right
- Services: 89 โ 132 โ 187 (rightward)
- Reverses at 187 (last request, not disk end)
- Services: 42 โ 23 (leftward)
Advantage: Reduces unnecessary head movement to disk boundaries, improving average seek time compared to SCAN.
Total head movement: Distance from start to furthest request + distance between extreme requests.