Operating System Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to Operating Systems
Module 2
Process Management
Module 3
Memory Management
Module 4
Storage Management
Module 5
Distributed, Real-Time & Modern Operating Systems
Read Module Notes Online
Module I: Introduction to Operating Systems
Chapter 1: Operating System Fundamentals and Computer System Architecture
1.1 What Operating Systems Do and Evolution of OS
An Operating System (OS) is the foundational system software that manages computer hardware, provides common services for application programs, and acts as an intermediary between users and the underlying physical machine. A complete computer system can be viewed as four layered components: hardware (CPU, main memory, I/O devices), the operating system, application programs (compilers, database engines, web browsers, text editors), and users (humans, other machines, or automated services). Without an operating system, every application developer would need to write low-level hardware drivers, manage interrupt vectors directly, and manually partition memory across concurrent tasks.
The role of an operating system is understood from two complementary perspectives: the user view and the system view. From the user view on personal workstations and mobile devices, the operating system is designed primarily for ease of use, responsiveness, and resource accessibility, with secondary attention to hardware utilization. On shared servers, mainframes, and cloud clusters, multiple users share finite CPU cores, RAM, and storage; here, the operating system must maximize aggregate throughput while guaranteeing fair resource isolation. On embedded microcontrollers in automobiles, medical instruments, or home appliances, the user interface is minimal or absent, and the operating system operates autonomously with deterministic timing.
From the system view, the operating system is a resource allocator and a control program. As a resource allocator, the OS arbitrates among competing requests for CPU cycles, physical memory frames, file storage blocks, and I/O bandwidth, resolving conflicts fairly and efficiently. As a control program, it supervises the execution of user programs to prevent errors, unauthorized memory accesses, and improper use of hardware devices. At the core of every operating system lies the kernel—the single continuously running program resident in privileged memory from boot until shutdown—while middleware, system utilities, and graphical shells execute outside the kernel.
Operating systems evolved through distinct generations to overcome hardware bottlenecks. Early 1950s systems had no OS; programmers signed up for dedicated machine blocks. Simple Batch Systems introduced resident monitors that automatically sequenced jobs punched onto cards, eliminating manual operator setup delays. To overlap slow mechanical card-reader I/O with fast CPU execution, Spooling (Simultaneous Peripheral Operation On-Line) buffered input and output jobs onto magnetic disks. Multiprogrammed Batch Systems kept multiple jobs in main memory simultaneously: whenever the active job paused for I/O, the OS switched the CPU to another ready job, keeping processor utilization high. Time-Sharing (Multitasking) Systems extended multiprogramming by switching the CPU among interactive users every few milliseconds, giving each user the illusion of a dedicated machine.
1.2 Computer System Organization
A modern general-purpose computer system consists of one or more Central Processing Units (CPUs) and multiple device controllers connected through a common system bus that provides access to shared main memory. Each device controller (such as a disk controller, USB host controller, or network adapter) manages a specific class of peripheral devices, maintains local buffer storage and special-purpose registers, and transfers data between its attached peripheral and local buffer. The operating system supplies a device driver for each controller, presenting a uniform logical interface to the rest of the kernel.
When a computer powers on or resets, an initial bootstrap program stored in non-volatile Read-Only Memory (ROM) or Electrically Erasable Programmable Read-Only Memory (EEPROM/UEFI firmware) executes. The bootstrap program initializes CPU registers, device controllers, and memory timings, runs Power-On Self-Test (POST) diagnostics, locates the operating system kernel on secondary storage (via the Master Boot Record or GUID Partition Table EFI System Partition), loads the kernel into main memory, and transfers control to the kernel entry point. Once running, the OS waits for events signaled via interrupts.
Hardware devices trigger an interrupt by asserting a signal on the interrupt-request line connected to the CPU, whereas software programs generate a trap (or exception) either due to an error (such as division by zero, page fault, or an invalid memory address) or via an explicit request for an OS service (system call). When an interrupt occurs, the CPU finishes its current instruction, saves the Program Counter (PC) and processor status register onto the kernel stack, disables or masks lower-priority interrupts, and jumps to the fixed address in the Interrupt Vector Table (IVT) pointing to the corresponding Interrupt Service Routine (ISR). After the ISR processes the event and clears the device status flag, the saved CPU state is restored via a return-from-interrupt instruction and the interrupted computation resumes seamlessly.
Storage in a computer system is organized as a hierarchy balancing access latency, cost per bit, and volatility. CPU registers and L1/L2/L3 static RAM (SRAM) caches deliver sub-nanosecond to few-nanosecond access times but have limited capacity and high cost. Main memory (Dynamic RAM, DRAM) holds active programs and data during execution, while non-volatile storage—Solid-State Drives (SSDs using NAND flash), magnetic Hard Disk Drives (HDDs), optical media, and magnetic tapes—retains persistent file systems across power cycles. For high-speed bulk transfers, Direct Memory Access (DMA) enables a device controller to move entire blocks of data directly between its local buffer and main memory via bus-mastering cycle stealing without continuous CPU intervention, generating only a single interrupt per block rather than one interrupt per byte.
| Storage Tier | Technology | Typical Access Latency | Volatility & OS Management Role |
|---|---|---|---|
| CPU Registers | Flip-flop CMOS logic | 0.25 – 0.5 ns | Volatile; managed by compiler and context-switch dispatcher |
| Cache (L1/L2/L3) | Static RAM (SRAM) | 1 – 15 ns | Volatile; hardware-managed with OS cache-coloring hints |
| Main Memory | Dynamic RAM (DDR4/DDR5) | 50 – 100 ns | Volatile; managed by OS virtual memory and page allocator |
| Solid-State Drive | NAND Flash (NVMe) | 20 – 100 microseconds | Non-volatile; managed via block layer, wear leveling, and file system |
| Hard Disk Drive | Magnetic platters | 4 – 12 milliseconds | Non-volatile; managed via OS disk scheduler and buffer cache |
| Optical / Tape | Laser / Magnetic tape | 100 ms – seconds | Non-volatile; used for archival backup and cold storage |
1.3 Computer System Architecture
Computer architectures are classified according to the number and organization of general-purpose processors used to execute workloads:
- Single-Processor Systems: Historically dominant machines containing one main CPU capable of executing a general-purpose instruction set, alongside specialized microcontrollers (such as keyboard, disk, or GPU controllers) that perform dedicated tasks without running user processes.
- Multiprocessor Systems (Parallel / Tightly Coupled): Systems with two or more processors sharing a common system bus, clock, main memory, and peripheral devices. They offer increased throughput, economy of scale through shared power and storage, and increased reliability via graceful degradation (fault tolerance) when one processor fails. Multiprocessor designs follow either Asymmetric Multiprocessing (AMP), where a boss processor assigns tasks to worker processors, or Symmetric Multiprocessing (SMP), where every processor executes all OS tasks as peers. Modern multicore chips place multiple computing cores on a single integrated silicon die, each with private L1 caches and a shared L2/L3 cache; Non-Uniform Memory Access (NUMA) architectures attach local DRAM banks to each CPU socket so local memory accesses are faster than remote cross-socket accesses.
- Clustered Systems (Loosely Coupled): Architectures that link two or more independent computer systems (nodes) over a high-speed local area network or InfiniBand fabric, sharing access to a Storage Area Network (SAN). Asymmetric clustering keeps one node in hot-standby mode monitoring the active server for high availability, whereas symmetric clustering runs applications concurrently on all nodes and balances workloads dynamically.
Worked Numerical Example (Multiprocessor Speedup): Suppose an operating system kernel workload is 75% parallelizable () and 25% strictly serial () due to spinlock contention. If the system scales from 1 core to cores, the speedup is:
Chapter 2: Operating System Operations, Structures, and Distributed Systems
2.1 Dual-Mode Operation and Hardware Protection
Because an operating system shares hardware among multiple concurrent programs, a bug or malicious instruction in one user program must not corrupt the kernel or other user applications. Modern CPUs enforce this boundary through dual-mode (or multimode) operation using a hardware mode bit in the processor status register: mode bit 0 indicates kernel mode (supervisor/privileged mode), while mode bit 1 indicates user mode. Privileged instructions—such as halting the machine, modifying base-and-limit memory registers, disabling interrupts, loading page-table pointers, or initiating direct I/O—are permitted only in kernel mode. If a user-mode program attempts to execute a privileged instruction, the hardware raises an illegal-instruction trap and transfers control to the OS kernel.
At boot time, the hardware initializes in kernel mode, loads the OS, and switches to user mode before starting user applications. Whenever a system call, interrupt, or exception occurs, the hardware automatically switches to kernel mode, runs the kernel handler, and resets the mode bit to user mode upon return. To prevent a user process from monopolizing the CPU in an infinite loop, the OS configures a programmable hardware timer that generates periodic interrupts (e.g., every 1 to 10 milliseconds). Because resetting the timer counter is a privileged instruction, no user program can disable time-sharing preemption.
Modern processors extend dual-mode operation into multimode rings or virtualization modes: x86 processors provide four privilege rings (Ring 0 for kernel, Ring 3 for user applications) plus hardware virtualization modes (VMX root mode for hypervisors and VMX non-root mode for guest OS kernels), while ARMv8 provides Exception Levels EL0 (user), EL1 (OS kernel), EL2 (hypervisor), and EL3 (secure monitor).
2.2 Operating System Structures
The internal architecture of an operating system dictates its performance, modularity, security, and maintainability. Five major structural models have evolved across OS history:
| OS Structure | Architectural Organization | Key Advantages | Primary Limitations |
|---|---|---|---|
| Simple / Monolithic | All OS services (file system, memory, scheduling, drivers) run in a single kernel address space | Minimal system-call overhead; fast intra-kernel function calls | Tight coupling; a bug in one driver can crash the entire kernel |
| Layered Approach | OS divided into N hierarchical layers (Layer 0 = hardware, Layer N = user interface) | Clean modularity, easier debugging and verification per layer | Careful layer ordering required; performance overhead crossing layers |
| Microkernel | Minimal kernel (IPC, basic scheduling, low-level memory); services run in user space | High reliability, security isolation, easy portability | Frequent context switches and message-passing IPC overhead |
| Modular (Loadable) | Core kernel with dynamically loadable kernel modules (LKMs) at runtime | Combines monolithic speed with layered flexibility (e.g., Linux, Solaris) | Loaded modules still share kernel address space |
| Hybrid Systems | Blends microkernel message passing with monolithic performance-critical subsystems | Balanced responsiveness and modularity (e.g., Windows NT, macOS XNU) | Increased architectural complexity across subsystem boundaries |
In a monolithic kernel such as traditional UNIX or MS-DOS, there is minimal internal structure; MS-DOS provided no dual-mode hardware protection, allowing applications direct BIOS and hardware access, whereas original UNIX split the system into the kernel and user-space system programs, with all kernel subsystems compiled into one binary. The layered approach (pioneered by Dijkstra's THE operating system) enforces strict top-down invocation: layer may invoke operations only from layer , simplifying verification but introducing overhead when I/O requests traverse many layers. Microkernels (such as Mach, QNX, and L4) strip the kernel down to essential IPC, address-space management, and thread scheduling, running file systems and device drivers as isolated user-space servers. Modern Linux and BSD systems adopt Loadable Kernel Modules (LKMs), allowing device drivers and file systems to be inserted (insmod/modprobe) and removed dynamically without rebooting.
2.3 Distributed Systems
A distributed system is a collection of physically separate, potentially heterogeneous computer nodes networked together to provide users with shared access to computational, data, and peripheral resources. Unlike tightly coupled multiprocessor systems that share a physical memory bus and clock, distributed nodes communicate exclusively by exchanging messages over a communication network (such as TCP/IP over Ethernet or fiber links). A Network Operating System (NOS) provides file sharing, remote login, and inter-node messaging while preserving each node's autonomous OS identity. By contrast, a true Distributed Operating System presents the illusion of a single unified system image, transparently migrating processes and balancing loads across nodes.
Distributed systems are built for four primary reasons: resource sharing (printers, specialized GPUs, databases), computation speedup (partitioning large jobs across many nodes), reliability (replication ensures service continuity if individual nodes fail), and communication (collaborative workflows and distributed transactions). Key architectural models include client-server systems (dedicated compute/file servers responding to client requests) and peer-to-peer (P2P) systems (symmetric nodes acting simultaneously as clients and servers without a central bottleneck).
Chapter 3: OS Services, User Interfaces, and System Calls
3.1 Operating System Services
An operating system provides an execution environment with standardized services aimed at both human users and application programs:
- User Interface (UI): Supplies Command-Line Interfaces (CLI), Batch interfaces, or Graphical User Interfaces (GUI) for launching and controlling programs.
- Program Execution: Loads executable binaries into main memory, initializes stacks and heaps, runs the program, and handles normal or abnormal termination.
- I/O Operations: Abstracts raw device registers into uniform read/write operations for files, terminals, disks, and network sockets.
- File-System Manipulation: Enables creation, deletion, reading, writing, searching, and permission enforcement on named files and hierarchical directories.
- Communications: Supports inter-process data exchange on the same host (shared memory) or across network hosts (message passing).
- Error Detection: Continuously monitors hardware (CPU parity, memory ECC, disk bad sectors, network timeouts) and software faults (illegal memory references, arithmetic overflow) to take corrective action.
- Resource Allocation, Accounting, and Protection: Schedules CPU cycles and memory across concurrent jobs, logs resource consumption for billing or capacity planning, and enforces access control so processes cannot interfere with one another or unauthorized external users.
3.2 User Operating System Interfaces
Users interact with the operating system primarily through a Command-Line Interface (CLI) or a Graphical User Interface (GUI). A CLI, implemented by a command interpreter or shell (such as Bash, Zsh, or PowerShell), reads text commands from the user and executes them either internally within the shell process (built-in commands like cd or export) or by spawning external utility programs (such as ls, grep, or cp). Shells support I/O redirection, pipelines, environment variables, and shell scripting for automated administration. A GUI provides a desktop metaphor using windows, icons, menus, and pointer/touch gestures (such as Windows Explorer, macOS Finder, or GNOME/KDE on Linux). Mobile and embedded devices employ touch-screen gestures and voice interfaces tailored to constrained displays. Most modern systems provide both a GUI for everyday productivity and a CLI for scripting, automation, and remote system administration.
3.3 System Calls and APIs
System calls provide the programmatic interface to the services made available by an operating system. Typically written in C or C++ (with small assembly stubs for hardware traps), system calls allow user-mode processes to request kernel-mode operations safely. Application developers rarely invoke raw system calls directly; instead, they call standardized Application Programming Interfaces (APIs) such as the POSIX API (on Linux, UNIX, and macOS), the Win32 API (on Windows), or the Java API. Using an API ensures program portability across any OS supporting that API and hides low-level register conventions.
When an application invokes an API function (such as read()), the C standard library (glibc) places the system-call number and parameters into designated CPU registers (or onto the user stack/memory block, passing the block address in a register) and executes a software trap instruction (such as syscall on x86-64 or svc on ARM). The hardware switches to kernel mode, looks up the system-call number in the kernel's system-call dispatch table, executes the corresponding kernel routine, places the return value in a register, and returns to user mode.
| System Call Category | Representative Operations | POSIX / UNIX Examples | Windows Win32 Examples |
|---|---|---|---|
| Process Control | Create, terminate, load, execute, wait, allocate memory | fork(), exec(), exit(), wait() |
CreateProcess(), ExitProcess(), WaitForSingleObject() |
| File Manipulation | Create, delete, open, close, read, write, reposition | open(), read(), write(), close() |
CreateFile(), ReadFile(), WriteFile(), CloseHandle() |
| Device Manipulation | Request device, release device, read/write device attributes | ioctl(), read(), write() |
SetConsoleMode(), ReadConsole(), WriteConsole() |
| Information Maintenance | Get/set time or date, get system data, get/set process attributes | getpid(), alarm(), sleep() |
GetCurrentProcessId(), SetTimer(), Sleep() |
| Communications | Create/delete connection, send/receive messages, attach shared memory | pipe(), shm_open(), mmap(), socket() |
CreatePipe(), MapViewOfFile() |
| Protection | Get/set file permissions, allow/deny user access | chmod(), umask(), chown() |
SetFileSecurity(), InitializeSecurityDescriptor() |
#include <fcntl.h>
#include <unistd.h>
int main(void) {
char buffer[4096];
ssize_t bytesRead;
int srcFd = open("source.txt", O_RDONLY);
if (srcFd < 0) return 1;
int dstFd = open("dest.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dstFd < 0) { close(srcFd); return 1; }
while ((bytesRead = read(srcFd, buffer, sizeof(buffer))) > 0) {
write(dstFd, buffer, bytesRead);
}
close(srcFd);
close(dstFd);
return 0;
}Chapter 4: Processes, Process States, PCB, and Threads
4.1 The Process Concept
A process is a program in execution—an active entity that requires resources such as CPU time, memory, files, and I/O devices to accomplish its task. By contrast, a program is a passive entity, such as an executable binary file stored on disk. When a program is loaded into memory and begins executing, it becomes a process. Multiple processes may run the same program concurrently (for instance, two users running separate instances of a text editor); although their text (code) sections may be identical and even shared read-only in memory, each process maintains its own execution state.
The memory layout of a process is divided into four distinct segments:
- Text Section: Contains the compiled machine instructions of the program, typically marked read-only to prevent accidental self-modification.
- Data Section: Stores initialized global/static variables (
.data) and uninitialized global/static variables (.bss, zero-initialized by the OS loader) whose lifetimes span the entire execution of the process. - Heap: Dynamically allocated memory region (managed via
malloc()/free()ornew) that grows upward toward higher addresses during runtime. - Stack: Temporary storage for function parameters, return addresses, and local variables, growing downward as nested functions are invoked and shrinking upon return.
4.2 Process States and State Transitions
As a process executes, it transitions dynamically among five fundamental states:
- New: The process is being created by the operating system; its initial metadata and address space are being allocated.
- Ready: The process is loaded in main memory and possesses all required resources except the CPU; it waits in the ready queue to be assigned to a processor core.
- Running: Instructions of the process are actively executing on a CPU core. At any instant, at most one process (or one thread) can be running on a single CPU core.
- Waiting (Blocked): The process cannot continue executing until some external event occurs, such as completion of a disk read, arrival of a network packet, or availability of a synchronization lock.
- Terminated: The process has finished execution (or been aborted by a signal), and the operating system reclaims its allocated memory, open file descriptors, and kernel structures.
4.3 Process Control Block (PCB)
Each process is represented in the operating system kernel by a Process Control Block (PCB), also called a Task Control Block (TCB). The PCB serves as the repository for all information needed to pause and later resume a process during a context switch. A typical PCB stores the following fields:
- Process Identifier (PID) & State: Unique integer PID, parent PID, and current state (New, Ready, Running, Waiting, Terminated).
- Program Counter (PC): Memory address of the next instruction to be executed for this process.
- CPU Registers: Accumulators, index registers, stack pointers, and condition-code flags saved whenever an interrupt or context switch occurs.
- CPU Scheduling Information: Process priority, pointers to scheduling queues, and accumulated CPU burst statistics.
- Memory-Management Information: Base and limit register values, page tables, or segment tables defining the process's virtual-to-physical address mapping.
- Accounting Information: User/kernel CPU time consumed, wall-clock start time, and resource limits.
- I/O Status Information: List of I/O devices allocated to the process and the table of open file descriptors.
Worked Numerical Example (Context-Switch Overhead): If a batch workload requires of CPU computation and experiences context switches, each taking (20 microseconds), total elapsed time is , meaning context switching adds 10% overhead.
4.4 Threads and Multithreading
A thread is the basic unit of CPU utilization, consisting of a thread ID, a program counter, a register set, and a private execution stack. Unlike heavyweight processes that each possess an isolated address space, all threads belonging to the same process share the code (text) section, global data section, heap memory, and operating-system resources such as open files and signals. Because threads share memory directly, creating a new thread or switching between threads of the same process requires far less overhead than creating or context-switching separate processes.
Multithreading delivers four major benefits: responsiveness (a GUI application remains interactive while a background worker thread performs network I/O), resource sharing (threads share heap data without explicit IPC copies), economy (thread creation and context switching are orders of magnitude faster than process creation), and scalability (on multicore CPUs, multiple threads of one process run truly in parallel on separate cores). Multithreading models map user-level threads (managed by a user-space library) to kernel-level threads (scheduled by the OS kernel) in three ways:
- Many-to-One Model: Maps many user-level threads to a single kernel thread. Thread switching is fast in user space, but if one thread makes a blocking system call, the entire process blocks, and multiple threads cannot run in parallel on multicore CPUs.
- One-to-One Model: Maps each user thread to a dedicated kernel thread (used by Linux NPTL and Windows). Provides true multicore concurrency and non-blocking I/O, though creating too many threads can burden kernel memory.
- Many-to-Many Model: Multiplexes many user-level threads onto a smaller or equal pool of kernel threads, balancing concurrency with bounded kernel overhead; a two-level variation also allows pinning critical threads to specific kernel threads.
#include <pthread.h>
#include <stdio.h>
long shared_sum = 0;
void* worker(void* arg) {
long limit = *(long*)arg;
long local = 0;
for (long i = 1; i <= limit; i++) {
local += i;
}
shared_sum = local;
return NULL;
}
int main(void) {
pthread_t tid;
long n = 1000;
pthread_create(&tid, NULL, worker, &n);
pthread_join(tid, NULL);
printf("Computed sum: %ld\n", shared_sum);
return 0;
}4.5 Threading Issues, Thread Pools, and Process vs Thread Comparison
Designing multithreaded applications introduces subtle operating system interactions that do not arise in single-threaded processes. When a thread calls fork(), some UNIX implementations duplicate all threads of the parent process, whereas others duplicate only the calling thread (because calling exec() immediately afterward would discard the duplicated threads anyway). Signal handling also becomes complex: synchronous signals (such as illegal memory access or division by zero) are delivered to the specific thread that caused them, whereas asynchronous signals (such as Ctrl+C or a timer expiration) may be delivered to every thread, to one designated signal-handling thread, or to the first thread not masking that signal.
Thread cancellation terminates a target thread before it has finished its work. Asynchronous cancellation immediately destroys the target thread, risking leaked mutex locks or partially updated shared structures. Deferred cancellation sets a cancellation flag that the target thread checks periodically at safe cancellation points (such as blocking I/O calls), allowing orderly resource cleanup. To bound thread-creation overhead in busy servers, operating systems and runtime libraries provide Thread Pools: a fixed or dynamically bounded number of worker threads are created at startup and wait on a shared task queue, eliminating repeated thread creation/destruction latency and preventing resource exhaustion under bursty request loads.
Implicit threading delegates thread creation and management from application programmers to compilers and runtime libraries—examples include OpenMP (compiler directives such as #pragma omp parallel for that automatically distribute loop iterations across cores), Grand Central Dispatch (dispatch queues on macOS/iOS), and Intel Threading Building Blocks (TBB). Finally, Thread-Local Storage (TLS) allows each thread to maintain its own private copy of data that persists across function calls (such as per-thread errno or transaction IDs).
| Architectural Dimension | Process | Thread (Kernel-Level) |
|---|---|---|
| Address Space | Isolated virtual address space (Text, Data, Heap, Stack) | Shares Text, Data, Heap, and open files; private Stack & Registers |
| Creation & Switching Cost | Heavyweight; requires copying page tables and flushing/tagging TLB | Lightweight; shares page tables, minimal register/stack switch |
| Inter-Entity Communication | Requires explicit OS IPC (pipes, sockets, shared memory) | Direct read/write via shared heap/global variables (requires mutexes) |
| Fault Isolation | High; a crash in one process does not corrupt sibling processes | Low; an uncaught segmentation fault terminates the entire process |
Module II: Process Management
Chapter 5: Process Scheduling and Interprocess Communication
5.1 Process Scheduling Queues and Schedulers
The objective of multiprogramming is to have some process running at all times to maximize CPU utilization, whereas the objective of time-sharing is to switch the CPU among processes so frequently that users can interact with each program while it runs. To achieve this, the operating system maintains scheduling queues. As processes enter the system, they are placed in the job/ready queue—typically implemented as a linked list or priority tree of PCBs residing in main memory and waiting to execute. Processes waiting for a specific I/O device (such as a disk drive or network socket) are placed in device wait queues.
Three schedulers govern process movement across queues. The long-term scheduler (job scheduler) selects processes from a mass-storage spool pool and loads them into main memory for execution, controlling the degree of multiprogramming (the number of processes in memory). It must balance I/O-bound processes (which spend more time performing I/O than computing) and CPU-bound processes (which spend most of their time doing computations) so neither the CPU nor the I/O subsystem sits idle. The short-term scheduler (CPU scheduler) selects from among the processes in the ready queue and allocates the CPU core to one of them; because it runs every few milliseconds, it must be extremely fast. Some time-sharing systems also include a medium-term scheduler that performs swapping—temporarily removing partially executed processes from RAM to disk to reduce memory pressure and reintroducing them later.
5.2 Operations on Processes
Processes in an operating system can be created and terminated dynamically, forming a process tree rooted at an initial system process (such as init or systemd with PID 1 in UNIX/Linux). During process creation, a parent process invokes a system call such as fork() (in POSIX) or CreateProcess() (in Windows). Resource sharing options range from sharing all resources, sharing a subset, to complete isolation. Execution options allow the parent to continue running concurrently with the child or to call wait() until the child terminates. In POSIX systems, fork() duplicates the parent's address space (optimized via Copy-on-Write), and the child commonly calls exec() to replace its memory image with a new executable program.
A process terminates when it finishes executing its final statement and invokes exit(), returning an integer exit status to its waiting parent and releasing all memory, open files, and I/O buffers back to the OS. A parent may also forcibly terminate a child (via kill() or TerminateProcess()) if the child exceeds allocated resources, its task is no longer needed, or the parent itself is exiting (cascading termination). If a child terminates before its parent calls wait(), it enters a zombie state—its memory is freed, but its PCB entry remains in the process table to hold its exit status until the parent reaps it. If a parent exits without waiting, its children become orphans and are adopted by init/systemd.
5.3 Interprocess Communication (IPC)
Concurrent processes executing in an operating system are either independent (they cannot affect or be affected by other processes) or cooperating (they can affect or be affected by other processes through shared data or signals). Cooperating processes require Interprocess Communication (IPC) mechanisms to exchange data and synchronize actions. Two fundamental IPC models exist:
- Shared Memory: A region of physical memory is mapped into the virtual address spaces of two or more cooperating processes. After the OS establishes the shared segment (via
shm_open()andmmap()), processes read and write directly at memory speed without kernel intervention, though the application programmer must explicitly synchronize concurrent writes. - Message Passing: Processes communicate without sharing address spaces by invoking kernel-mediated
send(message)andreceive(message)primitives. Communication links may be direct (naming the peer process explicitly) or indirect (via mailboxes/ports), synchronous (blocking) or asynchronous (non-blocking), and buffered with zero, bounded, or unbounded capacity. Ordinary pipes (unidirectional, parent-child), named pipes (FIFOs), and network sockets are classic message-passing mechanisms.
#define BUFFER_SIZE 10
typedef struct { int data; } item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
void produce(item next_produced) {
while (((in + 1) % BUFFER_SIZE) == out)
; // Buffer full: wait
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
}
item consume(void) {
while (in == out)
; // Buffer empty: wait
item next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
return next_consumed;
}5.4 Preemptive vs Non-Preemptive Scheduling, Dispatcher, and Criteria
CPU scheduling decisions take place under four circumstances: (1) when a process switches from running to waiting (e.g., an I/O request), (2) when a process switches from running to ready (e.g., an interrupt or time-quantum expiration), (3) when a process switches from waiting to ready (e.g., I/O completion), and (4) when a process terminates. Scheduling under circumstances 1 and 4 only is termed non-preemptive (cooperative): once the CPU is allocated to a process, it keeps the CPU until it voluntarily yields or terminates. Scheduling that also intervenes under circumstances 2 and 3 is preemptive, allowing the OS to interrupt a running process to enforce time sharing or priority guarantees, at the cost of requiring careful synchronization of shared kernel data structures.
The dispatcher is the kernel module that gives control of the CPU to the process selected by the short-term scheduler. Its functions include switching context (saving the old PCB and loading the new PCB), switching to user mode, and jumping to the proper location in the user program to restart execution. The time the dispatcher takes to stop one process and start another is called dispatch latency.
| Scheduling Criterion | Definition | Optimization Goal |
|---|---|---|
| CPU Utilization | Percentage of time the CPU is actively executing instructions | Maximize (typically 40%–90% in real systems) |
| Throughput | Number of processes completed per unit of time | Maximize |
| Turnaround Time | Total interval from process submission to process completion () | Minimize |
| Waiting Time | Total time a process spends waiting in the ready queue () | Minimize |
| Response Time | Time from request submission until the first response is produced | Minimize (critical for interactive systems) |
Chapter 6: CPU Scheduling Algorithms and Worked Examples
6.1 First-Come, First-Served (FCFS) Scheduling
FCFS is the simplest CPU scheduling algorithm: the process that requests the CPU first is allocated the CPU first, using a standard First-In, First-Out (FIFO) ready queue. FCFS is strictly non-preemptive. While trivial to implement and free of starvation, its average waiting time can be very high when a long CPU-bound process arrives ahead of several short processes—a phenomenon known as the convoy effect, where short I/O-bound processes pile up behind one slow CPU-bound job.
6.2 Shortest-Job-First (SJF) and SRTF Scheduling
SJF associates with each process the length of its next CPU burst and schedules the process with the smallest next CPU burst. SJF is provably optimal in minimizing average waiting time for a given set of processes. It exists in two variants: non-preemptive SJF (the running process finishes its burst) and preemptive SJF, known as Shortest-Remaining-Time-First (SRTF), where a newly arriving process with a shorter burst than the remaining time of the current process preempts the CPU. Because exact future CPU bursts are unknown, operating systems estimate them using exponential averaging of past bursts:
6.3 Priority Scheduling, Round-Robin, and Multilevel Queues
In Priority Scheduling, each process is assigned an integer priority, and the CPU is allocated to the ready process with the highest priority (by convention in many textbooks, smaller integers denote higher priority). Priority scheduling can be preemptive or non-preemptive. A major hazard is starvation (indefinite blocking), where low-priority processes wait forever under a steady stream of high-priority arrivals. Aging solves starvation by gradually increasing the priority of processes that wait in the system for a long time.
Round-Robin (RR) scheduling is designed specifically for time-sharing systems. It resembles FCFS with preemption added: a small fixed unit of time called a time quantum (or time slice), typically 10 to 100 milliseconds, is defined. The ready queue operates as a circular FIFO queue. Each process runs for at most one time quantum; if its burst completes earlier, it releases the CPU voluntarily; otherwise, a timer interrupt preempts it and moves it to the tail of the ready queue. Selecting the time quantum involves a trade-off: if it is too large, RR degenerates into FCFS; if it is too small, frequent context switches degrade CPU efficiency.
Multilevel Queue (MLQ) scheduling partitions the ready queue into separate queues (such as foreground interactive processes using RR and background batch processes using FCFS), with fixed-priority or time-slice scheduling among queues. Multilevel Feedback Queue (MLFQ) scheduling improves upon MLQ by allowing processes to migrate between queues: a process using too much CPU time is demoted to a lower-priority queue, while an aging process waiting too long in a lower queue is promoted upward.
6.4 Worked Numerical Comparison of Scheduling Algorithms
Consider four processes arriving at time 0 in order P1, P2, P3, P4 with CPU bursts: P1 = 8 ms (Priority 3), P2 = 4 ms (Priority 1), P3 = 9 ms (Priority 4), P4 = 5 ms (Priority 2), where priority 1 is highest:
| Algorithm (All Arrival = 0) | Execution Order (Gantt Sequence) | Individual Waiting Times | Average Waiting Time | Average Turnaround Time |
|---|---|---|---|---|
| FCFS | P1(0-8), P2(8-12), P3(12-21), P4(21-26) | P1=0, P2=8, P3=12, P4=21 | ms | ms |
| SJF (Non-Preemptive) | P2(0-4), P4(4-9), P1(9-17), P3(17-26) | P2=0, P4=4, P1=9, P3=17 | ms | ms |
| Priority (1 = Highest) | P2(0-4), P4(4-9), P1(9-17), P3(17-26) | P2=0, P4=4, P1=9, P3=17 | ms | ms |
| Round-Robin (q = 4) | P1(0-4), P2(4-8), P3(8-12), P4(12-16), P1(16-20), P3(20-24), P4(24-25), P3(25-26) | P1=12, P2=4, P3=17, P4=20 | ms | ms |
Worked Staggered-Arrival SRTF Example: Now suppose processes arrive at different times: P1(AT=0, BT=8), P2(AT=1, BT=4), P3(AT=2, BT=9), P4(AT=3, BT=5). At t=0, P1 starts. At t=1, P2 arrives with BT=4 < P1's remaining 7, so P2 preempts P1. At t=2, P3 arrives (BT=9 > 3). At t=3, P4 arrives (BT=5 > 2). P2 finishes at t=5. Among ready processes P4(5), P1(7), P3(9), P4 runs from 5 to 10, P1 runs from 10 to 17, and P3 runs from 17 to 26. Waiting times are: P1 = 17 - 0 - 8 = 9 ms, P2 = 5 - 1 - 4 = 0 ms, P3 = 26 - 2 - 9 = 15 ms, P4 = 10 - 3 - 5 = 2 ms. Average waiting time = .
Chapter 7: Process Synchronization
7.1 The Critical-Section Problem
When cooperating processes or threads share writable variables, memory buffers, or files, the final outcome can depend on the exact timing of context switches—a defect known as a race condition. The segment of code in each process that accesses shared modifiable resources is called its critical section. To eliminate race conditions, any valid solution to the critical-section problem must satisfy three strict requirements:
- Mutual Exclusion: If process is executing in its critical section, no other process may execute in its critical section simultaneously.
- Progress: If no process is in its critical section and some processes wish to enter, only those processes not executing in their remainder sections may participate in deciding who enters next, and this selection cannot be postponed indefinitely.
- Bounded Waiting: There exists a bound on the number of times other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted, preventing starvation.
Peterson's Solution is a classic software-based two-process algorithm using two shared variables—int turn and boolean flag[2]—that guarantees mutual exclusion, progress, and bounded waiting on sequentially consistent memory. On modern multicore hardware with out-of-order execution, operating systems rely on atomic hardware instructions such as test_and_set() and compare_and_swap() to construct spinlocks and mutexes.
7.2 Semaphores and Classic Synchronization Problems
A semaphore is an integer synchronization variable invented by Edsger Dijkstra that, apart from initialization, is accessed only through two indivisible (atomic) standard operations: wait(S) (historically P(S)) and signal(S) (historically V(S)). In a counting semaphore, can range over an unrestricted integer domain to control access to a resource pool with multiple identical instances. In a binary semaphore, is restricted to 0 and 1, functioning identically to a mutual-exclusion lock (mutex).
To avoid busy waiting (spinlooping that wastes CPU cycles while waiting), operating systems implement semaphores with a waiting queue: if wait(S) decrements and finds , the calling process blocks itself and is placed in the semaphore's queue; when another process calls signal(S) and , one blocked process is removed from the queue and moved to the ready queue.
semaphore mutex = 1; // Binary semaphore for buffer mutual exclusion
semaphore empty = N; // Counts available empty slots
semaphore full = 0; // Counts filled slots ready for consumption
void producer(item next_produced) {
wait(empty); // Decrement empty count; block if buffer is full
wait(mutex); // Enter critical section
insert_item(next_produced);
signal(mutex); // Exit critical section
signal(full); // Increment filled slot count
}
void consumer(void) {
wait(full); // Decrement full count; block if buffer is empty
wait(mutex); // Enter critical section
item next_consumed = remove_item();
signal(mutex); // Exit critical section
signal(empty); // Increment empty slot count
}Two additional classic synchronization problems illustrate semaphore design patterns:
- Readers-Writers Problem: Multiple concurrent readers may safely read a shared database simultaneously, but a writer requires exclusive access. Using a
rw_mutexsemaphore and an integerread_countprotected bymutex, the first reader acquiresrw_mutexand the last reader releases it. - Dining-Philosophers Problem: Five philosophers sit around a circular table with five chopsticks placed between them. If every philosopher picks up their left chopstick simultaneously, all five wait forever for their right chopstick—a classic deadlock. Deadlock is prevented by allowing at most four philosophers at the table, requiring both chopsticks to be picked up atomically, or imposing an asymmetric rule where odd philosophers pick up left first and even philosophers pick up right first.
7.3 Monitors
Although semaphores are powerful, incorrect ordering of wait() and signal() calls (such as reversing their order or omitting a signal()) causes subtle deadlocks or mutual-exclusion violations. A monitor is a high-level language synchronization construct (implemented in Java's synchronized methods, C# locks, and pthreads mutex-plus-condition pairs) that encapsulates shared data variables, procedures that operate on them, and synchronization in a single abstract data type. Only one process or thread may be active inside a monitor at any instant, guaranteeing automatic mutual exclusion. To allow processes to wait for specific state conditions inside a monitor, condition variables are declared with two operations: x.wait() (suspends the calling process until another process invokes x.signal()) and x.signal() (resumes exactly one suspended process, or has no effect if none is waiting).
Chapter 8: Deadlocks
8.1 Deadlock Characterization
In a multiprogramming environment, a set of processes is in a deadlocked state when every process in the set is waiting for an event (typically the release of a resource) that can only be caused by another process in the same set. A deadlock can arise if and only if four necessary conditions hold simultaneously in the system:
- Mutual Exclusion: At least one resource must be held in a non-sharable mode; only one process at a time can use the resource.
- Hold and Wait: A process must be holding at least one resource while waiting to acquire additional resources currently held by other processes.
- No Preemption: Resources cannot be forcibly taken away from a process; a resource can be released only voluntarily by the process holding it after completing its task.
- Circular Wait: A closed chain of waiting processes must exist such that waits for a resource held by , waits for , ..., and waits for a resource held by .
Deadlocks can be modeled visually using a Resource-Allocation Graph (RAG), a directed graph with process vertices, resource vertices, request edges (), and assignment edges (). If the graph contains no cycles, no deadlock exists; if a cycle exists and each resource type has only a single instance, a deadlock has definitely occurred; if resource types have multiple instances, a cycle is a necessary but not sufficient condition for deadlock.
8.2 Methods for Handling Deadlocks
Operating systems handle deadlocks using one of four strategies: (1) Deadlock Prevention—structurally invalidating at least one of the four necessary conditions; (2) Deadlock Avoidance—requiring advance knowledge of maximum resource claims and granting requests only if the resulting state remains safe; (3) Deadlock Detection and Recovery—allowing deadlocks to occur, periodically running a detection algorithm, and recovering; or (4) Ostrich Approach—ignoring the problem entirely (used by Windows and Linux kernels for user-space deadlocks because prevention overhead is high and deadlocks are rare).
In Deadlock Prevention, mutual exclusion cannot be broken for intrinsically non-sharable hardware like printers. Hold-and-wait is prevented by requiring a process to request all resources before starting or release all held resources before requesting new ones (causing low utilization). No preemption is broken by forcing a waiting process to release held resources if a new request is denied. Circular wait—the most practical target—is prevented by imposing a strict total ordering on all resource types and requiring processes to request resources only in strictly increasing numerical order.
8.3 Deadlock Avoidance: Banker's Algorithm
A system state is safe if there exists a safe sequence of all processes such that for each , the resources that can still request can be satisfied by the currently available resources plus all resources held by preceding processes (). Every safe state is guaranteed deadlock-free, whereas an unsafe state may lead to deadlock. Dijkstra's Banker's Algorithm checks safety before granting any resource request using four matrices/vectors for processes and resource types: Available[m], Max[n][m], Allocation[n][m], and Need[n][m] = Max[n][m] - Allocation[n][m].
Worked Numerical Example (Banker's Algorithm): Consider 5 processes (–) and 3 resource types A (10 instances), B (5 instances), C (7 instances). At time , Available = [3, 3, 2]:
| Process | Allocation (A B C) | Max (A B C) | Need = Max - Alloc (A B C) |
|---|---|---|---|
| P0 | 0 1 0 | 7 5 3 | 7 4 3 |
| P1 | 2 0 0 | 3 2 2 | 1 2 2 |
| P2 | 3 0 2 | 9 0 2 | 6 0 0 |
| P3 | 2 1 1 | 2 2 2 | 0 1 1 |
| P4 | 0 0 2 | 4 3 3 | 4 3 1 |
Safety Check Execution: Start with Work = [3, 3, 2]. P0 needs [7,4,3] > Work (skip). P1 needs [1,2,2] ≤ [3,3,2] (satisfied!): execute P1, release its allocation, so Work = [3,3,2] + [2,0,0] = [5,3,2]. Next, P3 needs [0,1,1] ≤ [5,3,2]: execute P3, Work = [5,3,2] + [2,1,1] = [7,4,3]. Next, P4 needs [4,3,1] ≤ [7,4,3]: execute P4, Work = [7,4,3] + [0,0,2] = [7,4,5]. Next, P2 needs [6,0,0] ≤ [7,4,5]: execute P2, Work = [7,4,5] + [3,0,2] = [10,4,7]. Finally, P0 needs [7,4,3] ≤ [10,4,7]: execute P0, Work = [10,5,7]. Because all 5 processes finish, the state is safe with safe sequence .
Resource-Request Check: Now suppose P1 requests Request_1 = [1, 0, 2]. Since [1, 0, 2] ≤ Need_1 [1, 2, 2] and [1, 0, 2] ≤ Available [3, 3, 2], we pretend to allocate: Available = [2, 3, 0], Alloc_1 = [3, 0, 2], Need_1 = [0, 2, 0]. Running the safety algorithm finds the safe sequence , so the request is immediately granted. Conversely, if P4 requests [3, 3, 0] while Available = [2, 3, 0], it must wait because 3 > 2 instances of A are available.
8.4 Deadlock Detection and Recovery
If a system neither prevents nor avoids deadlocks, it runs a deadlock detection algorithm (Wait-For Graph cycle detection for single-instance resources, or an matrix check similar to Banker's Algorithm for multi-instance resources). Once a deadlock is detected, recovery proceeds either through process termination (aborting all deadlocked processes at once, or aborting one process at a time in increasing order of priority/cost until the cycle breaks) or through resource preemption (selecting a victim process, rolling back its state to a safe checkpoint, and guarding against starvation by tracking how many times a process is chosen as victim).
Worked Numerical Example (Multi-Instance Deadlock Detection): Consider 5 processes (–) and 3 resource types A (7 instances), B (2 instances), C (6 instances), with Available = [0, 0, 0]:
| Process | Allocation (A B C) | Request (A B C) | Detection Trace (Work starts [0, 0, 0]) |
|---|---|---|---|
| P0 | 0 1 0 | 0 0 0 | Step 1: Request ≤ [0,0,0] → Finish P0; Work = [0, 1, 0] |
| P1 | 2 0 0 | 2 0 2 | Step 4: Request ≤ [3,1,3] → Finish P1; Work = [5, 1, 3] |
| P2 | 3 0 3 | 0 0 0 | Step 2: Request ≤ [0,1,0] → Finish P2; Work = [3, 1, 3] |
| P3 | 2 1 1 | 1 0 0 | Step 3: Request ≤ [3,1,3] → Finish P3; Work = [5, 2, 4] |
| P4 | 0 0 2 | 0 0 2 | Step 5: Request ≤ [5,2,4] → Finish P4; Work = [5, 2, 6] |
Because all five processes finish, the system is currently not deadlocked. However, if makes one additional request for resource C (Request_2 = [0, 0, 1]), then only can finish (Work = [0, 1, 0]), and processes remain deadlocked in a circular wait for resources A and C.
8.5 Multiprocessor Scheduling, Thread Scheduling, and Little's Law
In Symmetric Multiprocessing (SMP) systems, CPU scheduling extends beyond a single ready queue. Operating systems choose between a common ready queue (all cores pull from one shared queue protected by a lock, which can become a contention bottleneck) or per-core private ready queues (standard in modern Linux and Windows). Per-core queues preserve Processor Affinity: because a running process warms up a core's L1/L2 caches, migrating it to another core invalidates cache lines (soft affinity attempts to keep a process on the same CPU, while hard affinity system calls like sched_setaffinity() restrict it strictly). To prevent one core from sitting idle while another has a backlog, Load Balancing runs either push migration (a periodic task moves processes from overloaded to idle cores) or pull migration (an idle core pulls a waiting task from a busy core).
Thread scheduling distinguishes between Process-Contention Scope (PCS), where a user-level thread library schedules many-to-one or many-to-many threads onto available Light-Weight Processes (LWPs) within the same process, and System-Contention Scope (SCS), where the OS kernel schedules one-to-one kernel threads across all physical CPU cores in the system.
Worked Numerical Example (Little's Law): If an interactive server receives an average of processes per second and measurements show an average of processes waiting in the ready queue, then the average waiting time per process is .
8.6 Hardware Synchronization Primitives and Mutex Locks
At the lowest kernel level, semaphores and monitors are built atop atomic hardware instructions that execute without interruption across all CPU cores:
// Atomic Test-and-Set executed indivisibly by CPU hardware
bool test_and_set(bool *target) {
bool rv = *target;
*target = true;
return rv;
}
// Atomic Compare-and-Swap executed indivisibly by CPU hardware
int compare_and_swap(int *value, int expected, int new_value) {
int temp = *value;
if (*value == expected)
*value = new_value;
return temp;
}
// Spinlock Mutual Exclusion using test_and_set
void acquire_spinlock(bool *lock) {
while (test_and_set(lock))
; // Busy wait until lock becomes false
}
void release_spinlock(bool *lock) {
*lock = false;
}Because spinlocks waste CPU cycles while busy-waiting, they are used in OS kernels only when the expected lock hold time is shorter than two context switches (e.g., protecting a short ready-queue update on a multicore CPU). For longer critical sections, operating systems provide adaptive mutexes (which spin briefly if the lock holder is currently running on another core, and sleep/block in a wait queue if the holder is descheduled).
8.7 Classic Synchronization Implementations and Liveness Hazards
To illustrate how software and monitor abstractions eliminate race conditions and deadlocks, consider Peterson's classic two-process software solution and a deadlock-free Monitor solution to the Dining-Philosophers problem:
// Peterson's Two-Process Critical-Section Solution
boolean flag[2] = {false, false};
int turn = 0;
void enter_critical_section(int i) {
int j = 1 - i;
flag[i] = true; // Express intent to enter
turn = j; // Politely yield priority to peer j
while (flag[j] && turn == j)
; // Wait only if peer wants in and it is peer's turn
}
void exit_critical_section(int i) {
flag[i] = false; // Clear intent upon leaving
}
// Monitor-based Dining Philosophers (Deadlock-Free)
monitor DiningPhilosophers {
enum { THINKING, HUNGRY, EATING } state[5];
condition self[5];
void pickup(int i) {
state[i] = HUNGRY;
test(i);
if (state[i] != EATING) self[i].wait();
}
void putdown(int i) {
state[i] = THINKING;
test((i + 4) % 5); // Wake left neighbor if hungry and able
test((i + 1) % 5); // Wake right neighbor if hungry and able
}
void test(int i) {
if ((state[(i + 4) % 5] != EATING) && (state[i] == HUNGRY) && (state[(i + 1) % 5] != EATING)) {
state[i] = EATING;
self[i].signal();
}
}
}Beyond deadlock, concurrent systems face two related liveness hazards. Starvation (indefinite blocking) occurs when a runnable process is perpetually denied CPU time or locks because higher-priority or luckier peers repeatedly overtake it. Livelock occurs when two or more processes continuously change their states in response to each other without making any forward progress (analogous to two people stepping left and right in a hallway trying to let each other pass). Both differ from deadlock, where processes are permanently blocked waiting for each other.
| Liveness Hazard | Process State | Root Cause | Primary Remedy |
|---|---|---|---|
| Deadlock | Permanently Blocked (Waiting) | Circular wait on non-preemptible held resources | Resource ordering, Banker's Algorithm, or cycle detection |
| Starvation | Ready or Waiting indefinitely | Unfair scheduling or lock-acquisition bias | Aging (gradual priority boost) or FIFO queueing |
| Livelock | Running (actively retrying) | Symmetric collision-recovery loops without backoff | Randomized exponential backoff |
Module III: Memory Management
Chapter 9: Memory Management Strategies
9.1 Background, Hardware Protection, and Address Binding
Main memory consists of a large array of bytes, each with a unique physical address. For a program to execute, it must be brought from secondary storage into main memory and placed within a process. To ensure memory protection so no user process can overwrite the operating system kernel or another process's memory, the CPU hardware provides two special registers: a base register (holding the smallest legal physical memory address) and a limit register (specifying the size of the range). Every memory address generated in user mode is checked by hardware: if , the access proceeds; otherwise, the hardware traps to the OS as a fatal addressing error.
The CPU's Memory Management Unit (MMU) translates logical (virtual) addresses generated by the CPU into physical addresses sent to the DRAM controller. Address binding—mapping symbolic program addresses to physical locations—occurs at three stages: compile time (if the physical load address is known in advance, producing absolute code), load time (if the load location is unknown at compile time, producing relocatable code), or execution time (if a process can be moved between memory segments during execution, requiring hardware relocation support).
To optimize physical RAM usage, operating systems employ dynamic loading (a routine is not loaded into memory until it is called, keeping rarely used error handlers on disk) and dynamic linking with shared libraries (such as .so files on Linux or .dll files on Windows), where a single copy of a system library in RAM is mapped into the address spaces of multiple concurrent processes, reducing both memory footprint and disk usage.
9.2 Swapping
Swapping allows the total virtual memory footprint of active processes to exceed the physical RAM capacity of the machine. A process—or in modern operating systems, individual pages of a process—can be swapped temporarily out of main memory to a backing store (a dedicated swap partition or swap file on SSD/HDD) and later brought back into memory for continued execution. Standard full-process swapping incurs high transfer latency proportional to process size: swapping a 100 MB process to a disk transferring at 50 MB/s takes 2 seconds each way (4 seconds total). This is why modern kernels such as Linux and Windows perform page-level swapping (paging out only idle 4 KB pages) rather than moving entire processes.
9.3 Contiguous Memory Allocation
In contiguous memory allocation, each process is contained in a single contiguous section of physical memory, protected by hardware relocation (base) and limit registers. Early systems used fixed-sized partitions (MFT), whereas modern contiguous allocators use variable-sized partitions (MVT), tracking free memory regions (holes) in a linked list. When a process arrives requesting memory of size , the OS chooses a free hole using one of three strategies:
- First Fit: Allocates the first hole in the free list that is large enough; fast because searching stops immediately upon finding a match.
- Best Fit: Searches the entire list (unless sorted by size) and allocates the smallest hole that is large enough, producing the smallest leftover fragment.
- Worst Fit: Allocates the largest available hole, leaving behind a large leftover hole that may still be useful for subsequent processes.
Worked Numerical Example (Contiguous Allocation): Given free memory partitions of sizes 100 KB, 500 KB, 200 KB, 300 KB, and 600 KB (in order), suppose processes arrive requesting 212 KB, 417 KB, 112 KB, and 426 KB:
- First Fit: 212 KB → 500 KB (288 KB left); 417 KB → 600 KB (183 KB left); 112 KB → 288 KB (176 KB left); 426 KB → must wait (no hole ≥ 426 KB).
- Best Fit: 212 KB → 300 KB (88 KB left); 417 KB → 500 KB (83 KB left); 112 KB → 200 KB (88 KB left); 426 KB → 600 KB (174 KB left). All four processes fit!
- Worst Fit: 212 KB → 600 KB (388 KB left); 417 KB → 500 KB (83 KB left); 112 KB → 388 KB (276 KB left); 426 KB → must wait.
Contiguous allocation suffers from external fragmentation: enough total free memory exists to satisfy a request, but it is broken into non-contiguous small holes. Compaction (sliding active processes together in memory) eliminates external fragmentation only if execution-time dynamic relocation is supported, at significant CPU copy cost. Fixed-partition schemes also suffer from internal fragmentation, where allocated memory slightly exceeds the requested size and the unused remainder inside the partition is wasted.
Chapter 10: Paging and Segmentation
10.1 Paging Architecture and Address Translation
Paging is a non-contiguous memory-management scheme that permits a process's physical address space to be scattered across non-adjacent blocks of RAM, completely eliminating external fragmentation and the need for compaction. Physical memory is divided into fixed-sized blocks called frames, and logical memory is divided into blocks of the exact same size called pages (typically 4 KB, 2 MB, or 1 GB on modern 64-bit architectures). When a process of size pages executes, its pages are loaded into any available frames in RAM, recorded in a per-process Page Table.
Every logical address generated by the CPU is split into two components: a page number () used as an index into the page table, and a page offset () combined with the base frame number () from the page table to form the physical address. For a logical address space of bytes and a page size of bytes, the upper bits specify the page number , and the lower bits specify the offset :
PageTable[p].
Because the page table resides in main memory, every memory access would naively require two DRAM accesses (one for the page table entry, one for the data byte), halving memory speed. To solve this, CPUs include a fast associative hardware cache called the Translation Lookaside Buffer (TLB). When the CPU generates , the TLB is searched in parallel; on a TLB hit, frame is returned immediately. On a TLB miss, the page table in DRAM is consulted and the TLB is updated. Some TLBs store Address-Space Identifiers (ASIDs) per entry so the TLB does not need to be flushed on every context switch. The Effective Access Time (EAT) with a TLB is:
Worked Numerical Example (TLB EAT): Suppose a TLB lookup takes , main memory access takes , and the TLB hit ratio is (90%):
Each page table entry (PTE) also stores protection bits (Read-Only, Read-Write, Execute-Disable) and a Valid-Invalid bit indicating whether the page belongs to the process's legal address space. For 64-bit address spaces, a single flat page table would consume gigabytes per process. Operating systems therefore use three advanced page-table structures:
- Hierarchical (Multi-Level) Paging: Pages the page table itself. In a 32-bit system with 4 KB pages (12-bit offset), the remaining 20-bit page number is split into a 10-bit outer page number () and a 10-bit inner page number (); x86-64 uses 4-level or 5-level paging.
- Hashed Page Tables: Common for sparse 64-bit address spaces, hashing the virtual page number into a hash table whose buckets hold linked lists of matching entries.
- Inverted Page Tables: Maintains one global entry per physical frame of RAM rather than one entry per virtual page per process, drastically reducing page-table memory overhead at the cost of slower lookup (mitigated by hashing and the TLB).
10.2 Segmentation
Segmentation is a memory-management scheme that supports the programmer's logical view of a program as a collection of variable-sized logical units—such as the main code segment, global data segment, heap, stack, and symbol table—rather than a flat linear array of bytes. Each logical address consists of an ordered pair , where is the segment number and is the offset within that segment. A Segment Table maps each segment number to a physical base address and a segment limit (length). During translation, the MMU checks that ; if valid, the physical address is ; otherwise, a segmentation fault trap is raised.
Worked Numerical Example (Segmentation Translation): Given a Segment Table: Segment 0 (Base = 219, Limit = 600), Segment 1 (Base = 2300, Limit = 14), Segment 2 (Base = 90, Limit = 100), Segment 3 (Base = 1327, Limit = 580). Translate logical addresses: (a) : since , Physical Address = ; (b) : since , Physical Address = ; (c) : since , hardware raises an illegal-address trap (segmentation fault).
Chapter 11: Virtual Memory Management, Demand Paging, and Thrashing
11.1 Virtual Memory, Demand Paging, and Copy-on-Write
Virtual memory separates logical memory as perceived by users from physical memory. This separation allows programmers to write applications larger than physical RAM, lets multiple processes share code and libraries safely, and speeds up process creation via Copy-on-Write (CoW). Under CoW, when fork() creates a child process, parent and child initially share the same physical frames marked read-only; only when either process attempts to write to a shared page does the kernel allocate a new physical frame and copy that single page. Virtual memory is commonly implemented via Demand Paging: pages are loaded from secondary storage into physical frames only when they are actually referenced during execution, never in advance.
Each page table entry includes a valid-invalid bit: v indicates the page is both legal and currently resident in RAM; i indicates the page is either invalid (outside the process's logical space) or valid on disk but not yet loaded. When a process attempts to access a page marked i, the MMU triggers a page-fault trap to the operating system. The OS handles a page fault in six steps: (1) check an internal PCB table to verify whether the reference is valid or an illegal access (if illegal, terminate the process); (2) locate a free physical frame from the free-frame list; (3) schedule a disk read to load the desired page into that frame; (4) update the PCB and page table entry to mark the page valid (v); (5) restart the instruction that was interrupted by the trap.
Worked Numerical Example (Impact of Page Fault Rate): If and average page-fault service time , even a tiny page fault rate of (1 fault per 1,000 accesses) yields —a 40x slowdown! Keeping near zero is therefore essential.
11.2 Thrashing, Working-Set Model, and Kernel Memory Allocation
If the operating system raises the degree of multiprogramming too high, the combined active memory pages of all running processes exceed available physical frames. Processes begin page-faulting continuously, spending more time swapping pages to and from disk than executing instructions—a severe performance collapse called thrashing. As CPU utilization drops during disk waits, a naive medium-term scheduler may admit even more processes, worsening the thrashing spiral.
To prevent thrashing, the OS must allocate each process enough frames to hold its locality of reference—the set of pages actively used together during a phase of execution. Peter Denning's Working-Set Model defines the working set as the number of unique pages referenced by process in the most recent memory references. If total demand (total physical frames), the OS suspends one or more processes and swaps them out so the remaining processes have sufficient frames. Alternatively, Page-Fault Frequency (PFF) monitors each process's fault rate: if it rises above an upper threshold, the OS allocates another frame; if it falls below a lower threshold, a frame is reclaimed.
Kernel memory is allocated differently from user-mode memory because kernel structures are often smaller than a single page and device DMA buffers require physically contiguous frames. Kernels use the Buddy System (allocating physically contiguous blocks in powers of two and coalescing adjacent buddies upon release) and the Slab Allocator (pre-allocating object caches for frequent kernel structures like PCBs and inodes, eliminating internal fragmentation and initialization overhead).
Chapter 12: Page Replacement Algorithms
12.1 Frame Allocation and Page Replacement Basics
When a page fault occurs and no free physical frames remain, the OS must select a victim frame to evict. To avoid unnecessary disk writes, each page table entry maintains a dirty (modify) bit set by hardware whenever the page is written to; if the victim page's dirty bit is 0, it does not need to be written back to disk. Frame allocation among processes uses either equal allocation ( frames each) or proportional allocation based on process size, and replacement can be local (a process replaces only from its own frames) or global (a process can take a frame from another process, yielding higher system throughput).
12.2 FIFO, Optimal, LRU, and Clock Page Replacement
- First-In, First-Out (FIFO): Replaces the oldest page in memory (tracked via a simple FIFO queue). Although trivial to implement, FIFO ignores usage frequency and can exhibit Belady's Anomaly—a counterintuitive behavior where giving a process more physical frames actually increases the number of page faults.
- Optimal (OPT / Belady's Algorithm): Replaces the page that will not be used for the longest period of time in the future. OPT achieves the lowest possible page-fault rate for any reference string and never suffers from Belady's anomaly, but it requires future knowledge and serves as a theoretical benchmark.
- Least Recently Used (LRU): Approximates OPT by looking backward in time, replacing the page that has not been referenced for the longest period. LRU satisfies the stack property and never exhibits Belady's anomaly. Hardware implements LRU using counters or a doubly linked stack; because exact LRU is expensive per memory reference, OS kernels commonly approximate it using the Clock (Second-Chance) algorithm with a single reference bit per frame.
- Second-Chance (Clock) & Enhanced Second-Chance: Cycles through frames in a circular buffer; if a frame's reference bit is 1, it clears the bit to 0 and advances the clock hand; if 0, it evicts that frame. Enhanced Second-Chance uses the ordered pair (reference bit, modify bit) to prefer evicting clean unreferenced pages
(0,0)before dirty unreferenced pages(0,1).
Worked Numerical Comparison (3 Physical Frames): Consider the reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 with 3 physical frames:
| Algorithm (3 Frames) | Eviction Rule | Total Page Faults | Belady's Anomaly Risk |
|---|---|---|---|
| FIFO | Oldest loaded page evicted first | 10 page faults | Yes (can fault more with more frames) |
| LRU | Least recently referenced page evicted | 9 page faults | No (stack algorithm) |
| Optimal (OPT) | Page used farthest in the future evicted | 7 page faults | No (theoretical minimum) |
Belady's Anomaly Demonstration (FIFO): On the classic reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5, FIFO produces 9 page faults with 3 frames, but produces 10 page faults when given 4 frames—proving that FIFO lacks the inclusion (stack) property.
12.3 Step-by-Step Worked Page Replacement Trace (3 Frames)
To master page replacement calculations for examinations, let us trace every single reference in the string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 across 3 physical frames (initially empty) for FIFO, LRU, and Optimal:
| Ref | FIFO (3 Frames) | FIFO Status | LRU (3 Frames) | LRU Status | Optimal (3 Frames) | OPT Status |
|---|---|---|---|---|---|---|
| 7 | [7, -, -] | Fault (1) | [7, -, -] | Fault (1) | [7, -, -] | Fault (1) |
| 0 | [7, 0, -] | Fault (2) | [7, 0, -] | Fault (2) | [7, 0, -] | Fault (2) |
| 1 | [7, 0, 1] | Fault (3) | [7, 0, 1] | Fault (3) | [7, 0, 1] | Fault (3) |
| 2 | [2, 0, 1] | Fault (4) | [2, 0, 1] | Fault (4) | [2, 0, 1] | Fault (4) |
| 0 | [2, 0, 1] | Hit | [2, 0, 1] | Hit | [2, 0, 1] | Hit |
| 3 | [2, 3, 1] | Fault (5) | [2, 0, 3] | Fault (5) | [2, 0, 3] | Fault (5) |
| 0 | [2, 3, 0] | Fault (6) | [2, 0, 3] | Hit | [2, 0, 3] | Hit |
| 4 | [4, 3, 0] | Fault (7) | [4, 0, 3] | Fault (6) | [2, 4, 3] | Fault (6) |
| 2 | [4, 2, 0] | Fault (8) | [4, 0, 2] | Fault (7) | [2, 4, 3] | Hit |
| 3 | [4, 2, 3] | Fault (9) | [4, 3, 2] | Fault (8) | [2, 4, 3] | Hit |
| 0 | [0, 2, 3] | Fault (10) | [0, 3, 2] | Fault (9) | [2, 0, 3] | Fault (7) |
| 3 | [0, 2, 3] | Hit | [0, 3, 2] | Hit | [2, 0, 3] | Hit |
| 2 | [0, 2, 3] | Hit | [0, 3, 2] | Hit | [2, 0, 3] | Hit |
12.4 Worked 2-Level Paging, Inverted Page Table, and Working-Set Calculations
Worked Example 1 (Multi-Level Page Table Size): Consider a 32-bit logical address space with 4 KB ( bytes) pages and 4-byte Page Table Entries (PTEs). A single-level page table has entries (1,048,576 entries), consuming of contiguous RAM per process. With 2-level paging, the 20-bit page number is split into a 10-bit outer index (, 1,024 entries = 4 KB outer directory) and a 10-bit inner index (, 1,024 entries = 4 KB per inner table). A small process using only 12 MB of memory needs just 1 outer table (4 KB) plus 3 inner tables (12 KB) = 16 KB total instead of 4 MB!
Worked Example 2 (Inverted Page Table Memory Savings): Suppose a 64-bit workstation has 8 GB of physical RAM ( bytes) with 4 KB ( bytes) pages and 8-byte entries. Total physical frames = frames (2,097,152 frames). An Inverted Page Table stores one entry per physical frame across the entire OS, consuming just total regardless of whether 10 or 1,000 processes are running.
Worked Example 3 (Working-Set Window Trace): Consider the reference stream 2, 6, 1, 5, 7, 7, 7, 7, 5, 1, 6, 2, 3, 4, 1, 2, 3, 4, 4, 4 with a working-set window references. At time (after the first 10 references: 2, 6, 1, 5, 7, 7, 7, 7, 5, 1), the working set is , requiring frames. At time (the last 10 references: 6, 2, 3, 4, 1, 2, 3, 4, 4, 4), the locality has shifted to , also requiring frames. By dynamically adjusting frame allocation to match , the OS prevents thrashing across phase transitions.
12.5 Memory-Mapped Files and Kernel Buddy/Slab Allocators
Memory-mapped files (via POSIX mmap() or Windows MapViewOfFile()) map a disk file directly into a portion of a process's virtual address space. Subsequent file reads and writes become ordinary memory pointer accesses rather than read()/write() system calls, and the OS transparently loads file blocks on demand via page faults and flushes dirty pages back to disk asynchronously. Multiple processes mapping the same file read-only share identical physical frames in RAM.
Inside the kernel, the Buddy System allocates memory from a fixed-size segment of physically contiguous pages in power-of-two blocks (e.g., 4 KB, 8 KB, 16 KB, ..., 512 KB). If a 21 KB kernel buffer is requested from a 256 KB segment, the allocator splits 256 → 128 + 128 → 64 + 64 → 32 + 32 and assigns the 32 KB block; when freed, adjacent buddies are coalesced back into larger blocks. Because the Buddy System can still incur internal fragmentation for small objects (like 150-byte PCBs or 200-byte file descriptors), the Slab Allocator creates pre-initialized caches (slabs) of exact-size objects from one or more contiguous pages, achieving zero internal fragmentation and instant allocation.
12.6 Belady's Anomaly Complete Trace (3 Frames vs 4 Frames)
To verify Belady's Anomaly mathematically, trace FIFO on the reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 with 3 frames versus 4 frames:
| Ref | FIFO (3 Frames) | 3F Status | FIFO (4 Frames) | 4F Status |
|---|---|---|---|---|
| 1 | [1, -, -] | Fault (1) | [1, -, -, -] | Fault (1) |
| 2 | [1, 2, -] | Fault (2) | [1, 2, -, -] | Fault (2) |
| 3 | [1, 2, 3] | Fault (3) | [1, 2, 3, -] | Fault (3) |
| 4 | [4, 2, 3] | Fault (4) | [1, 2, 3, 4] | Fault (4) |
| 1 | [4, 1, 3] | Fault (5) | [1, 2, 3, 4] | Hit |
| 2 | [4, 1, 2] | Fault (6) | [1, 2, 3, 4] | Hit |
| 5 | [5, 1, 2] | Fault (7) | [5, 2, 3, 4] | Fault (5) |
| 1 | [5, 1, 2] | Hit | [5, 1, 3, 4] | Fault (6) |
| 2 | [5, 1, 2] | Hit | [5, 1, 2, 4] | Fault (7) |
| 3 | [5, 3, 2] | Fault (8) | [5, 1, 2, 3] | Fault (8) |
| 4 | [5, 3, 4] | Fault (9) | [4, 1, 2, 3] | Fault (9) |
| 5 | [5, 3, 4] | Hit | [4, 5, 2, 3] | Fault (10) |
With 3 frames, FIFO incurs 9 page faults; with 4 frames, FIFO incurs 10 page faults. Stack algorithms such as LRU and Optimal never suffer from Belady's anomaly because the set of pages resident in frames is always a strict subset of the pages resident in frames.
12.7 Enhanced Second-Chance Algorithm, Page Size, and Program Locality
In the Enhanced Second-Chance (Clock) algorithm, the OS inspects both the hardware reference bit () and modify/dirty bit () as an ordered pair , dividing resident pages into four priority classes for eviction:
- Class (0, 0): Neither recently used nor modified — best page to evict immediately (zero disk write needed).
- Class (0, 1): Not recently used, but modified — must be written to swap space before eviction.
- Class (1, 0): Recently used, but clean — likely to be referenced again soon.
- Class (1, 1): Recently used and modified — must be written out and likely needed again; last choice for eviction.
Choosing the hardware page size involves a fundamental trade-off. Smaller pages (e.g., 4 KB) reduce internal fragmentation and match tight program localities, but require larger page tables and cause more page faults when loading large sequential arrays. Larger pages (e.g., 2 MB huge pages) shrink page tables, maximize TLB reach (allowing a 64-entry TLB to cover 128 MB instead of 256 KB), and transfer more data per disk I/O, at the cost of higher internal fragmentation. Modern operating systems support multiple page sizes simultaneously (such as Linux Transparent Huge Pages).
Program structure strongly affects page-fault rates even under identical hardware and OS policies. In C/C++, multidimensional arrays are stored in row-major order. Traversing a integer matrix row-by-row touches consecutive addresses within the same 4 KB page, generating roughly 1,024 page faults; traversing the exact same matrix column-by-column jumps by 4,096 bytes on every inner-loop iteration, potentially causing page faults if physical frames are scarce!
int data[1024][1024]; // 4 MB array = 1,024 pages (4 KB each)
// Cache & Page-Friendly: Row-major traversal (~1,024 page faults)
for (int i = 0; i < 1024; i++)
for (int j = 0; j < 1024; j++)
data[i][j] = 0;
// Thrashing Risk: Column-major traversal (up to 1,048,576 page faults)
for (int j = 0; j < 1024; j++)
for (int i = 0; i < 1024; i++)
data[i][j] = 0;Finally, I/O Interlock (page pinning) prevents the page-replacement daemon from evicting a page that is currently the target of an active DMA transfer from a disk or network controller; otherwise, another process's newly loaded page in that physical frame would be overwritten by the incoming DMA burst.
12.8 Implementing LRU, Counting Algorithms, and Page Buffering
Implementing exact LRU requires hardware support beyond a simple reference bit, using one of two mechanisms. In the Counter Implementation, every page table entry has a time-of-use field and the CPU maintains a logical clock counter incremented on every memory reference; upon a page fault, the OS searches the page table for the page with the smallest counter value. In the Stack Implementation, the OS maintains a doubly linked list of page numbers: whenever a page is referenced, it is removed from the middle of the list and moved to the top, leaving the least recently used page always at the bottom (requiring 6 pointer updates per reference without searching).
Counting-based page replacement algorithms maintain a counter of the number of references made to each page. Least Frequently Used (LFU) evicts the page with the smallest count, assuming actively used pages have high counts (though a page heavily used early in execution may linger forever unless counts are periodically shifted right by 1 bit). Most Frequently Used (MFU) evicts the page with the largest count, based on the heuristic that a page with a small count was probably just brought in and has yet to be used. Neither LFU nor MFU is common in production kernels because they are expensive to maintain and rarely outperform Clock approximations.
To keep disk I/O off the critical path of a page fault, operating systems maintain a pool of free frames (Page Buffering). When a page fault occurs, the desired page is read into an already-free frame from the pool immediately, while the victim frame is written out asynchronously later; furthermore, keeping a list of unmodified evicted frames allows a page to be reclaimed instantly at zero disk cost if referenced again before its frame is overwritten.
12.9 Frame Allocation Worked Example and Thrashing Control
Every architecture imposes a minimum number of frames per process—defined by the maximum number of pages a single machine instruction can touch (including instruction fetch, indirect memory operands, and destination). For example, an instruction copying one 64-bit word across two unaligned page boundaries with indirect addressing can require up to 6 frames.
Worked Numerical Example (Equal vs Proportional Frame Allocation): Suppose a system has 64 total physical frames, of which 2 frames are reserved for the OS kernel, leaving available frames shared between Process A (size 10 pages) and Process B (size 127 pages):
- Equal Allocation: Each of the 2 processes receives frames. Process A only needs 10 pages, wasting 21 frames, while Process B is severely starved with only 31 frames.
- Proportional Allocation: Frames are allocated proportionally to process size , where . Process A receives frames, and Process B receives frames (with 1 remaining frame assigned by priority).
In Linux, the kernel daemon kswapd continuously monitors free page watermarks (high, low, and min). When free memory drops below low, kswapd wakes up and runs a two-list Clock/LRU scan (Active and Inactive lists) to reclaim clean pages and swap out dirty anonymous pages. If memory exhaustion becomes critical and thrashing threatens system stability, the Linux Out-Of-Memory (OOM) killer scores processes by memory usage and priority (oom_score) and terminates the highest-scoring non-essential process to immediately free its frames.
12.10 Comprehensive Memory Management Comparison Matrix
The following table synthesizes all major memory management strategies covered in Module III, comparing how each handles fragmentation, hardware requirements, address translation overhead, and swapping:
| Strategy | Fragmentation | Hardware Required | Translation Overhead | Supports Virtual Memory |
|---|---|---|---|---|
| Contiguous (Fixed Partitions) | Internal fragmentation | Base & Limit registers | Single addition + bounds check | No |
| Contiguous (Variable Partitions) | External fragmentation | Relocation & Limit registers | Single addition + bounds check | No (full swap only) |
| Simple Paging | Negligible internal (avg 0.5 page) | MMU Page Table + TLB | 1 TLB hit or 2 DRAM accesses | Yes (with valid-invalid bit) |
| Multi-Level Paging | Negligible internal | MMU Page Walk + TLB | 1 TLB hit or DRAM accesses | Yes (standard in 64-bit OS) |
| Segmentation | External fragmentation | Segment Table (Base/Limit) | Segment lookup + bounds check | Limited (rarely pure) |
| Demand Paging | Negligible internal | MMU + Page-Fault Trap + Swap | Low when fault rate | Yes (core of modern OS) |
12.11 NUMA-Aware Allocation and Prepaging
On multi-socket enterprise servers with Non-Uniform Memory Access (NUMA), each CPU socket connects directly to local DRAM channels while accessing remote sockets' DRAM across an inter-socket interconnect (such as Intel UPI or AMD Infinity Fabric) at 30–50% higher latency. Modern operating systems implement NUMA-aware page allocators (defaulting to a local-allocation policy that assigns physical frames from the DRAM node attached to the core where the requesting thread is currently scheduled). Additionally, to mitigate the initial cold-start storm of page faults when a swapped-out process resumes, kernels use Prepaging: saving a list of the process's working-set pages before swapping out and reloading all of them together in a single sequential disk burst upon resumption.
12.12 Virtual Memory Protection, Shared Pages, and Copy-on-Write Mechanics
Beyond address translation, paging provides fine-grained hardware memory protection. Every Page Table Entry (PTE) stores read, write, and execute permission bits alongside a user/supervisor bit. Whenever the CPU executes an instruction, the MMU simultaneously verifies that the requested operation matches the PTE permissions: writing to a read-only code page or executing code from a non-executable stack page triggers an immediate hardware protection fault. Shared pages allow multiple processes running the same program or shared library (such as libc.so) to map their own virtual pages to the exact same physical frames marked read-only and reentrant, saving tens of megabytes of RAM across concurrent processes.
12.13 Address Translation Worked Example (32-Bit Paging & TLB Reach)
Consider a 32-bit virtual address space with 4 KB () pages. Logical address 0x00003A14 (decimal 14,868) splits into page number (0x00003) and offset (0xA14). If PageTable[3] = 7 (physical frame 7), the physical address is (0x00007A14). Notice that the 12-bit offset 0xA14 passes through unchanged while only the page number bits are replaced by the frame number.
TLB Reach is defined as the total amount of virtual memory accessible directly through the TLB without incurring a page-table walk: . With a 128-entry TLB and 4 KB pages, TLB reach is . Increasing the page size to 2 MB expands TLB reach for the exact same 128-entry hardware to —dramatically accelerating database and scientific workloads with large working sets.
Module IV: Storage Management
Chapter 13: File System Structure, Implementation, and Allocation Methods
13.1 File Concept, Access Methods, and Directory Structures
A file is a named collection of related information recorded on non-volatile secondary storage. From the user's perspective, a file is the smallest logical unit of persistent storage, characterized by attributes such as name, identifier, type, location, size, protection permissions, and timestamps (creation, last modification, last access). Operations on files include creating, writing, reading, repositioning (seeking), deleting, and truncating. Operating systems support three primary file access methods: Sequential Access (reading/writing records in order from start to end, ideal for text streams and logs), Direct/Relative Access (jumping directly to any fixed-length logical block number , essential for databases), and Indexed Sequential Access (maintaining an index of keys pointing to disk blocks).
To organize thousands or millions of files, file systems provide directories mapping human-readable file names to internal file identifiers. Directory architectures evolved across four designs: Single-Level Directory (all files in one flat namespace, causing name collisions among users), Two-Level Directory (separate Master File Directory per user), Tree-Structured Directory (hierarchical paths with absolute and relative working directories, used by all modern OSes), and Acyclic-Graph Directory (allowing shared subdirectories/files via hard links or symbolic links without cycles).
File protection enforces controlled access across owner, group, and other user classes. In POSIX systems (Linux/UNIX), each file carries a 9-bit permission mask (Read=4, Write=2, Execute=1 for owner, group, and others—e.g., 0755 grants rwxr-xr-x), supplemented by Access Control Lists (ACLs) for fine-grained per-user rules.
13.2 File System Structure and Implementation
File systems are structured as a layered software stack from hardware up to user applications:
- I/O Control: Device drivers and interrupt handlers transferring raw blocks between disk controllers and main memory.
- Basic File System: Issues generic commands to read/write physical blocks identified by drive and block number, managing memory buffers and caches.
- File-Organization Module: Translates logical block numbers (0 to ) of a file to physical disk block addresses and tracks free disk space.
- Logical File System: Manages directory structures, metadata, File Control Blocks (FCBs or inodes), and access permissions.
To implement a file system efficiently, the OS maintains both on-disk structures (persistent across reboots) and in-memory structures (cached in RAM for speed). On-disk structures include a boot control block (per-volume boot code), a volume control block (superblock in UNIX/Linux, Master File Table metadata in NTFS, recording block count, block size, and free-block counts), a directory structure mapping file names to identifiers, and a per-file File Control Block (FCB, called an inode in UNIX) storing ownership, permissions, timestamps, size, and pointers to data blocks.
In memory, the kernel maintains a mount table of mounted file systems, a directory-structure cache of recently accessed directories, a system-wide open-file table containing a copy of each open file's FCB and open count, and a per-process open-file table storing file descriptors and current read/write file offsets. Modern file systems also use a Virtual File System (VFS) abstraction layer (defining superblock, inode, dentry, and file objects) so identical POSIX calls (open, read, write) work seamlessly across ext4, NTFS, FAT32, and network file systems.
To prevent file-system corruption after sudden power loss, modern file systems (ext4, NTFS, XFS, APFS) use Journaling (Write-Ahead Logging): before modifying metadata or data blocks in place, the file system writes a transaction record to a circular journal log; after a crash, replaying committed journal entries restores consistency in seconds without scanning the entire disk (fsck).
13.3 File Allocation Methods and Free-Space Management
How an operating system allocates disk blocks to files directly determines sequential read speed, random-access performance, and disk-space utilization. Three primary allocation strategies exist:
| Allocation Method | Metadata Stored in FCB / Directory | Access Performance | Key Drawbacks |
|---|---|---|---|
| Contiguous Allocation | Starting block address and total block length | Fastest sequential and direct random access (minimal seeks) | External fragmentation; difficult to grow files dynamically |
| Linked Allocation | Pointer to first block and last block; each block points to next | Good sequential access; zero external fragmentation | Slow random access (must traverse links); pointer overhead and vulnerability to broken links |
| Indexed Allocation | Index block holding array of all data-block pointers (e.g., UNIX inode) | Supports fast direct random access without external fragmentation | Index-block overhead for tiny files; multi-level indirection needed for huge files |
A variation of linked allocation is the File Allocation Table (FAT), used in MS-DOS and USB flash drives: all block-next pointers are centralized in a dedicated table at the start of the volume, allowing the OS to cache the FAT in RAM and perform fast random seeks without reading intermediate data blocks. To handle both tiny and multi-gigabyte files efficiently, UNIX/Linux inodes use a combined indexed scheme: 12 direct block pointers, 1 single-indirect pointer (pointing to a block of pointers), 1 double-indirect pointer, and 1 triple-indirect pointer.
Worked Numerical Example (Inode Capacity): With block size (4 KB) and 4-byte block pointers, each index block holds pointers. Direct pointers address ; a single-indirect block addresses ; a double-indirect block addresses ; and a triple-indirect block addresses .
Free disk blocks are tracked using a Free-Space List implemented as a bit vector (bitmap, 1 bit per block where 1 = free, 0 = allocated; e.g., a 1 TB disk with 4 KB blocks needs bits = 32 MB), a linked free list (each free block points to the next), grouping (storing addresses of free blocks in the first free block), or counting (storing starting address and count of contiguous free blocks).
Chapter 14: Mass-Storage Structure, RAID, SSDs, and Disk Scheduling
14.1 Mass-Storage Structure, Access Time, and SSDs
A traditional magnetic Hard Disk Drive (HDD) consists of circular platters coated with magnetic material, spun by a spindle motor at 5,400 to 15,000 RPM. Read-write heads mounted on an actuator arm move radially across concentric tracks; the set of tracks at the same radial distance across all platter surfaces forms a cylinder, and each track is divided into fixed-size sectors (typically 512 bytes or 4 KB). Total disk access time is the sum of seek time (time for the actuator arm to move the head to the target cylinder, typically 3–10 ms), rotational latency (time for the desired sector to rotate under the head, averaging half a revolution), and transfer time. Because seek time dominates HDD latency, operating systems schedule pending I/O requests to minimize total head movement.
Solid-State Drives (SSDs) store data in non-volatile NAND flash memory cells with no moving mechanical parts, delivering sub-100-microsecond latency and high random IOPS. Because NAND flash must be erased in large blocks (e.g., 256 KB–4 MB) before individual 4 KB pages can be overwritten, SSD controllers include a Flash Translation Layer (FTL) that performs out-of-place writes, garbage collection, wear leveling (distributing writes evenly across flash blocks to prevent premature cell wear), and processes OS TRIM commands to mark deleted file blocks as invalid.
14.2 RAID (Redundant Array of Independent Disks)
Enterprise servers combine multiple physical disks into a single logical volume using RAID to improve I/O performance via striping and fault tolerance via mirroring or parity:
| RAID Level | Technique | Min Disks | Fault Tolerance & Key Use Case |
|---|---|---|---|
| RAID 0 | Block-level striping | 2 | None (1 disk failure loses all data); maximum speed/capacity |
| RAID 1 | Disk mirroring | 2 | Survives 1 disk failure per mirrored pair; high read throughput |
| RAID 5 | Striping with distributed parity | 3 | Survives any 1 disk failure; balanced cost, capacity, and safety |
| RAID 6 | Striping with dual distributed parity | 4 | Survives any 2 simultaneous disk failures; large enterprise arrays |
| RAID 10 | Mirrored pairs striped together (1+0) | 4 | Survives multiple failures if not in same mirror pair; high-IOPS databases |
14.3 Disk Scheduling Algorithms: FCFS, SSTF, SCAN, C-SCAN, and LOOK
- FCFS (First-Come, First-Served): Services disk requests strictly in arrival order. Fair and starvation-free, but produces wild back-and-forth head swings and high seek time under heavy load.
- SSTF (Shortest-Seek-Time-First): Selects the pending request closest to the current head position. Substantially reduces total seek distance compared to FCFS, but can cause starvation of requests located near the inner or outer edges of the disk.
- SCAN (Elevator Algorithm): The disk arm starts at one end and moves toward the other end, servicing all requests along the way until it reaches the extreme cylinder (0 or max), then reverses direction and services requests on the return sweep.
- C-SCAN (Circular SCAN): Moves from one end to the other servicing requests; upon reaching the extreme end, it immediately returns to the beginning without servicing any requests on the return trip, providing more uniform waiting times than SCAN.
- LOOK and C-LOOK: Practical optimizations of SCAN and C-SCAN where the arm travels only as far as the furthest pending request in each direction rather than traveling all the way to the physical edge cylinder.
Worked Numerical Example (Disk Head Movement): Consider a disk with 200 cylinders (0 to 199). The head is initially at cylinder 53 (moving toward 199 for SCAN/C-SCAN/LOOK), and the pending request queue is: 98, 183, 37, 122, 14, 124, 65, 67.
| Algorithm | Service Order from Head = 53 | Total Head Movement (Cylinders) |
|---|---|---|
| FCFS | 53 → 98 → 183 → 37 → 122 → 14 → 124 → 65 → 67 | cylinders |
| SSTF | 53 → 65 → 67 → 37 → 14 → 98 → 122 → 124 → 183 | cylinders |
| SCAN (up to 199) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 199 → 37 → 14 | cylinders |
| C-SCAN (up to 199, wrap to 0) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 199 → 0 → 14 → 37 | cylinders |
| LOOK (up to 183) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 37 → 14 | cylinders |
| C-LOOK (up to 183, wrap to 14) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 14 → 37 | cylinders |
14.4 Worked Numerical Comparisons: File Allocation & RAID Parity
Worked Example 1 (File Allocation Block-Access Cost): Consider a file of 100 blocks (numbered 0 to 99) stored on a disk. Suppose we want to insert a new block in the middle (after block 49) or read block 75 directly. Let us compare disk I/O operations required:
- Contiguous Allocation: Direct access to block 75 takes 1 disk read (at
start + 75). Inserting a block after block 49 requires shifting blocks 50–99 one position right (50 reads + 50 writes = 100 disk I/Os), or copying the entire 100-block file to a larger hole. - Linked Allocation (without FAT): Direct access to block 75 requires traversing pointers from block 0 through block 74, taking 76 disk reads. Inserting a block after block 49 requires reading block 49, writing the new block pointing to 50, and updating block 49's pointer—just 52 reads to reach 49 + 2 writes (no data shifting!).
- Indexed Allocation (single index block cached in RAM): Direct access to block 75 reads the index block (1 read if not cached, 0 if cached) + 1 read for block 75 = 1–2 disk reads. Inserting a block updates only one pointer in the index block in RAM and writes the new data block.
Worked Example 2 (RAID-5 XOR Parity Calculation and Reconstruction): Suppose a RAID-5 stripe spans 4 disks (D0, D1, D2, and Parity P). If D0 = 10110010, D1 = 01101100, and D2 = 11000101, the parity byte P is computed by bitwise Exclusive-OR ():
14.5 Disk Access Time, Swap-Space Management, and NAS vs SAN
To evaluate real HDD performance, consider a disk spinning at 7,200 RPM with an average seek time of 8 ms and a transfer rate of 100 MB/s. At 7,200 RPM, one full rotation takes , so average rotational latency (half a revolution) is . Reading a 4 KB sector takes . Total average access time is , proving that mechanical seek and rotation account for over 99% of single-sector HDD latency.
Operating systems manage swap space either inside a normal file in the file system (easy to resize, slightly slower due to file-system metadata lookup) or on a dedicated raw disk partition (faster, bypassing file-system overhead, managed by a specialized swap-space manager). For networked storage, Network-Attached Storage (NAS) exposes file-level protocols (NFS, SMB/CIFS) over standard IP networks, whereas a Storage Area Network (SAN) provides block-level storage arrays over high-speed Fibre Channel or iSCSI fabrics so servers see remote LUNs as local raw disks.
14.6 Directory Implementation and File-System Consistency
Directory structures map file names to inode/FCB numbers using either a Linear List (simple sequential search of (filename, pointer) pairs, slow lookup for large directories) or a Hash Table (computes a hash of the file name for average lookup time, handling collisions via chained buckets). Modern file systems like ext4 and XFS use B-trees (HTrees) for scalable sorted directory indexing.
Because file systems cache modified directory blocks and inodes in RAM before flushing them to disk, an unexpected power loss can leave metadata inconsistent (for example, a block marked allocated in an inode while still marked free in the bitmap). Consistency checkers such as UNIX fsck or Windows chkdsk scan all metadata structures at boot to repair discrepancies, but scanning multi-terabyte disks takes hours. Journaling file systems (ext4, NTFS, XFS) eliminate full scans by recording metadata intentions in a sequential write-ahead log (journal) before modifying main file-system structures; upon reboot, only uncommitted or recently committed journal transactions are replayed in milliseconds.
14.7 Virtual File System (VFS) Object Model and File-System Mounting
Before a file system on a disk partition can be accessed by applications, it must be mounted into the OS's global directory namespace (via mount() on UNIX/Linux, attaching a device to a mount point directory like /mnt/data, or assigning drive letters like D: on Windows). During mounting, the OS reads the partition's superblock, verifies file-system integrity, and registers the volume in the kernel mount table. If a non-empty directory serves as a mount point, its original contents are temporarily hidden until the mounted volume is unmounted.
To support dozens of distinct file systems (ext4, XFS, FAT32, ISO 9660, NFS) through a single unified set of system calls, Linux and UNIX kernels implement the Virtual File System (VFS) abstraction layer using four core object types:
| VFS Kernel Object | Primary Responsibility | Key Operations / Fields |
|---|---|---|
| Superblock Object | Represents a specific mounted file system | Block size, dirty flag, alloc_inode(), write_super() |
| Inode Object | Represents a specific file's metadata on disk | Inode number, permissions, timestamps, create(), lookup() |
| Dentry Object | Represents a directory entry linking a name to an inode | Cached path component for fast pathname resolution |
| File Object | Represents an open file associated with a process | Current file offset, access mode, read(), write(), lseek() |
14.8 Free-Space Management Worked Numerical Examples
Efficiently tracking which disk blocks are free is critical for allocation speed and disk utilization. Consider a small disk partition containing 32 blocks (numbered 0 to 31), where blocks 2, 3, 4, 5, 8, 9, 10, 11, 12, 18, 25, 26 are allocated and all remaining blocks are free:
- Bit Vector (Bitmap): Each block is represented by 1 bit (1 = free, 0 = allocated). The 32-bit map is
1100 0011 0000 0111 1101 1111 1001 1111. To locate the first free block, hardware bit-scan instructions inspect 32-bit or 64-bit words at a time: if word is non-zero and its first set bit is at offset , the free block number is . For a 4 TB disk with 4 KB blocks ( blocks), the bitmap occupies . - Counting Method: Instead of listing every free block individually, the OS stores pairs
(start_block, count)of contiguous free runs:(0, 2), (6, 2), (13, 5), (19, 6), (27, 5)—requiring just 5 records instead of 20 pointers.
14.9 Solid-State Drive (SSD) Internals and NVMe Architecture
Unlike magnetic disks that overwrite sectors in place, NAND flash SSDs organize storage into pages (4 KB–16 KB, unit of read/write) grouped into erase blocks (128–512 pages, unit of erasure). A flash page cannot be overwritten until its entire parent block is erased, and each flash block endures a finite number of Program/Erase (P/E) cycles (e.g., 3,000–10,000 cycles for TLC NAND). Consequently, the SSD's internal Flash Translation Layer (FTL) maintains a logical-to-physical mapping table, writes updated data to fresh erased pages, marks old pages stale, runs background garbage collection (copying valid pages out of partially stale blocks and erasing the block), and performs wear leveling so writes are spread evenly across all physical blocks.
To prevent write amplification (copying stale deleted files during garbage collection), the OS issues an asynchronous TRIM (or SCSI UNMAP) command whenever a user deletes a file, informing the SSD controller that those logical blocks no longer contain valid data. Modern NVMe (Non-Volatile Memory Express) SSDs connect directly over PCIe lanes and replace legacy single-queue SATA controllers with up to 64,000 parallel submission/completion queues, matching multicore CPU scalability and reducing I/O latency to tens of microseconds.
14.10 Disk Scheduling Selection Guidelines and Swap-Space Calculation
Selecting a disk scheduling algorithm depends on the expected I/O workload and fairness requirements. FCFS is suitable only for ultra-light loads or SSDs where seek distance is zero (modern Linux uses lightweight none/mq-deadline or kyber schedulers for NVMe SSDs). SSTF minimizes average seek time under moderate loads but risks starving edge cylinders. SCAN and LOOK eliminate starvation and work well under heavy HDD loads, while C-SCAN and C-LOOK provide the most uniform response-time variance because they sweep in only one active direction. For swap-space sizing, if a system has 16 GB of RAM and runs workloads peaking at 24 GB of virtual memory commit, configuring at least 8–16 GB of dedicated swap space (on a fast NVMe partition or swap file) prevents Out-Of-Memory (OOM) killer terminations while supporting hibernation if needed.
14.11 File Sharing, Consistency Semantics, and Protection
In multi-user operating systems, file sharing requires clear ownership, access control, and consistency guarantees when multiple processes read and write the same file concurrently. Each file is associated with an owner User ID (UID) and Group ID (GID), and POSIX systems enforce discretionary access control via three 3-bit fields (Owner, Group, Others) for Read (r), Write (w), and Execute (x). Special permission bits extend this model: the SetUID bit allows an executable (such as passwd) to run with the file owner's privileges rather than the caller's, while the Sticky Bit on shared directories (such as /tmp) ensures only a file's owner or root can delete or rename it. For complex enterprise rules, Access Control Lists (ACLs) attach explicit per-user and per-group allow/deny entries beyond the basic 9-bit mask.
Consistency semantics define when modifications made by one user become visible to other users reading the same file:
- UNIX Semantics: Writes to an open file are immediately visible to all other users who currently have the file open, and processes can share a single file pointer when a parent forks a child.
- Session Semantics (AFS): Writes to an open file are buffered locally and are not visible to other users until the file is closed; once closed, the updated version is visible only to sessions opened afterward.
- Immutable-Shared-Files Semantics: Once a file is declared shared, its name and contents cannot be modified; updates create a brand-new file version.
14.12 Second Worked Disk Scheduling Example (200 Cylinders, Head = 50)
To reinforce disk scheduling mechanics, consider a 200-cylinder disk (0–199) with the head starting at cylinder 50 (moving toward 0 for directional algorithms) and request queue: 82, 170, 43, 140, 24, 16, 190:
| Algorithm (Moving Toward 0) | Service Sequence | Total Head Movement |
|---|---|---|
| FCFS | 50 → 82 → 170 → 43 → 140 → 24 → 16 → 190 | cylinders |
| SSTF | 50 → 43 → 24 → 16 → 82 → 140 → 170 → 190 | cylinders |
| SCAN (down to 0) | 50 → 43 → 24 → 16 → 0 → 82 → 140 → 170 → 190 | cylinders |
| C-SCAN (down to 0, wrap 199) | 50 → 43 → 24 → 16 → 0 → 199 → 190 → 170 → 140 → 82 | cylinders |
| LOOK (down to 16) | 50 → 43 → 24 → 16 → 82 → 140 → 170 → 190 | cylinders |
14.13 Log-Structured and Copy-on-Write File Systems
Traditional file systems update metadata and data blocks in place, causing random disk seeks. Log-Structured File Systems (LFS) treat the entire disk as a sequential append-only log, buffering all dirty data and metadata in RAM and writing them in a single large sequential burst, using a background cleaner to compact fragmented segments. Copy-on-Write (CoW) file systems such as ZFS and Btrfs combine CoW semantics with end-to-end block checksums: modified blocks are always written to new disk locations before atomically updating the root tree pointer, enabling instant zero-cost snapshots, silent data-corruption detection, and crash immunity without a separate journal.
14.14 I/O Subsystem: Polling, Interrupts, DMA, and Buffering
Beyond disk scheduling, the operating system's I/O subsystem coordinates communication between the CPU and diverse peripheral controllers. Three interaction mechanisms govern I/O transfer:
- Programmed I/O (Polling): The CPU repeatedly reads a device controller's status register in a busy-wait loop until the device is ready, then transfers each byte. Polling is efficient only for ultra-fast devices where waiting is shorter than an interrupt-handler context switch.
- Interrupt-Driven I/O: The CPU issues an I/O command and switches to another ready process; the controller raises a hardware interrupt only when the device is ready for the next data transfer, freeing CPU cycles for useful computation.
- Direct Memory Access (DMA): For high-bandwidth block devices (NVMe SSDs, Gigabit NICs, GPUs), the OS programs a DMA controller with a source/destination memory address and byte count; the DMA engine transfers the entire buffer directly over the system bus and raises a single completion interrupt at the end.
To smooth speed mismatches between producers and consumers (such as a fast CPU writing to a slow printer or network link), kernels employ Buffering (storing data temporarily in kernel RAM), Caching (retaining a fast copy of frequently read disk blocks in the page cache), and Spooling (queuing sequential jobs for exclusive devices like printers on disk so multiple processes can submit output concurrently without interleaving pages).
14.15 Disk Performance and Storage Tiering Summary
| Storage Metric / Mechanism | Hard Disk Drive (HDD) | NVMe Solid-State Drive (SSD) |
|---|---|---|
| Primary Latency Bottleneck | Mechanical seek time + rotational delay (5–12 ms) | NAND flash page read/program + FTL lookup (20–100 μs) |
| Sequential vs Random IOPS | Random IOPS ~100–200 (seek-bound) | Random IOPS ~100,000–1,000,000+ (parallel queues) |
| OS Scheduling Policy | SCAN / C-SCAN / LOOK to minimize arm travel | none / mq-deadline (no mechanical seek) |
| Block Reclamation | Overwrite sectors directly in place | Requires TRIM + FTL garbage collection & wear leveling |
14.16 Disk Formatting, Partitioning, and Bad-Block Recovery
Before an operating system can store files on a new magnetic disk or SSD, the storage device must undergo three preparation steps. First, low-level (physical) formatting divides the disk into physical sectors containing a header (cylinder/sector number and Error-Correcting Code, ECC), data area (512 bytes or 4 KB), and trailer. Second, partitioning groups contiguous cylinders or logical blocks into independent logical volumes recorded in a Master Boot Record (MBR, supporting up to 4 primary partitions and 2 TB) or GUID Partition Table (GPT, supporting 128+ partitions and exabyte-scale drives). Third, high-level (logical) formatting creates the initial file-system structures—superblock, free-space bitmap, and empty root directory—on each partition.
Over a disk's operational lifetime, individual sectors may develop media defects. Controllers and operating systems handle bad blocks via two mechanisms: Sector Sparing (Forwarding), where the controller maps a defective logical sector to a hidden spare sector from a reserved pool, and Sector Slipping, where the controller shifts all subsequent logical sector numbers down by one slot during formatting to skip the bad sector without incurring an extra seek. In file systems, known unrecoverable blocks can also be assigned to a hidden bad-blocks file so the allocator never assigns them to user files.
14.17 File-System Performance Optimization
To maximize I/O throughput, modern operating systems combine four storage optimizations: (1) Disk-Block Caching (Unified Page Cache), keeping recently read blocks in free DRAM; (2) Read-Ahead (Prefetching), speculatively loading sequential blocks when a process reads block sequentially; (3) Elevator/I/O Merging, coalescing adjacent small write requests into a single large contiguous disk write; and (4) Asynchronous Write-Back, returning immediately to the user process after copying data into the kernel page cache and flushing dirty pages to disk in the background.
14.18 C/POSIX File and Directory Operations Walkthrough
Application developers interact with the Logical File System through POSIX file-descriptor and directory-stream APIs. Opening a directory with opendir() and iterating entries via readdir() abstracts away whether the underlying volume uses linear lists, B-trees, or remote NFS tables:
#include <dirent.h>
#include <sys/stat.h>
#include <stdio.h>
int main(void) {
DIR *dir = opendir(".");
if (!dir) return 1;
struct dirent *entry;
struct stat info;
while ((entry = readdir(dir)) != NULL) {
if (stat(entry->d_name, &info) == 0) {
printf("%-24s %10ld bytes (mode %o)\n",
entry->d_name, (long)info.st_size, info.st_mode & 0777);
}
}
closedir(dir);
return 0;
}Module V: Distributed, Real-Time & Modern Operating Systems
Chapter 15: Distributed Operating Systems and Distributed File Systems
15.1 Motivation, Types, and Coordination in Distributed OS
A Distributed Operating System (DOS) manages a collection of autonomous networked computers and presents them to users and applications as a single coherent computing system. The primary motivations for building distributed operating systems include resource sharing (allowing remote access to specialized hardware, printers, and databases), enhanced performance through parallel execution across multiple nodes, high reliability and fault tolerance (if one node crashes, replicas on surviving nodes continue serving requests), and incremental scalability (adding commodity servers rather than replacing an expensive mainframe).
Distributed systems are broadly categorized into three architectural types:
- Network Operating Systems (NOS): Each node runs its own local operating system and users are explicitly aware of multiple machines (logging in remotely via SSH or mounting explicit network shares).
- True Distributed Operating Systems: Provide single-system-image transparency—covering access, location, migration, replication, concurrency, and failure transparency—so process migration, global IPC, and memory/file access appear local to users regardless of physical node placement.
- Middleware-Based Distributed Systems: Run a unified software layer (such as RPC frameworks, gRPC, or Kubernetes container orchestrators) atop heterogeneous local OS kernels to coordinate distributed services.
Because distributed nodes lack a shared physical clock and shared memory, distributed operating systems rely on logical synchronization and coordination algorithms. Lamport's Logical Clocks assign monotonically increasing timestamps such that if event happens before event , then . When a coordinator node fails, Election Algorithms such as the Bully Algorithm (the surviving node with the highest process ID asserts leadership) or the Ring Algorithm (passing an election message around a logical ring) elect a new coordinator deterministically. Remote Procedure Calls (RPCs) abstract network socket messaging into local function-call syntax via client/server stubs and parameter marshaling.
15.2 Distributed File Systems (DFS): Naming, Transparency, and Remote File Access
A Distributed File System (DFS) enables clients to store, retrieve, and share files across networked servers as if they resided on local disks. Designing a DFS centers on two foundational concepts: naming and transparency. Location transparency means the file's logical path name does not reveal its physical server address (e.g., /project/data.csv remains unchanged even if moved across servers). Location independence means the name of a file does not need to change when its physical storage location migrates from one disk or server to another.
Remote file access in a DFS is implemented through two primary mechanisms:
- Remote Service Model (RPC-Based): Every client file operation (open, read, write, seek) is sent as a Remote Procedure Call to the server, which executes the disk I/O and returns the result. This simplifies cache coherence and supports stateless servers (as in NFSv3, where crash recovery requires no server-side session state), but incurs network round-trip latency on every access.
- Caching Model: Clients download whole files or large data blocks into local RAM or SSD caches, perform reads and writes locally at high speed, and flush modified blocks back to the server upon closing or periodic sync (used in AFS and stateful NFSv4 with leases/callbacks to preserve cache consistency).
Worked Numerical Example (DFS Caching Benefit): Suppose , network RTT , block transfer time , and server disk latency . Without caching (), every block access takes . With an 80% client cache hit ratio (), expected latency drops to —a 4.7x speedup.
In cloud-scale data centers, distributed file systems such as Google File System (GFS) and Hadoop HDFS split multi-terabyte files into large 64 MB or 128 MB chunks replicated across three separate racks (via a central NameNode metadata server and distributed DataNodes), optimizing for high-throughput sequential streaming rather than low-latency small-file random writes.
Chapter 16: Real-Time Operating Systems (RTOS)
16.1 Real-Time System Characteristics
A Real-Time Operating System (RTOS) is engineered for applications where correctness depends not only on the logical result of computation, but also on the exact physical time at which the result is delivered. Real-time systems power automotive anti-lock braking, avionic flight controllers, industrial robotics, and medical pacemakers. They are classified into two strictness tiers:
- Hard Real-Time Systems: Missing a deadline constitutes a catastrophic system failure (e.g., airbag deployment or nuclear reactor shutdown). Secondary storage delays and non-deterministic virtual memory paging are eliminated or strictly bounded.
- Soft Real-Time Systems: Critical tasks receive higher priority than non-critical tasks and retain priority until completion, but occasional deadline misses degrade quality of service rather than causing failure (e.g., live video streaming or VoIP).
16.2 Features of Real-Time Kernels and Schedulability
To guarantee deterministic response, real-time kernels minimize both interrupt latency (time from interrupt arrival to start of the ISR) and dispatch latency (time to stop one process and start a higher-priority real-time process). Key RTOS kernel features include:
- Preemptible Kernel Paths: Unlike traditional batch kernels that disable preemption inside long system calls, RTOS kernels insert preemption points or use fine-grained spinlocks so a high-priority task can preempt kernel execution within microseconds.
- Priority Inheritance Protocol: Solves priority inversion—a hazard where a low-priority task holding a mutex blocks a high-priority task while a medium-priority task preempts the low-priority task. Priority inheritance temporarily elevates the low-priority holder to the priority of the highest waiting task until it releases the mutex.
- Deterministic Memory & POSIX RT Extensions: Static memory pools or page locking (
mlockall()) prevent unpredictable page faults, while POSIX real-time scheduling policies (SCHED_FIFOandSCHED_RR) provide strict fixed-priority execution.
Periodic real-time tasks are scheduled using Rate-Monotonic Scheduling (RMS, assigning static priorities inversely proportional to task period ) or Earliest-Deadline-First (EDF, dynamically prioritizing the task with the closest absolute deadline):
Worked Numerical Example (RMS vs EDF): Consider two periodic tasks: Task 1 () and Task 2 (). Total utilization is . For , the RMS sufficient bound is . Because , RMS cannot guarantee schedulability by the bound alone, whereas EDF () guarantees both tasks meet every deadline.
Chapter 17: Modern OS Security, Virtualization, and Kernel Case Studies
17.1 Operating System Security and Protection
Protection refers to internal OS mechanisms controlling access of processes and users to resources (via Access Control Lists, capability lists, protection rings, and the Principle of Least Privilege), whereas security defends the system against external and internal threats. Program threats include buffer-overflow stack smashing (overwriting a function's return address to hijack control flow), Trojan horses, logic bombs, and kernel rootkits. System and network threats include self-propagating worms, port scanning, and Distributed Denial-of-Service (DDoS) floods.
Modern operating systems deploy layered defenses: Address Space Layout Randomization (ASLR, randomizing stack/heap/library base addresses), Non-Executable memory pages (NX/DEP, preventing execution of data on the stack), Mandatory Access Control frameworks (SELinux and AppArmor, confining even root-owned daemons to strict policy domains), salted cryptographic password hashing (Argon2/bcrypt), and hardware-rooted Secure Boot anchored in a Trusted Platform Module (TPM) chip.
17.2 Virtualization and Containers
Virtualization decouples operating systems from physical hardware using a Hypervisor (Virtual Machine Monitor). Type-1 (bare-metal) hypervisors such as VMware ESXi, Linux KVM, and Xen run directly on physical hardware (assisted by Intel VT-x / AMD-V CPU extensions) and host multiple isolated guest OS kernels. Type-2 hypervisors (VirtualBox, VMware Workstation) run atop a host OS. By contrast, OS-level virtualization (containers such as Docker and LXC) shares a single host OS kernel across isolated user-space environments using Linux namespaces (isolating PIDs, network stacks, mounts, and hostnames) and control groups (cgroups, bounding CPU, RAM, and disk I/O quotas).
| Dimension | Virtual Machines (Type-1/Type-2 Hypervisor) | Containers (OS-Level Virtualization) |
|---|---|---|
| Isolation Boundary | Hardware-level isolation; each VM runs a full guest OS kernel | Process-level isolation via namespaces and cgroups; shared host kernel |
| Boot Time & Footprint | Tens of seconds to boot; gigabytes of RAM/disk per VM | Milliseconds to start; megabytes of image/memory overhead |
| OS Heterogeneity | Can run Windows, Linux, and BSD guests on one host | All containers must match the host OS kernel ABI (e.g., Linux on Linux) |
17.3 Case Studies: Linux and Windows Kernels
The Linux kernel is a modular monolithic UNIX-like kernel supporting dynamic Loadable Kernel Modules (LKMs). Its default process scheduler—the Completely Fair Scheduler (CFS) and newer EEVDF—tracks each task's virtual runtime () in a red-black tree, always picking the task with the smallest accumulated weighted CPU time. Linux exposes kernel diagnostics via virtual file systems (/proc and sysfs), manages storage through a unified VFS layer (ext4, XFS, Btrfs), and initializes user space via systemd.
The Windows (NT architecture) operating system employs a hybrid kernel combining a Hardware Abstraction Layer (HAL) for portability, an Executive managing I/O, virtual memory, and an Object Manager (uniform handle-based security for files, processes, and events), preemptive multilevel feedback queue scheduling, a centralized Registry database for configuration, and NTFS featuring transaction journaling and fine-grained Access Control Lists. Comparing both architectures illustrates how diverse engineering designs converge on identical operating system principles: safe dual-mode isolation, fair scheduling, virtual memory paging, and reliable persistent storage.
17.4 Distributed Coordination, Clock Synchronization, and Election Algorithms
Because distributed operating systems lack a shared physical clock, physical clock skew across servers can violate causality in distributed databases and build systems. Cristian's Algorithm and the Network Time Protocol (NTP) synchronize physical clocks over a network by measuring Round-Trip Time (RTT). If a client sends a time request at local time , receives the server's timestamp at local time , and the server's internal processing time is , the client sets its clock to:
Worked Numerical Example (Cristian's Algorithm): If a client sends a request at , receives at , and , then one-way network delay is , and the client sets its clock to .
For distributed mutual exclusion without shared memory, systems use three strategies: Centralized Coordinator (a single leader grants locks; simple, 3 messages per critical section, but single point of failure), Ricart-Agrawala Distributed Algorithm (a requesting node broadcasts a timestamped request to all peers and enters only after receiving replies; messages, no single point of failure), or Token Ring (a unique token circulates around a logical ring). When a coordinator crashes, Election Algorithms choose a new leader: in the Bully Algorithm, any node noticing the timeout sends an ELECTION message to all higher-numbered nodes; if none responds, it declares itself COORDINATOR; if a higher node responds, that node takes over the election. In the Ring Algorithm, nodes pass an active-ID list around a logical ring and the highest ID becomes coordinator.
17.5 Virtualization Techniques and Linux CFS Case Study
Early x86 processors could not run unmodified guest OS kernels directly via simple Trap-and-Emulate because certain sensitive instructions failed silently in user mode instead of trapping to the hypervisor. Virtualization solved this in three stages: Full Virtualization with Binary Translation (VMware dynamically rewrote sensitive guest instructions on the fly), Paravirtualization (Xen modified the guest OS kernel to replace sensitive instructions with explicit hypercalls to the hypervisor), and Hardware-Assisted Virtualization (Intel VT-x and AMD-V added a dedicated root/non-root CPU mode and Extended Page Tables so unmodified guest OS kernels run at near-native speed and trap cleanly). Live Migration transfers a running VM from one physical host to another with sub-second downtime by iteratively pre-copying RAM pages over the network while the VM continues executing, then pausing briefly to copy the final dirty pages.
In Linux's Completely Fair Scheduler (CFS), each runnable task tracks its virtual runtime (), which increments at a rate inversely proportional to the task's priority weight (). Tasks with higher priority (lower nice value) accumulate vruntime more slowly and thus receive more CPU time:
| Kernel Subsystem | Linux Kernel (Monolithic Modular) | Windows NT Kernel (Hybrid) |
|---|---|---|
| CPU Scheduling | CFS / EEVDF using Red-Black Tree on vruntime | 32-level Preemptive Multilevel Feedback Queue |
| Primary File System | ext4 / XFS / Btrfs behind unified VFS | NTFS with Master File Table & USN Journal |
| IPC & System Calls | POSIX syscalls, pipes, sockets, mmap, D-Bus | Win32 API over Native NT API, LPC/ALPC, Named Pipes |
| Security Model | UID/GID, POSIX rwx, Capabilities, SELinux/AppArmor | Security Identifiers (SIDs), Access Control Lists (ACLs) |
17.6 Distributed Transparency Dimensions and Logical Clock Trace
A mature Distributed Operating System or Distributed File System strives to hide the physical distribution of hardware and data behind seven standardized forms of transparency:
| Transparency Type | Technical Meaning in Distributed Systems |
|---|---|
| Access Transparency | Local and remote resources are accessed using identical operations (e.g., POSIX read()). |
| Location Transparency | Resource names do not reveal physical network addresses or server hostnames. |
| Migration Transparency | Resources or processes can move to another node without changing their names. |
| Relocation Transparency | Resources can be moved while actively in use without interrupting client sessions. |
| Replication Transparency | Multiple copies of data exist for fault tolerance without the user knowing which copy is read. |
| Concurrency Transparency | Multiple users share distributed resources safely without interfering with each other. |
| Failure Transparency | Node or link failures are masked automatically via failover and retries. |
Worked Example (Lamport Logical Clocks): Consider three distributed processes starting with logical clocks at 0. (1) executes an internal event: . (2) sends message to with timestamp 2 (). (3) receives while its local clock is 1; applying Lamport's rule . (4) sends to at ; receives it at local time 0 and updates . Every causal chain strictly satisfies .
17.7 Distributed File Systems: Stateful vs Stateless and Cache Consistency
Distributed File Systems differ sharply in whether the server retains client state across requests:
| Property | Stateless DFS (e.g., NFSv3) | Stateful DFS (e.g., NFSv4, AFS) |
|---|---|---|
| Server State | Server tracks no open-file tables or client offsets | Server tracks open files, locks, and client cache leases |
| Crash Recovery | Trivial; client simply retries idempotent RPCs after reboot | Requires lease-recovery grace period after server restart |
| Request Size | Every request must carry full file handle and byte offset | Shorter requests using server-side file state |
| Cache Consistency | Client polling/expiration timers (weak consistency) | Server callbacks/delegations invalidate stale client caches |
To balance performance and correctness, DFS caching protocols use four update policies: Write-Through (writes go immediately to server disk; high reliability, high network latency), Delayed-Write (writes are buffered locally and flushed every 30 seconds; fast, but risks data loss on client crash), Write-on-Close (used by AFS: all writes stay local until close() flushes the entire file back to the server), and Centralized Control (server grants read-only or exclusive write leases).
17.8 Real-Time Priority Inversion and Rate-Monotonic Timeline
Consider three tasks in a real-time kernel: High-priority , Medium-priority , and Low-priority . At , acquires mutex . At , becomes ready, preempts , and requests , blocking on . At , (which does not need ) becomes ready and preempts , delaying indefinitely—this is Priority Inversion. With the Priority Inheritance Protocol, the moment blocks on , the kernel temporarily elevates 's priority to match , preventing from preempting so quickly releases and executes immediately.
In Rate-Monotonic Scheduling (RMS), consider Task A () and Task B (). Since , Task A receives higher static priority. Over a 100 ms hyperperiod: A runs [0–10], B runs [10–35], CPU idles [35–40], A runs [40–50], CPU idles [50–80], A runs [80–90], CPU idles [90–100]. Total utilization is , guaranteeing all deadlines are met.
17.9 OS Security Architecture: Buffer Overflow Anatomy and Defense
A classic stack-based buffer overflow occurs when a C program copies unchecked user input (using unsafe functions like strcpy() or gets()) into a fixed-size local array on the call stack, overwriting adjacent local variables, the saved frame pointer, and the function's return address. When the function returns, the CPU jumps to the attacker's injected payload or Return-Oriented Programming (ROP) gadget chain. Modern OS kernels neutralize this threat using four stacked defenses: Stack Canaries (placing a random guard value before the return address and verifying it before returning), NX/DEP (marking stack pages non-executable), ASLR (randomizing memory layout on every execution), and Control-Flow Integrity (CFI).
17.10 Distributed Election Algorithms: Bully vs Ring Worked Trace
When a coordinator node fails in a distributed cluster, surviving nodes must elect a new coordinator deterministically:
- Bully Algorithm Trace (6 Nodes: 1..6, Coordinator 6 crashes): Node 2 detects that Node 6 is unresponsive and broadcasts
ELECTION(2)to all higher-ID nodes (3, 4, 5, 6). Nodes 3, 4, and 5 replyOK, silencing Node 2. Next, Nodes 3, 4, and 5 each initiate their ownELECTIONto higher nodes; Node 5 receives no response from crashed Node 6, so Node 5 declares itself leader by broadcastingCOORDINATOR(5)to Nodes 1–4. - Ring Algorithm Trace (Logical Ring 1 → 2 → 3 → 4 → 5 → 6 → 1): Node 2 notices Node 6 is down and sends
ELECTION([2])to Node 3, which appends its ID ([2, 3]) and forwards to Node 4, then Node 5 ([2, 3, 4, 5]), skipping dead Node 6 and forwarding to Node 1 ([2, 3, 4, 5, 1]), returning to Node 2. Seeing its own ID in the list, Node 2 picks the maximum ID (5) and circulatesCOORDINATOR(5)around the ring.
17.11 Container Primitives: Linux Namespaces, cgroups, and OverlayFS
Unlike full virtual machines that emulate hardware and boot a separate OS kernel, Linux containers achieve lightweight isolation using three native kernel features:
- Linux Namespaces: Partition global kernel resources so each container sees its own isolated view:
pid(process IDs start at PID 1 inside the container),net(private network interfaces, routing tables, and ports),mnt(private root filesystem mount points),ipc(isolated System V IPC/POSIX message queues),uts(private hostname), anduser(mapping container root UID 0 to an unprivileged host UID). - Control Groups (cgroups v2): Enforce hierarchical resource limits and accounting across groups of processes, capping maximum CPU bandwidth shares, physical RAM limits (triggering container-scoped OOM kills if exceeded), and block I/O throughput.
- OverlayFS (Union File System): Stacks multiple read-only image layers beneath a single thin Copy-on-Write writable container layer, enabling hundreds of containers to share the same base OS libraries in RAM and disk while keeping per-container modifications isolated.
17.12 Cryptographic Authentication, Kerberos, and Network Firewalls
Modern operating systems integrate cryptography directly into user authentication, storage, and networking. Rather than storing plaintext passwords, systems store salted cryptographic hashes (such as Argon2id or bcrypt in /etc/shadow) so identical passwords produce different hashes and resist rainbow-table attacks. Enterprise networks use Kerberos—a trusted third-party Ticket-Granting Service (TGS) using symmetric keys—or Public Key Infrastructure (PKI) X.509 certificates for mutual authentication. Full-disk encryption (BitLocker on Windows, LUKS/dm-crypt on Linux, FileVault on macOS) encrypts every storage block with AES-XTS using keys sealed inside the hardware TPM chip. At the network boundary, kernel-level stateful packet-filtering firewalls (Linux nftables/iptables, Windows Filtering Platform) inspect IP/TCP headers and connection states to drop unauthorized traffic before it reaches user-space daemons.
17.13 Remote Procedure Call (RPC) Execution Lifecycle and Semantics
Remote Procedure Calls (RPCs) allow a client program on one host to invoke a function executing on a remote server using familiar local call syntax. The RPC lifecycle proceeds through six steps: (1) the client invokes a local client stub; (2) the client stub marshals (serializes) parameters into a platform-neutral network message (handling byte-order endianness); (3) the OS sends the packet over TCP/UDP to the server port; (4) the server stub unmarshals parameters and invokes the actual server procedure; (5) the server executes the work and returns results to the server stub; (6) the server stub marshals the response back to the client stub, which returns to the caller.
Because network links can drop packets or crash mid-call, RPC systems define explicit failure semantics: At-Least-Once semantics (client retries until an acknowledgment arrives, safe only for idempotent operations like reading a block) versus At-Most-Once semantics (server caches recent request IDs and replies so a retried non-idempotent operation like debiting a bank account is never executed twice).
17.14 Real-Time Kernel Latency Breakdown and POSIX RT Scheduling
In hard real-time embedded systems (such as FreeRTOS, Zephyr, or VxWorks), total event-response time equals the sum of Interrupt Latency (hardware propagation delay + time to finish the current uninterruptible instruction + saving CPU context) and Dispatch Latency (time for the real-time scheduler to preempt a lower-priority task, switch context, and launch the target real-time handler). Using the POSIX Real-Time API, developers lock critical pages into RAM with mlockall(MCL_CURRENT | MCL_FUTURE) to eliminate page-fault jitter and assign strict real-time scheduling classes:
| POSIX Scheduling Policy | Priority Range | Preemption & Time-Slicing Behavior |
|---|---|---|
SCHED_FIFO | Static 1–99 (Real-Time) | Runs until completion, I/O block, or preemption by a strictly higher-priority RT task |
SCHED_RR | Static 1–99 (Real-Time) | Same as SCHED_FIFO, but equal-priority RT tasks share CPU via fixed time quantum |
SCHED_OTHER | Dynamic (Nice -20..+19) | Standard CFS/EEVDF time-sharing; always yields immediately to any runnable RT task |
17.15 Distributed Shared Memory (DSM) and Hadoop HDFS Architecture
Distributed Shared Memory (DSM) provides programmers on a cluster of networked machines with the abstraction of a single globally shared virtual address space, even though no physical memory bus connects the nodes. When a process on Node A accesses a virtual page currently owned by Node B, the local MMU triggers a page fault, and the DSM runtime fetches the page over the network from Node B. To prevent thrashing ("ping-ponging" of pages when two nodes write to different variables on the same page, known as false sharing), DSM systems use release consistency and read-replication protocols.
For petabyte-scale data processing, the Hadoop Distributed File System (HDFS) adopts a write-once, read-many-times model tailored to streaming analytics. A single master NameNode manages the hierarchical namespace and maps files to 128 MB blocks, while hundreds of worker DataNodes store the actual blocks on local Linux ext4/XFS disks. By default, HDFS maintains a replication factor of 3: one replica on the local rack, a second on a different node in a remote rack, and a third on another node in that same remote rack, ensuring both high aggregate read bandwidth and immunity to entire-rack power or switch failures.
17.16 Mobile Operating Systems: Android and iOS Architecture
Mobile operating systems (Android and iOS) adapt desktop OS kernels for battery-powered ARM SoCs, touchscreens, and strict application sandboxing. Android runs a modified Linux kernel paired with the Binder IPC driver, Ashmem (anonymous shared memory), and the Android Runtime (ART) executing Ahead-of-Time (AOT) compiled bytecode; each app runs under a unique Linux UID inside an SELinux-confined sandbox. iOS runs Apple's XNU hybrid kernel (Mach microkernel + BSD subsystem) with hardware-enforced code signing, strict background execution budgets, and aggressive app suspension to maximize battery life.
17.17 Distributed System Fault Tolerance and CAP Theorem
In distributed operating systems and distributed file systems, hardware crashes and network partitions are normal occurrences rather than rare exceptions. Fault tolerance relies on redundancy (data replication across failure domains), heartbeat failure detectors, and consensus protocols (such as Paxos and Raft) that elect a single leader and replicate state-machine logs across a quorum of nodes. According to Brewer's CAP Theorem, during a network Partition (P), a distributed data store must choose between strong Consistency (C—every read receives the most recent write or an error, as in Raft-based etcd) or high Availability (A—every non-failing node returns a response, even if potentially stale, as in Dynamo-style stores).
17.18 POSIX Real-Time Scheduling Configuration in C
To enforce deterministic real-time execution on POSIX-compliant kernels (such as Linux with PREEMPT_RT or QNX Neutrino), systems programmers lock virtual memory pages using mlockall() and configure SCHED_FIFO priority attributes before launching time-critical control loops:
#include <pthread.h>
#include <sys/mman.h>
#include <sched.h>
int configure_rt_thread(pthread_t *thread, void *(*fn)(void *), int prio) {
mlockall(MCL_CURRENT | MCL_FUTURE); // Pin all pages in RAM to prevent page faults
pthread_attr_t attr;
struct sched_param param;
pthread_attr_init(&attr);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
param.sched_priority = prio; // Real-time priority 1..99
pthread_attr_setschedparam(&attr, ¶m);
return pthread_create(thread, &attr, fn, NULL);
}University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 5 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Operating System (University of Kerala BCA Sem 5)
Operating System (UK5DSCCAP303 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in operating system. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Operating System Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to Operating Systems
An Operating System (OS) is the foundational system software that manages computer hardware, provides common services for application programs, and acts as an intermediary between users and the underlying physical machine. A complete computer system can be viewed as four layered components: hardware (CPU, main memory, I/O devices), the operating system, application programs (compilers, database engines, web browsers, text editors), and users (humans, other machines, or automated services).
Process Management
The objective of multiprogramming is to have some process running at all times to maximize CPU utilization, whereas the objective of time-sharing is to switch the CPU among processes so frequently that users can interact with each program while it runs. To achieve this, the operating system maintains scheduling queues. As processes enter the system, they are placed in the job/ready queue—typically implemented as a linked list or priority tree of PCBs residing in main memory and waiting to execute.
Memory Management
Main memory consists of a large array of bytes, each with a unique physical address. For a program to execute, it must be brought from secondary storage into main memory and placed within a process. To ensure memory protection so no user process can overwrite the operating system kernel or another process's memory, the CPU hardware provides two special registers: a base register (holding the smallest legal physical memory address) and a limit register (specifying the size of the range).
Storage Management
A file is a named collection of related information recorded on non-volatile secondary storage. From the user's perspective, a file is the smallest logical unit of persistent storage, characterized by attributes such as name, identifier, type, location, size, protection permissions, and timestamps (creation, last modification, last access). Operations on files include creating, writing, reading, repositioning (seeking), deleting, and truncating.
Distributed, Real-Time & Modern Operating Systems
A Distributed Operating System (DOS) manages a collection of autonomous networked computers and presents them to users and applications as a single coherent computing system.
Core Curriculum & Key Topics
- Operating System Fundamentals and Computer System Architecture
- 1 What Operating Systems Do and Evolution of OS
- 2 Computer System Organization
- 3 Computer System Architecture
- Operating System Operations, Structures, and Distributed Systems
- 1 Dual-Mode Operation and Hardware Protection
- 2 Operating System Structures
- 3 Distributed Systems
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of operating system.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Operating System
The evaluation framework for Operating System (UK5DSCCAP303) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK5DSCCAP303 (Operating System) examination: 1. Sketch Layered Architectures & Protocol Flows: Draw neat block diagrams for OSI/TCP-IP layers, OS process state transitions, CPU scheduling Gantt charts, or cryptographic handshakes. 2. Solve Numerical & Scheduling Workouts Cleanly: Show step-by-step calculations for FCFS/SJF/Round Robin waiting times, subnetting, or cipher key transformations. 3. Cite Standards, Protocols & Statutes Accurately: Reference exact protocol numbers, IT Act provisions, or cloud service models (IaaS, PaaS, SaaS) clearly. 4. Balance All 5 Modules: University of Kerala question papers sample definitions, protocol comparisons, and architecture essays across every module.
Exam Preparation & Study Guides — Operating System
What is What Operating Systems Do and why is it important in Operating System?
An Operating System (OS) is the core system software managing computer hardware, providing common services for application programs, and acting as an intermediary between users and physical hardware.
What is the key distinction in Network OS vs Distributed OS?
A Network OS preserves separate machine identities (remote login, explicit shares), whereas a Distributed OS presents a single-system image with transparent process migration.
What is the key distinction in Non-Preemptive vs Preemptive?
Non-preemptive scheduling switches only when a process yields or terminates; preemptive scheduling interrupts running processes on timer/I/O events, requiring kernel lock synchronization.
What is Address Binding Stages and why is it important in Operating System?
Occurs at Compile Time (absolute code), Load Time (relocatable code), or Execution Time (dynamic hardware relocation).
What is File System Implementation and why is it important in Operating System?
Combines persistent on-disk structures with cached in-memory tables and Virtual File System (VFS) abstractions.
What is the official course code and credit structure for Operating System at University of Kerala?
Operating System carries the official course code UK5DSCCAP303 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Operating System?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Operating System (UK5DSCCAP303) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 5 Subjects
Browse study notes for other courses in BCA Sem 5:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.