Vault Notes
๐ŸŽงListen

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:

CPU utilization formula:

CPU Utilization = 1 - p^n

where:

Example: With 3 processes, each spending 80% time in I/O wait (p = 0.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 Goals

A secure system must achieve three fundamental objectives:

  1. Data Confidentiality: Sensitive information remains accessible only to authorized users
  2. Data Integrity: Unauthorized users cannot modify data without proper permissions
  3. System Availability: The system remains operational and accessible to legitimate users

Security Components

Security implementation requires three essential components:

  1. Authentication: Verifies user identity ("Who are you?")
  1. Authorization: Determines access permissions ("What can you do?")
  1. Enforcement: Ensures compliance with security policies ("Making sure you do only what you're allowed")

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:

Common abuse scenarios:

Mitigation strategies:

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:

Behavioral monitoring countermeasures:

Detection indicators:

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:

Common attack vectors:

Defense mechanisms:

Integrity checking - Primary countermeasure that verifies program authenticity:

Additional protections:

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:

Common Targets:

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:

Countermeasures:

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:

Typical payloads:

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:

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.

ProgramProcess
Passive entity stored on diskActive entity in
Static code and dataDynamic execution

Process Memory Layout

Stack Free memory Heap (Dynamic Data) Data Segment Code Segment (Text) grows down grows up
Process Memory Layout. A vertical stack showing how a process is laid out in memory, from top to bottom: Stack, then free memory, then Heap, then Data Segment, then Code Segment. The Stack at the top grows downward, shown by a downward arrow; it grows and shrinks dynamically during function calls and stores function parameters, return addresses, and local variables. Below the stack is the available free memory. Under that is the Heap, labelled Dynamic Data, which grows upward toward the stack, shown by an upward arrow; it is used for dynamic memory allocation during runtime, allocated using malloc() and new. The stack and heap grow toward each other, with available free memory between them. Below the Heap is the Data Segment, which contains global variables and static data, in initialized and uninitialized data sections, with a fixed size determined at compile time. At the bottom is the Code Segment, also called Text, which contains the actual program instructions, read-only machine code, shared among multiple instances of the same program. Takeaway: a process's memory is these regions stacked together, with the stack and heap expanding toward each other and the data and code segments fixed below them.

A process in memory consists of four main segments:

Stack:

Heap (Dynamic Data):

Data Segment:

Code Segment (Text):

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:

  1. Create - Allocate memory, initialize PCB, load program
  2. Manage - Schedule execution, block/suspend, resume operations
  3. Terminate - Deallocate resources, remove from memory

Dual Mode Operation

User Mode (Non-privileged):

Kernel Mode (Privileged):

Mode switching occurs during system calls, interrupts, or exceptions.

Process Control Block (PCB): Data structure maintained by the OS for each process containing:

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:

Cooperating Processes influence or are influenced by other processes during execution.

Key features:

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:

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:

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:

Communication Types

Synchronous vs Asynchronous:

TypeSender Behavior
SynchronousBlocks until message delivered
AsynchronousContinues immediately

Direct vs Indirect:

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:

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

NewReadyRunningTerminatedWaitingSuspend ReadySuspend Wait Admitted Dispatch Interrupt Exit I/O Request I/O Complete Suspend Resume Suspend Resume
Process State Diagram. It shows the states a process moves through: New, Ready, Running, Waiting (also called Blocked), Terminated, Suspend Ready, and Suspend Wait. The transitions, in reading order: Admitted takes a process from New to Ready. Dispatch takes it from Ready to Running. Interrupt takes it back from Running to Ready. An I/O Request takes it from Running to Waiting. I/O Complete takes it from Waiting back to Ready. Exit takes it from Running to Terminated. Suspend takes a process from Ready to Suspend Ready, and from Waiting to Suspend Wait. Resume takes it back from Suspend Ready to Ready, and from Suspend Wait to Waiting. Memory location note from the text: Ready, Running and Waiting processes reside in main memory (RAM); New, Suspended and Terminated (cleanup phase) processes may reside on disk (secondary storage). Takeaway: a process cycles between Ready, Running and Waiting until it exits to Terminated, and it can be parked in a suspended state and resumed along the way.

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:

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:

Execution State:

Scheduling Data:

Memory Details:

Resource Management:

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:

  1. State Save - Store current process's CPU registers, program counter, and memory management info
  2. 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:

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

Complex Memory Sharing

Sharing data between processes requires explicit mechanisms:

Performance Impact

The combination of these factors makes traditional processes:

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:

Thread-Specific Resources

Each thread maintains its own:

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:

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.

AspectUser Level Threads (ULT)Kernel Level Threads (KLT)
CreationCreated by application librariesCreated by the operating system kernel
ManagementThread operations handled by the application / thread libraryThread operations handled by the kernel
Context SwitchingFastest - no kernel involvementSlower - requires kernel involvement / system calls
Blocking BehaviorEntire process blocks when one thread blocksOnly the blocking thread blocks; other threads continue

Key Trade-offs

ULT Advantages:

ULT Disadvantages:

KLT Advantages:

KLT Disadvantages:

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

One-to-One Model

Many-to-Many Model

ModelUser ThreadsKernel Threads
Many-to-OneMany1
One-to-OneManyMany
Many-to-ManyManyFew

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:

Key scheduler responsibilities:

Performance metrics schedulers optimize:

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.

Throughput

Throughput = Processes Completed / Time Period

Turnaround Time

Total time from process arrival to completion:

Turnaround Time = Completion Time - Arrival Time

Waiting Time

Time a process spends in the ready queue waiting for CPU:

Waiting Time = Turnaround Time - Burst Time

Response Time

Time from process arrival until it first gets CPU access:

Response Time = First Response Time - Arrival Time

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:

Which algorithms cause starvation:

Prevention techniques:

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:

Key Principle: CPU switches between processes so quickly (typically every 10-100 milliseconds) that users perceive their programs as running continuously.

Response Time Requirements:

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:

  1. New process -> Job queue
  2. Admitted to memory -> Ready queue
  3. CPU allocated -> Running state
  4. 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:

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:

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:

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:

Dispatch Latency is the time overhead required to:

  1. Stop the currently running process
  2. 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)

Shortest Job First (SJF)

Longest Job First (LJF)

Highest Response Ratio Next (HRRN)

Response Ratio = (Waiting Time + Burst Time) / Burst Time

Preemptive Algorithms

Shortest Remaining Time First (SRTF)

Longest Remaining Time First (LRTF)

Round Robin (RR)

Priority Scheduling

Advanced Scheduling

Multilevel Queue Scheduling

Multilevel Feedback Queue

  1. New jobs start in highest priority queue
  2. If time slice expires -> demote to lower queue
  3. If job completes within slice -> promote to higher queue

Lottery Scheduling

Starvation Analysis

Read as: Algorithm can cause indefinite postponement of processes.

AlgorithmStarvation Risk
FCFSNo
SJFYes
SRTFYes
Round RobinNo
LJFYes
LRTFYes
Priority (both types)Yes
HRRNNo
Multilevel QueueYes
Multilevel FeedbackNo

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:

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:

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

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:

  1. Test the lock status
  2. If busy โ†’ enter wait state and retry
  3. If free โ†’ atomically set the lock and proceed
  4. 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

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;                       //

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

  1. Declare interest: Process sets its flag to 'true'
  2. Be polite: Process sets 'turn' to favor the other process
  3. Wait if needed: Process waits only if:
  1. Enter safely: If other process isn't interested OR it's our turn, proceed
  2. 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:

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:

  1. Process declares interest: interested[process] = TRUE
  2. Process gives turn to other: turn = process
  3. Process waits if other is interested AND it's still the process's turn

Exit protocol:

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

Limitations

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

Signal (V/Up): Executed after leaving critical section

Both operations execute atomically to prevent race conditions.

Binary Semaphore Initial value: s = 1

wait(S):            signal(S):
    while (S == 0);     S++;
    S--;

Limitations:

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
    }

Semaphore Value Interpretation:

Example: Printer pool with 3 printers

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:

  1. Check if lock is free
  2. If locked, keep checking repeatedly
  3. Continue until lock is acquired

The thread remains active throughout this process but performs no useful work - this is called busy waiting.

Characteristics

When to Use Effective for:

Avoid when:

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:

Synchronization Requirements:

Semaphore Solution:

semaphore mutex = 1     // Mutual exclusion
semaphore empty = n     // count of empty slots
semaphore full = 0      // count of filled slots

Producer Process:

  1. wait(empty) - ensure empty slot available
  2. wait(mutex) - acquire exclusive buffer access
  3. Add item to buffer
  4. signal(mutex) - release buffer access
  5. signal(full) - increment filled slot count

Consumer Process:

  1. wait(full) - ensure filled slot available
  2. wait(mutex) - acquire exclusive buffer access
  3. Remove item from buffer
  4. signal(mutex) - release buffer access
  5. signal(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

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

Strategy 2: Parity-Based Approach

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

Structure A monitor consists of:

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:

  1. Lock acquisition when a process enters any monitor procedure
  2. Lock release when the process exits or waits on a condition
  3. Condition queuing for processes that need to wait

Condition Variables Condition variables allow processes to:

Example: Buffer monitor with condition variables not_full and not_empty to coordinate producer-consumer operations.

Advantage Over Semaphores Monitors separate concerns:

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:

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:

  1. Mutual Exclusion

Only one process can use a resource at any given time. The resource cannot be shared among multiple processes concurrently.

  1. 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.

  1. No Preemption

Resources cannot be forcibly taken away from a process. A process must voluntarily release its resources only after completing its task.

  1. 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:

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:

  1. Prevention

Eliminate one of the four necessary conditions for deadlock:

Trade-off: Prevention reduces system efficiency and resource utilization.

  1. Avoidance

Use algorithms to ensure the system never enters an unsafe state:

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.

  1. Detection and Recovery

Allow deadlocks to occur, then detect and resolve them:

Detection methods:

Recovery options:

  1. 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

Hold and Wait Prevention

No Preemption Prevention

Circular Wait Prevention

Implementation Notes: Combined approach often used in practice:

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:

  1. Request Check: When process Pi requests resources, verify if request < available resources
  2. Tentative Allocation: Temporarily allocate the requested resources
  3. Safety Check: Run safety algorithm to check if system remains in safe state
  4. Decision: If safe, grant request; otherwise, make process wait

Safety Algorithm:

  1. Initialize work vector = available resources
  2. Mark all processes as unfinished
  3. Find process Pi where Need โ‰ค Work
  4. If found: Work = Work + Allocation of Pi, mark Pi as finished
  5. Repeat until all processes finished (safe) or no such process exists (unsafe)

Data Structures:

Example: 3 processes, 3 resource types

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:

Resource Need Calculation

Need = Max โˆ’ Allocation

where:

Banker's Algorithm Components (for multiple resource instances):

  1. Resource Request Algorithm: Checks if a resource request can be safely granted
  1. Safety Algorithm: Determines if current system state is safe

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:

Multiple Instance Resources:

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

Multiple Instance Resources: Use resource allocation matrix

When to Run Detection:

Detection algorithms consume CPU time, so timing matters:

Recovery Strategies:

Once deadlock is detected, the system must break it:

Process Termination:

Resource Preemption:

Selection Criteria for victim process:

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

Method 2: Abort one process at a time

Resource Preemption

Forcibly take resources from some processes and reassign them to break the cycle.

Three key considerations:

  1. Victim Selection: Choose which process loses its resources
  1. Rollback: Return the preempted process to a safe state
  1. Starvation Prevention: Ensure no process is repeatedly victimized

Deadlock-Free Resource Allocation:

To guarantee no deadlocks occur, ensure sufficient resources:

r โ‰ฅ p(s โˆ’ 1) + 1

where:

Example: If 4 processes each need at most 3 units of a resource:

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:

How it works:

  1. Program starts with minimal memory footprint
  2. When a routine is called for the first time, the loader fetches it from disk
  3. Routine is loaded into available memory space
  4. Subsequent calls use the already-loaded routine

Benefits:

Example: A text editor with spell-check feature

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:

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)

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:

Memory allocation:

Advantages:

Disadvantages:

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:

  1. Multiprogramming with Fixed Task (MFT)
  1. Multiprogramming with Variable Task (MVT)
  1. Overlays
  1. Buddy System (Dynamic 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:

Limitations:

Solutions to Overcome Limitations:

Overlays: Manually divide program into segments that can share memory space

Virtual Memory: Allows processes larger than physical memory

Benefits of These Solutions:

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:

How it works:

  1. Program is split into a main module (always in memory) and overlay modules
  2. When a function in an overlay module is needed, the module is loaded from disk
  3. Previously loaded overlay modules may be replaced to make space
  4. Control returns to main module after overlay execution

Example: A compiler with phases:

Only the active phase stays in memory alongside the main module.

Limitations:

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:

Allocation process:

  1. Find smallest available block โ‰ฅ request size
  2. If block is too large, split it recursively until proper size
  3. Mark allocated block as used

Deallocation and coalescing:

  1. Mark block as free
  2. Check if buddy is also free
  3. If yes, merge both blocks into larger block
  4. Repeat merging with new buddy until no more merging possible

Example: For 1MB segment starting at address 0:

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.

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:

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:

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:

Fragmentation:

Allocation Policies:

PolicyDescription
Best FitAllocate smallest suitable block
Worst FitAllocate largest available block

Why Worst Fit Works Best:

Example: Memory has blocks of 100K, 200K, 300K, Process needs 150K:

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.

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.

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.

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.

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:

Example:

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:

  1. Compaction
  1. Non-contiguous Memory Allocation

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:

  1. Block processes - Suspend all processes that will be relocated
  2. Relocate memory - Move process blocks toward lower memory addresses
  3. Update references - Adjust all memory pointers and addresses
  4. Allocate memory - Satisfy pending allocation requests from the new free space
  5. Resume processes - Restart the relocated processes

Requirements:

Trade-offs:

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:

  1. Paging
  1. Segmentation
  1. Segmented Paging
  1. Virtual Memory (Demand Paging)

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:

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:

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:

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:

  1. Hash the virtual address (PID + page number)
  2. Search inverted table for matching entry
  3. If found, frame number = table index
  4. 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:

AspectPagingSegmentation
Internal FragmentationOnly in the last pageNone - segments are exactly sized
External FragmentationNone - all pages are the same sizeYes - variable-size segments create holes over time
Programmer VisibilityTransparent - programmer is unawareVisible - programmer must manage segments

Paging characteristics:

Segmentation characteristics:

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:

Example: 32KB logical address space with 4KB pages:

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 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:

Example: 16 KB physical memory with 4 KB pages:

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:

Number of entries = Number of pages in logical address space (for single-level paging)

Each page table entry contains:

Page table size: PT_size = N x e bytes

Control Bits:

Each page table entry uses four control bits:

Address Translation Process:

The CPU generates a logical address split into two parts:

Translation steps:

  1. Extract page number p from logical address
  2. Use p to index into page table in main memory
  3. Retrieve frame number f from page table entry
  4. Combine frame number f with original displacement d
  5. Result is physical address = f + d [as shown: frame number concatenated with displacement]

Example: Logical address 1025 with page size 1024 bytes

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:

With TLB:

EMAT Formula:

EMAT = alpha(c + m) + (1 - alpha)(c + 2m)

Breaking down the formula:

Simplified form:

EMAT = c + m + (1 - alpha)m = c + m(2 - alpha)

Example: If m = 100ns, c = 10ns, TLB hit ratio = 90%

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:

Memory overhead components:

Page Table size = (S / P) x e

Internal Fragmentation = P / 2 (average unused space per page)

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:

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:

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:

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:

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:

  1. Select victim page - Choose an existing page in memory to replace
  2. Write back if dirty - If the victim page was modified, save it to disk
  3. Update page table - Mark victim page as not present, invalidate TLB entry
  4. Load new page - Read the requested page from disk into the freed frame
  5. Update page table - Mark new page as present with correct frame address
  6. Resume process - Continue execution from the faulting instruction

Implementation Strategies:

Pure Demand Paging (default approach):

Pre-paging:

Benefits:

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:

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:

  1. Process suspension: The requesting process is blocked
  2. Mode switch: System switches to kernel mode
  3. Page retrieval: Virtual Memory Manager (VMM) locates the page on disk
  4. Frame allocation: System finds space in physical memory
  5. Page loading: Disk controller transfers the page to RAM
  6. Process resumption: Blocked process continues execution

Virtual Memory Manager Flow:

The VMM coordinates with system components in this sequence:

VMM Device Manager Device Driver Disk
Virtual Memory Manager Flow. A single horizontal flow line with four labelled nodes connected by arrows, left to right, in this order: VMM, then Device Manager, then Device Driver, then Disk. Each arrow points from one node to the next: VMM to Device Manager, Device Manager to Device Driver, and Device Driver to Disk. No other boxes, labels or values are shown. Takeaway: when a page fault is handled, the Virtual Memory Manager coordinates through the Device Manager and the Device Driver to fetch the needed page from Disk.

Frame Allocation Scenarios:

Case 1: Free frame available

Case 2: No free frames

Performance Impact:

Page Fault Service Time (PFST) directly affects system performance:

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:

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

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:

Algorithms affected by Belady's Anomaly:

Example scenario: Reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5

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:

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

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:

Example: Pages in memory with access counts:

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:

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

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:

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:

  1. Check oldest page's reference bit
  2. If R = 0: Replace this page
  3. If R = 1: Set R = 0, move to next oldest page
  4. Repeat until finding a page with R = 0

Example: Pages in FIFO order: A(R=1), B(R=0), C(R=1)

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):

Replacement Priority (best to worst):

  1. (R = 0, M = 0): Not used, clean - best choice
  2. (R = 0, M = 1): Not used, dirty - needs write-back
  3. (R = 1, M = 0): Recently used, clean
  4. (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:

Beyond the optimal point, adding more processes triggers thrashing, causing CPU utilisation to plummet despite high system activity.

Root Causes:

Primary causes:

Secondary causes:

Page Size Impact:

Page SizeAdvantages
LargeFewer page faults, reduced overhead
SmallBetter 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:

Recovery:

Immediate actions:

Long-term solutions:

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:

  1. Sequential access: Data is read or written in order from beginning to end
  2. Random access: Any byte can be accessed directly without reading preceding data

File System Components

A complete file system includes four essential components:

System Architecture

The file system operates through multiple layers that abstract hardware complexity:

Software Layer:

Hardware Layer:

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

Logical File System

File Organization Module

Basic File System

I/O Control Layer

Physical Devices

Key Benefits

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

Large Files Consume Space

I/O Transfer Patterns

Design Implications

Example: In a typical system with 1000 files:

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

Record Structure

Tree Structure

File Operations

Standard operations available on files:

File Attributes

Key properties that describe a file:

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:

File Control Block (FCB)

The FCB stores metadata about each file, including ownership, permissions, and location information. Different file systems implement this differently:

File Allocation Methods

Contiguous Allocation

Files are stored in consecutive disk blocks.

Linked Allocation

Each file block contains a pointer to the next block in the file.

Indexed Allocation

Uses an index block to track all file block locations directly.

Multilevel Indexed Allocation

Uses multiple levels of index blocks for large files. The inode structure contains pointers that work hierarchically:

Free Space Management

Bitmap Method

Uses a bit vector where each bit represents one disk block.

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.

Grouping Method

Stores addresses of n free blocks in the first free block.

Counting Method

Stores pairs of (starting block number, count of consecutive blocks).

Disk Scheduling Algorithms

First-Come First-Served (FCFS)

Shortest Seek Time First (SSTF)

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:

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:

Key characteristics:

Example: Requests at tracks [23, 89, 132, 42, 124], head at track 53, moving outward

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:

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:

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:

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

  1. Services: 89 โ†’ 132 โ†’ 187 (rightward)
  2. Reverses at 187 (last request, not disk end)
  3. 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.