Operating System Concepts and Techniques 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 Systems, Real-Time OS & Modern Extensions
Read Module Notes Online
Module I: Introduction to Operating Systems
Chapter 1: What Operating Systems Do and Computer System Organization
1.1 Definition and Dual Role of an Operating System
An Operating System (OS) is a foundational layer of system software that acts as an intermediary between computer hardware and application users. Because bare digital hardware—comprising processor cores, main memory arrays, system buses, and peripheral controllers—exposes only low-level machine instructions and electrical register interfaces, direct hardware programming for every application would be error-prone, non-portable, and insecure. The operating system abstracts those raw hardware mechanisms into clean, uniform services such as named files, virtual address spaces, protected processes, and network sockets. At the same time, it enforces strict isolation so that a fault or malicious instruction inside one program cannot corrupt the kernel or overwrite data belonging to another running program.
From the user viewpoint, the operating system is designed primarily for ease of use, responsiveness, and predictable interaction. On personal workstations and mobile devices, most system resources are dedicated to optimizing a single user's interactive experience, prioritizing graphical responsiveness, battery efficiency, and seamless peripheral integration. On shared multi-user servers or high-performance computing clusters, however, users share centralized CPU cores, memory banks, and storage arrays; here the OS must balance interactive responsiveness with fair resource partitioning so no single user monopolizes the machine. In embedded appliances such as automotive engine controllers or industrial robots, user interfaces may be minimal or absent, and the OS operates autonomously under deterministic timing constraints.
From the system viewpoint, the operating system functions simultaneously as a resource allocator and a control program. As a resource allocator, the OS arbitrates competing requests for finite CPU cycles, physical RAM frames, I/O bandwidth, and file locks, striving for high throughput, low turnaround latency, and equitable fairness. As a control program, it supervises the execution of user programs to prevent illegal memory accesses, invalid opcodes, or uncontrolled device operations. Because there is no universally accepted single definition of where the OS boundary ends, a practical rule identifies the kernel as the one program running at all times on the computer, while system programs (compilers, shells, file utilities) and application programs execute above it.
1.2 Computer System Organization and Interrupt-Driven Execution
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 shared access to main memory. Each device controller—such as a disk controller, USB host controller, or graphics adapter—manages a specific category of physical devices and maintains local buffer storage along with a set of special-purpose control and status registers. Because the CPU and device controllers can execute concurrently while competing for memory cycles, a hardware memory controller synchronizes access to shared Dynamic RAM (DRAM) to preserve data consistency.
When a computer powers on, it executes an initial bootstrap program stored in non-volatile Read-Only Memory (ROM) or Electrically Erasable Programmable ROM (EEPROM), commonly implemented today as Unified Extensible Firmware Interface (UEFI) firmware. The bootstrap program initializes CPU registers, memory controllers, and device buses, locates the operating system kernel on secondary storage, loads it into main memory, and transfers execution control to the kernel's entry point. Once initialized, the kernel enters an event-driven loop waiting for hardware or software events.
Hardware occurrences are signaled to the CPU by means of an interrupt. When a device controller completes an I/O transfer—for instance, reading a sector from a Solid-State Drive (SSD) into a buffer—it asserts a signal on the interrupt-request line connected to the CPU. Upon detecting the interrupt, the CPU finishes its current instruction, saves the current Program Counter (PC) and processor status register onto the kernel stack, and transfers control to a fixed memory address containing the interrupt vector. The interrupt vector is an array of pointers to Interrupt Service Routines (ISRs), allowing the CPU to jump directly to the handler corresponding to the specific device without polling every controller. Software-generated interrupts, called traps or exceptions, arise either from execution errors (such as division by zero or invalid memory access) or from explicit user requests for kernel services via system calls.
| I/O Mechanism | CPU Involvement | Data Transfer Path | Primary Use Case |
|---|---|---|---|
| Programmed I/O (Polling) | CPU continuously checks device status register in a busy-wait loop. | CPU registers mediate every byte or word between device and RAM. | Simple microcontrollers or ultra-low-latency polled hardware registers. |
| Interrupt-Driven I/O | CPU executes other tasks; interrupted only when device is ready for each word/byte. | CPU ISR transfers data between controller buffer and main memory. | Low-bandwidth devices such as keyboards, mice, and serial ports. |
| Direct Memory Access (DMA) | CPU configures DMA controller once, then resumes work; single interrupt on block completion. | DMA controller transfers entire blocks directly between device buffer and RAM over system bus. | High-throughput storage (NVMe SSDs), network cards (NICs), and audio/video streams. |
1.3 Storage Hierarchy and Computer System Architecture
Because CPU execution speed vastly outpaces main memory and secondary storage access times, computer systems organize storage into a hierarchy ranked by access latency, cost per bit, capacity, and volatility. At the apex sit CPU registers, offering single-cycle access but holding only tens to hundreds of bytes. Directly beneath registers reside L1, L2, and L3 cache memories constructed from fast Static RAM (SRAM), exploiting temporal and spatial locality to bridge the processor–memory speed gap. Main memory (RAM) provides gigabytes of byte-addressable volatile storage where active programs and kernel structures reside. Beneath RAM lie non-volatile secondary and tertiary storage tiers—Solid-State Drives (NAND flash), magnetic Hard Disk Drives (HDDs), optical media, and magnetic tape—preserving data across power cycles.
From an architectural standpoint, computer systems are categorized by the number and organization of their general-purpose processors:
- Single-Processor Systems: Historically dominant machines containing one main CPU core capable of executing a general-purpose instruction set, supplemented by specialized co-processors (such as disk, keyboard, or graphics controllers) that execute fixed microcode and do not run user processes.
- Multiprocessor Systems (Parallel Systems): Systems incorporating two or more closely coupled processors sharing the computer bus, clock, memory, and peripheral devices. In Asymmetric Multiprocessing (AMP), one primary processor schedules work and controls the system while secondary processors execute assigned tasks. In Symmetric Multiprocessing (SMP), all processors are peers running identical copies of the kernel, communicating through shared memory and balancing load dynamically. Modern multi-core chips place multiple execution cores on a single silicon die, reducing inter-core communication latency and power consumption compared to multi-socket boards.
- Clustered Systems: Loosely coupled architectures uniting two or more independent computer nodes over a high-speed Local Area Network (LAN) or InfiniBand fabric, typically sharing a Storage Area Network (SAN). Clusters provide high availability through asymmetric (hot-standby) or symmetric (active-active) failover and support High-Performance Computing (HPC) via parallelized workloads.
Chapter 2: Operating System Structure and Distributed Systems
2.1 Operating System Operations: Dual-Mode Execution and Timers
To protect the operating system and other running programs from errant or malicious code, hardware provides at least two distinct modes of operation tracked by a hardware mode bit inside the CPU status register: user mode (1) and kernel mode (0) (also termed supervisor, system, or privileged mode). When the system boots, the hardware starts in kernel mode. Before transferring control to a user application, the OS sets the mode bit to user mode. Whenever a user process executes a trap, triggers an interrupt, or invokes a system call, the hardware automatically switches the mode bit to kernel mode and jumps to a trusted kernel entry vector.
Certain machine instructions capable of harming system integrity—such as halting the CPU, modifying memory-management base/limit registers, disabling interrupts, or directly programming I/O controllers—are designated as privileged instructions. If a user-mode program attempts to execute a privileged instruction, the hardware refuses execution and generates an illegal-instruction trap to the kernel. Complementing dual-mode execution, a hardware timer prevents any user process from entering an infinite loop and starving the system. Before dispatching a user process, the OS loads a counter (for example, 1 to 10 milliseconds). As the system clock ticks, the counter decrements; when it reaches zero, a timer interrupt fires, returning control to kernel mode so the scheduler can preempt the running process.
2.2 Operating System Architectural Structures
As operating systems evolved from small batch monitors into multi-million-line software platforms, engineers adopted distinct internal architectures to manage complexity, performance, and maintainability.
| Architecture | Structural Design | Key Advantage | Primary Limitation |
|---|---|---|---|
| Monolithic Structure | Entire OS (scheduling, file systems, device drivers, networking) runs in a single kernel address space (e.g., traditional UNIX, Linux). | Minimal overhead for inter-subsystem calls; high raw throughput. | Tight coupling makes debugging harder; a fault in one driver can crash the entire kernel. |
| Layered Approach | OS partitioned into hierarchical layers (Layer 0 hardware up to Layer N user interface); each layer uses only services of lower layers. | Clean modularity, simplified verification, and straightforward isolated testing. | Strict ordering is difficult to define cleanly; each layer traversal adds call overhead. |
| Microkernel | Moves non-essential services out of kernel into user-space servers; kernel retains only minimal IPC, basic scheduling, and low-level memory mapping (e.g., Mach, QNX). | High reliability and security; easier extensibility and porting across hardware. | Frequent user-to-kernel context switches and message passing degrade performance. |
| Loadable Kernel Modules (LKMs) | Object-oriented core kernel dynamically loads and unloads binary modules (drivers, file systems) at runtime (e.g., Linux, Solaris, macOS). | Combines modular extensibility of microkernels with fast direct function calls of monolithic kernels. | Loaded modules still execute in privileged kernel space, requiring strict signing and verification. |
| Hybrid Systems | Combines monolithic performance paths with microkernel isolation concepts and modular subsystems (e.g., Windows NT, Apple macOS XNU). | Balances high desktop/server performance with strong subsystem separation. | Increased architectural complexity across kernel and user-space boundaries. |
2.3 Distributed Systems Overview
A distributed system is a collection of physically separate, possibly heterogeneous computer systems networked together to provide users with shared access to computational power, data storage, and peripheral resources. Unlike tightly coupled multiprocessors that share a single clock and physical memory, nodes in a distributed system communicate exclusively by exchanging messages over a communication network using protocols such as TCP/IP. Distributed systems enhance performance through parallel execution, increase reliability by replicating services across independent failure domains, and support incremental scalability as workload demand grows.
Depending on the degree of coupling and transparency, distributed environments take two primary software forms. A Network Operating System (NOS) provides features such as file sharing across a network and a communication scheme allowing different processes on separate computers to exchange messages; users remain explicitly aware of individual machines and log into remote hosts manually. By contrast, a Distributed Operating System presents a single-system image across autonomous nodes, hiding physical machine boundaries so that remote process execution, memory access, and file retrieval appear identical to local operations. We examine distributed OS architectures and distributed file systems in detail in Module V.
Chapter 3: Operating System Services, Interfaces, and System Calls
3.1 Operating System Services
An operating system provides an execution environment for programs by offering two complementary sets of services: those directly helpful to users and those engineered to ensure efficient, safe operation of the system itself.
- User-Facing Services: These include the User Interface (UI) for human interaction; Program Execution to load code into memory, run it, and handle normal or abnormal termination; I/O Operations abstracting device-specific protocols for files and peripherals; File-System Manipulation enabling creation, deletion, reading, writing, searching, and permission control of directories and files; Communications allowing processes on the same host or across networks to exchange data via shared memory or message passing; and Error Detection continuously monitoring CPU, memory parity, bus faults, and user program exceptions to preserve system stability.
- System-Efficiency Services: When multiple users or jobs execute concurrently, the OS provides Resource Allocation (CPU cycles, main memory, file storage, I/O devices), Accounting / Logging (tracking resource usage for billing or capacity planning), and Protection and Security (ensuring controlled access to internal kernel objects and authenticating external users against unauthorized intrusion).
3.2 User Operating System Interfaces
Users and administrators interact with an operating system primarily through two interface paradigms: Command-Line Interpreters and Graphical User Interfaces. A Command-Line Interpreter (CLI), commonly called a shell (such as Bash, Zsh, or PowerShell), reads text commands entered by a user or stored in a script file and executes them. Some shells implement commands internally, while others treat the command name as an executable file to be loaded into memory and run, making it trivial to extend the shell with new utilities without modifying the interpreter itself.
A Graphical User Interface (GUI) provides a visual desktop metaphor featuring windows, icons, menus, and pointer or touch interactions (such as Windows Explorer, macOS Aqua, or Linux GNOME/KDE). Rather than memorizing command syntax, users manipulate graphical objects directly, while underlying windowing managers translate pointer events into application callbacks and system calls. Modern systems frequently combine both: GUIs streamline everyday productivity, while CLIs remain indispensable for automation, remote SSH administration, and reproducible DevOps scripting.
3.3 System Calls: Mechanism, Types, and Execution
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 trap invocation), system calls allow user-mode applications to request privileged kernel actions safely. Because direct invocation of raw system call numbers is tedious and non-portable across OS versions, application developers normally program against an Application Programming Interface (API)—such as the POSIX API (on UNIX/Linux/macOS) or the Win32 API (on Windows). Runtime libraries such as libc translate standard API function calls (e.g., read(), write(), open()) into the appropriate kernel trap instructions.
Passing parameters from a user program to the kernel during a system call follows one of three standard mechanisms: (1) passing parameters directly in CPU registers (fastest, limited by register count); (2) storing parameters in a memory block or table and passing the starting address of that block in a single register (used by Linux and Solaris when parameter counts exceed register capacity); or (3) pushing parameters onto the program stack and having the OS pop them off.
| System Call Category | Core Responsibilities | Representative POSIX / UNIX Calls | Representative Windows Win32 Calls |
|---|---|---|---|
| Process Control | Create/terminate processes, load/execute binaries, wait for events, allocate memory. | fork(), execve(), exit(), waitpid() |
CreateProcess(), ExitProcess(), WaitForSingleObject() |
| File Management | Create, delete, open, close, read, write, reposition file pointers, inspect attributes. | open(), read(), write(), close(), lseek() |
CreateFile(), ReadFile(), WriteFile(), CloseHandle() |
| Device Management | Request/release devices, read/write device buffers, configure device attributes. | ioctl(), read(), write() |
SetConsoleMode(), DeviceIoControl() |
| Information Maintenance | Get/set system time, process IDs, OS version, resource statistics. | getpid(), alarm(), time(), uname() |
GetCurrentProcessId(), GetLocalTime(), Sleep() |
| Communications | Create/delete connections, send/receive messages, attach shared memory regions. | pipe(), shmget(), mmap(), socket() |
CreatePipe(), CreateFileMapping(), MapViewOfFile() |
| Protection | Modify file/resource permissions, manage user/group ownership and access lists. | chmod(), chown(), umask() |
SetFileSecurity(), InitializeSecurityDescriptor() |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork(); /* Create a child process */
if (pid < 0) {
perror("fork failed");
return 1;
} else if (pid == 0) {
/* Child process replaces its memory image with /bin/ls */
char *args[] = {"ls", "-l", NULL};
execvp(args[0], args);
perror("execvp failed");
exit(1);
} else {
/* Parent process waits for child completion */
int status = 0;
waitpid(pid, &status, 0);
printf("Parent: child %d exited with status %d\n", pid, WEXITSTATUS(status));
}
return 0;
}Chapter 4: Processes, Process Control Block, and Threads
4.1 The Process Concept and Memory Layout
A process is fundamentally a program in execution. Whereas a program is a passive entity—a file containing compiled machine instructions stored on disk—a process is an active entity with a Program Counter specifying the next instruction to execute and a set of associated resources. Two processes may execute the same program binary (for example, two separate terminal sessions running the same text editor), yet they remain distinct processes with independent execution states, memory stacks, and open file descriptors.
In virtual memory, a process image is partitioned into well-defined segments: the text section holding immutable executable machine code; the data section storing initialized and uninitialized global and static variables; the heap containing memory dynamically allocated at runtime (via malloc() or new) that grows upward; and the stack storing temporary function parameters, return addresses, and local variables that grows downward toward the heap.
4.2 Process States and State Transitions
As a process executes, it transitions through a well-defined lifecycle of states maintained by the kernel:
- New: The process is being created; kernel structures are initialized, but the process has not yet been admitted to the pool of executable processes.
- Ready: The process is loaded in main memory, holds all necessary resources except the CPU, and waits in the ready queue to be assigned to a processor core by the short-term scheduler.
- Running: Instructions of the process are currently being executed by a CPU core. At any instant on a single-core processor, at most one process can be in the running state.
- Waiting (Blocked): The process cannot continue execution until an external event occurs—such as completion of a disk I/O operation, arrival of a network packet, or acquisition of a synchronization lock.
- Terminated: The process has finished execution (normally via
exit()or abnormally via a fatal signal); the kernel deallocates its memory and resources while briefly retaining exit status for the parent process to collect.
4.3 Process Control Block (PCB)
Every process is represented inside the operating system kernel by a data structure called the Process Control Block (PCB) (also known as a Task Control Block, or task_struct in Linux). The PCB serves as the complete repository of all information required to suspend and later resume a process seamlessly during a context switch.
| PCB Field | Technical Contents | Operational Purpose |
|---|---|---|
| Process State | Current lifecycle flag (New, Ready, Running, Waiting, Terminated). | Determines which kernel queue owns the process and whether it is dispatchable. |
| Program Counter (PC) | Memory address of the next machine instruction to be executed. | Ensures execution resumes at the exact instruction following an interrupt or preemption. |
| CPU Registers | Accumulators, index registers, stack pointers, general-purpose and condition-code registers. | Saved on interrupt/context switch and restored when the process is re-dispatched. |
| CPU-Scheduling Info | Process priority, pointers to scheduling queues, nice values, accumulated CPU burst time. | Used by the CPU scheduler to select the next process to run. |
| Memory-Management Info | Base/limit registers, page tables, or segment tables depending on OS memory architecture. | Loaded into the Memory Management Unit (MMU) on context switch to enforce address isolation. |
| Accounting Info | CPU time consumed, real time elapsed, process ID (PID), parent PID, time limits. | Supports resource tracking, billing, and enforcement of per-process quotas. |
| I/O Status Info | List of allocated I/O devices and open file descriptor table pointers. | Tracks active files, sockets, and pending I/O requests for cleanup upon termination. |
4.4 Threads and Multithreaded Models
A thread is the basic unit of CPU utilization, often described as a lightweight process. Within a traditional single-threaded process, one thread of control executes sequentially. In a multithreaded process, multiple threads execute concurrently within the same process address space. Each thread maintains its own private Thread ID, Program Counter, register set, and execution stack, while sharing the parent process's code section, data section, heap, and open files/signals with sibling threads.
Multithreading delivers four major engineering benefits: (1) Responsiveness—an interactive GUI or web server can continue serving user events on one thread while another thread performs slow disk or network I/O; (2) Resource Sharing—threads share memory natively without explicit shared-memory IPC setup; (3) Economy—creating a thread and switching between threads within the same process is orders of magnitude faster than creating a new process and flushing virtual address mappings; and (4) Scalability—threads can execute truly in parallel across multiple CPU cores on SMP/multi-core hardware.
Operating systems map user-level threads (managed by user-space thread libraries without kernel awareness) to kernel-level threads (scheduled directly by the OS) using one of three multithreading models:
- Many-to-One Model: Maps many user-level threads onto a single kernel thread. Thread management is fast in user space, but if any thread executes a blocking system call, the entire process blocks, and multiple threads cannot run in parallel on multi-core CPUs.
- One-to-One Model: Maps each user thread to a dedicated kernel thread (used by modern Linux NPTL and Windows). Provides true multi-core parallelism and non-blocking execution when another thread waits on I/O, at the cost of kernel overhead per created thread.
- Many-to-Many Model: Multiplexes many user-level threads onto a smaller or equal pool of kernel threads, combining flexible user-level concurrency with multi-core kernel parallelism without exhausting kernel resources.
4.5 Thread Libraries, Thread Pools, and Implicit Threading
A thread library provides programmers with an API for creating and managing threads. Three primary libraries dominate production systems: POSIX Pthreads (a specification—not an implementation—used across UNIX, Linux, and macOS), Windows Threads (a kernel-level library on Windows), and Java Threads (managed by the JVM atop the host OS). Because creating a new thread per incoming network request still incurs allocation overhead and risks exhausting memory under denial-of-service spikes, high-throughput servers employ thread pools: a bounded number of worker threads are created at startup and sit idle waiting for tasks submitted to a shared work queue, bounding resource consumption and eliminating per-request creation latency.
Modern multi-core programming increasingly shifts thread management from application developers to compilers and runtime libraries via implicit threading. Techniques include OpenMP (compiler directives such as #pragma omp parallel for that automatically parallelize loops across cores), Grand Central Dispatch (GCD) on Apple platforms, and Fork-Join frameworks. Furthermore, multithreaded kernels must handle Thread-Local Storage (TLS) so each thread can maintain private copies of static-like variables (such as errno), as well as thread cancellation—either asynchronous cancellation (terminating a target thread immediately, risking unfreed locks) or deferred cancellation (allowing the target thread to poll cancellation points safely before exiting).
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
long long shared_sum = 0;
void *worker_runner(void *arg) {
int upper = *((int *)arg);
long long local_sum = 0;
for (int i = 1; i <= upper; i++) {
local_sum += i;
}
shared_sum = local_sum;
pthread_exit(0);
}
int main(void) {
pthread_t tid;
pthread_attr_t attr;
int limit = 1000;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, worker_runner, &limit);
pthread_join(tid, NULL);
printf("Computed sum = %lld\n", shared_sum);
return 0;
}4.6 Architectural Comparison: Process vs. Thread
| Attribute | Process (Heavyweight) | Thread (Lightweight) |
|---|---|---|
| Address Space | Isolated private virtual address space protected by MMU page tables. | Shares code, data, heap, and open files with sibling threads in the same process. |
| Context Switch Cost | High: requires saving registers, switching page-table base register, and flushing TLB. | Low: saves only CPU registers, PC, and stack pointer; page tables and TLB remain valid. |
| Inter-Unit Communication | Requires explicit kernel IPC (pipes, sockets, or shared memory setup). | Direct, zero-copy reads and writes to shared process variables (with synchronization). |
| Fault Isolation | Strong: a crash (segmentation fault) in one process does not terminate other processes. | Weak: an unhandled fault in one thread terminates the entire parent process. |
4.7 System Boot Sequence and OS Observability Tools
Bringing a computer from cold power-off to a multi-user login prompt follows a deterministic multi-stage chain. First, power-good circuitry releases the CPU reset line, causing the processor to jump to a fixed firmware address in UEFI / BIOS flash memory. Firmware runs the Power-On Self-Test (POST) to verify DRAM timings, PCIe buses, and storage controllers, then locates the EFI System Partition and loads a second-stage boot loader such as GRUB2 or Windows Boot Manager. The boot loader reads the compressed kernel image (vmlinuz) and initial RAM disk (initramfs) into memory and transfers control to the kernel's startup routine. The kernel initializes interrupt descriptor tables, memory allocators, and device drivers, mounts the root file system, and spawns User-Space PID 1 (systemd or init), which launches background daemons and user shells.
Once running, operating systems expose diagnostic interfaces for tracing system calls and kernel events without modifying application source code. On Linux, strace intercepts every system call invoked by a process (logging arguments and return codes), while perf and eBPF (Extended Berkeley Packet Filter) attach lightweight, kernel-verified probes to tracepoints, enabling microsecond-level latency profiling of schedulers, network stacks, and disk drivers in live production environments.
Module II: Process Management
Chapter 5: Process Scheduling, Operations, and Interprocess Communication
5.1 Scheduling Queues and Types of Schedulers
The objective of multiprogramming is to have some process running at all times to maximize CPU utilization, while the objective of time-sharing is to switch the CPU among processes so frequently that users can interact with each program while it is running. To achieve this, the operating system maintains several scheduling queues. When a process enters the system, it is placed in the job queue (or admitted directly into memory). Processes residing in main memory and ready to execute wait in the ready queue, typically implemented as a linked list or priority heap of PCB pointers. Processes waiting for a specific I/O device wait in that device's device queue.
Three classes of schedulers govern process movement across these queues:
- Long-Term Scheduler (Job Scheduler): Selects which jobs from a mass-storage spooling pool should be loaded into main memory for execution. It executes infrequently (seconds or minutes) and controls the degree of multiprogramming—the total number of processes in memory. It must select a balanced mix of I/O-bound processes (spending most time waiting for I/O) and CPU-bound processes (performing long bursts of computation).
- Short-Term Scheduler (CPU Scheduler): Selects which ready process in memory should be allocated the CPU next. Because it executes very frequently (often every 10–100 milliseconds), it must be extremely fast to avoid wasting CPU cycles on scheduling overhead.
- Medium-Term Scheduler: Present in time-sharing systems supporting swapping, this scheduler temporarily removes partially executed processes from main memory to disk (swap-out) to reduce memory pressure and later reloads them (swap-in) to resume execution.
5.2 Context Switch, Dispatcher, and Preemptive vs. Non-Preemptive Scheduling
Switching the CPU from one process to another requires performing a context switch: the kernel saves the state (registers, PC, memory mappings) of the currently running process into its PCB and restores the saved state of the newly selected process from its PCB. Context-switch time is pure overhead because the system performs no useful application work while switching; hardware support such as multiple register sets or fast cache/TLB tagging helps minimize this latency.
The dispatcher is the kernel module that actually gives control of the CPU to the process selected by the short-term scheduler. Its responsibilities are: (1) performing the context switch, (2) switching from kernel mode to user mode, and (3) jumping to the proper location in the user program to restart it. The time elapsed for the dispatcher to stop one process and start another running is called the dispatch latency.
CPU-scheduling decisions take place under four circumstances: (1) a process switches from running to waiting (e.g., I/O request), (2) a process switches from running to ready (e.g., timer interrupt), (3) a process switches from waiting to ready (e.g., I/O completion), or (4) a process terminates. When scheduling occurs only under conditions (1) and (4), the scheme is non-preemptive (cooperative): once the CPU is allocated to a process, it keeps the CPU until it voluntarily releases it by terminating or blocking. When scheduling also occurs under conditions (2) and (3), the scheme is preemptive, allowing the kernel to interrupt a running process mid-burst. Preemptive scheduling improves responsiveness but requires careful synchronization when processes share kernel or user data.
5.3 Operations on Processes and Interprocess Communication (IPC)
Operating systems provide mechanisms for process creation and process termination. A parent process creates child processes forming a process tree identified by unique Process Identifiers (PIDs). In UNIX/Linux, fork() duplicates the calling process address space (optimized via Copy-on-Write), and exec() overlays the child's memory with a new executable program. A process terminates normally via exit(), returning an exit status to its parent (collected via wait()). If a parent terminates before collecting its child, the child becomes an orphan (adopted by init/systemd); if a child terminates before the parent calls wait(), it briefly remains a zombie until its exit status is reaped.
Processes executing concurrently are either independent (neither affecting nor affected by other processes) or cooperating (sharing data or coordinating execution). Cooperating processes require Interprocess Communication (IPC) via two fundamental models:
- Shared Memory: Cooperating processes establish a shared region of virtual memory (e.g., POSIX
shm_open()+mmap()). After initial kernel setup, processes read and write directly at memory speed without kernel intervention, though applications must explicitly synchronize concurrent writes. - Message Passing: Processes exchange structured messages via kernel-managed primitives
send(message)andreceive(message)over direct links (naming peer PIDs) or indirect links (mailboxes/ports/pipes). Message passing is easier to implement in distributed systems and avoids shared-memory race conditions, at the cost of kernel copy overhead per message.
5.4 Scheduling Criteria
Different CPU-scheduling algorithms exhibit different performance characteristics. To compare them objectively, five standard metrics are evaluated:
- CPU Utilization: Percentage of time the CPU remains productively busy executing processes (ideally 40% in lightly loaded systems to 90%+ in heavily loaded servers).
- Throughput: Number of processes completed per unit time.
- Turnaround Time (TAT): Total interval from process submission (arrival) to process completion, encompassing waiting, execution, and I/O delays.
- Waiting Time (WT): Sum of periods a process spends sitting in the ready queue waiting for CPU allocation.
- Response Time (RT): Time from submission of a request until the first response is produced (critical for interactive applications).
Chapter 6: CPU Scheduling Algorithms and Worked Numericals
6.1 First-Come, First-Served (FCFS) Scheduling
FCFS is the simplest non-preemptive scheduling algorithm: the process that requests the CPU first is allocated the CPU first, managed directly with a FIFO ready queue. While trivial to implement and starvation-free, FCFS suffers from high average waiting time when a long CPU-bound process arrives ahead of several short interactive processes—a phenomenon known as the convoy effect.
6.2 Shortest-Job-First (SJF) and SRTF Scheduling
SJF associates each process with the length of its next CPU burst and allocates the CPU to the process with the smallest next burst. Mathematically, SJF is provably optimal in minimizing average waiting time for a given set of processes. However, exact future burst lengths are rarely known in general-purpose systems, so kernels estimate them using exponential averaging of past bursts: , where is the most recent observed burst, is the previous prediction, and weights recent history. The preemptive variant of SJF is Shortest-Remaining-Time-First (SRTF), which preempts the running process if a newly arriving process has a shorter remaining burst.
6.3 Priority Scheduling and Round-Robin (RR) Scheduling
Priority Scheduling assigns a priority number to each process and allocates the CPU to the highest-priority ready process (can be preemptive or non-preemptive). A major hazard is starvation (indefinite blocking), where low-priority processes wait indefinitely under heavy high-priority load. The standard remedy is aging, which gradually increases 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 operates like FCFS with preemption governed by a fixed time quantum (, typically 10–100 ms). The ready queue is treated as a circular FIFO queue: each process runs for at most time units; if its burst exceeds , a timer interrupt preempts it and appends it to the tail of the ready queue. If is too large, RR degenerates into FCFS; if is too small, excessive context switches degrade throughput.
| Algorithm | Preemptive? | Starvation Risk | Key Strength | Primary Weakness |
|---|---|---|---|---|
| FCFS | No | No | Simple FIFO queue; zero starvation. | Convoy effect increases average waiting time. |
| SJF / SRTF | SJF: No; SRTF: Yes | Yes (long jobs) | Provably minimum average waiting time. | Future CPU burst length cannot be known exactly. |
| Priority | Either | Yes (low priority) | Supports critical/real-time task importance. | Starvation of low-priority jobs without aging. |
| Round-Robin | Yes (quantum) | No | Excellent interactive response time; fair sharing. | Higher average turnaround if quantum is poorly tuned. |
6.4 Worked Numerical Example: Comparing FCFS, Non-Preemptive SJF, and Round-Robin
Consider four processes arriving at time in order with CPU burst times: , , , milliseconds. Let us compute the Gantt charts, Turnaround Time (TAT), and Waiting Time (WT) for FCFS, SJF, and Round-Robin ().
- FCFS Order: . Waiting times: . Average WT = .
- SJF Order: Sorted by burst: . Gantt: . Waiting times: . Average WT = .
- Round-Robin (q = 4 ms): Cycle 1: . ( finishes at 8). Cycle 2: . ( finishes at 20, at 25). Cycle 3: . ( finishes at 26). Waiting times (): , , , . Average WT = , with fast initial response for every process by .
Chapter 7: Process Synchronization
7.1 Race Conditions and the Critical-Section Problem
When cooperating processes or threads concurrently access and manipulate shared data, the final outcome can depend on the exact interleaved order in which instructions execute—a defect known as a race condition. For example, if two threads simultaneously execute counter++ (which compiles to register load, increment, and store), interleaved execution can lose one update. To prevent race conditions, the segment of code in which a process accesses shared variables is designated a critical section.
Any valid solution to the critical-section problem must satisfy three mandatory requirements:
- Mutual Exclusion: If process is executing in its critical section, no other process can execute in its critical section simultaneously.
- Progress: If no process is executing in its critical section and some processes wish to enter, only processes not executing in their remainder sections can participate in deciding who enters next, and this selection cannot be postponed indefinitely.
- Bounded Waiting: A finite bound must exist 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).
7.2 Semaphores and Classic Synchronization Problems
A semaphore , proposed by Edsger Dijkstra, is an integer synchronization variable accessed exclusively through two indivisible (atomic) operations: wait(S) (historically P(S)) and signal(S) (historically V(S)). In a counting semaphore, can range over an unrestricted domain to control access to a finite pool of identical resources. In a binary semaphore, is restricted to 0 and 1, functioning identically to a mutex lock. Modern OS implementations avoid busy-waiting (spinlocks) on uniprocessors by associating a waiting queue with each semaphore: when wait(S) finds , the calling process blocks itself and is placed in the semaphore's queue until another process invokes signal(S) to wake it.
/* Shared declarations: buffer of size N */
semaphore mutex = 1; /* Controls exclusive access to buffer */
semaphore empty = N; /* Counts empty buffer slots */
semaphore full = 0; /* Counts filled buffer slots */
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); /* Leave critical section */
signal(full); /* Increment filled slot count */
}
item consumer(void) {
wait(full); /* Decrement full count; block if buffer is empty */
wait(mutex); /* Enter critical section */
item next_consumed = remove_item();
signal(mutex); /* Leave critical section */
signal(empty); /* Increment empty slot count */
return next_consumed;
}Semaphores also model two other canonical synchronization benchmarks: the Readers-Writers Problem (allowing multiple concurrent readers when no writer is active, while giving writers exclusive access) and the Dining-Philosophers Problem (modeling five philosophers sharing five single chopsticks, illustrating how naive circular resource acquisition causes deadlock unless asymmetric ordering or a room-capacity semaphore is enforced).
7.3 Monitors
Although semaphores are powerful, a single misplaced wait() or omitted signal() can silently corrupt mutual exclusion or cause deadlock. A monitor is a high-level language synchronization construct (an abstract data type) that encapsulates shared data variables together with the procedures permitted to operate on them. Only one process or thread may be active inside a monitor at any instant, as the compiler automatically enforces mutual exclusion on all monitor procedures. To allow a process inside a monitor to pause until a specific state holds, monitors provide condition variables supporting two operations: x.wait() (suspends the caller and releases monitor exclusion) and x.signal() (resumes exactly one suspended process waiting on condition x).
Chapter 8: Deadlocks and Banker's Algorithm
8.1 Deadlock Characterization
In a multiprogramming environment, a set of processes is in a deadlock state when every process in the set is waiting for an event that can be caused only by another process in the same set. Deadlock can arise if and only if four Coffman conditions hold simultaneously in a system:
- Mutual Exclusion: At least one resource must be held in a non-sharable mode (only one process can use it at a time).
- Hold and Wait: A process must be currently 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; they can be released only voluntarily by the holding process 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 with a Resource-Allocation Graph (RAG) containing process vertices and resource vertices connected by 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 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 Coffman conditions; (2) Deadlock Avoidance—requiring advance declaration of maximum resource needs so the OS grants requests only when the resulting state remains safe; (3) Deadlock Detection and Recovery—allowing deadlocks to occur, periodically running a detection algorithm, and breaking the cycle; or (4) Ignoring the Problem (Ostrich Algorithm)—used by most desktop OSes like Linux and Windows when deadlocks are rare and prevention overhead is unacceptable.
- Deadlock Prevention Techniques: Break Hold and Wait by requiring processes to request all needed resources upfront before execution (low resource utilization). Break No Preemption by forcing a process holding resources to release them if a new request cannot be immediately satisfied. Break Circular Wait (the most practical prevention method) by imposing a strict total linear ordering on all resource types and requiring processes to request resources only in strictly increasing order.
- Deadlock Avoidance & Banker's Algorithm: A system is in a safe state if there exists a safe sequence such that for every , the remaining resources may still request can be satisfied by currently available resources plus resources held by all preceding (). Dijkstra's Banker's Algorithm maintains four matrices/vectors for processes and resource types:
Available[m],Max[n][m],Allocation[n][m], andNeed[n][m] = Max[n][m] - Allocation[n][m].
8.3 Worked Numerical Example: Banker's Algorithm Safety Check
Consider a system with 5 processes (–) and 3 resource types ( total instances). Suppose current Allocation and Max are given below, leaving Available = (3, 3, 2).
| Process | Allocation (A, B, C) | Max (A, B, C) | Need = Max − Allocation | Safe Execution Step |
|---|---|---|---|---|
| P0 | (0, 1, 0) | (7, 5, 3) | (7, 4, 3) | 4th: runs when Work = (7, 4, 3) → Work becomes (7, 5, 3) |
| P1 | (2, 0, 0) | (3, 2, 2) | (1, 2, 2) | 1st: Need (1,2,2) ≤ Work (3,3,2) → Work becomes (5, 3, 2) |
| P2 | (3, 0, 2) | (9, 0, 2) | (6, 0, 0) | 5th: runs when Work = (7, 5, 5) → Work becomes (10, 5, 7) |
| P3 | (2, 1, 1) | (2, 2, 2) | (0, 1, 1) | 2nd: Need (0,1,1) ≤ Work (5,3,2) → Work becomes (7, 4, 3) |
| P4 | (0, 0, 2) | (4, 3, 3) | (4, 3, 1) | 3rd: Need (4,3,1) ≤ Work (7,4,3) → Work becomes (7, 4, 5) |
Because every process completes in the order , the system is in a safe state. If now requests , since and , we tentatively update Available = (2, 3, 0), Allocation[1] = (3, 0, 2), and Need[1] = (0, 2, 0); running the safety check again yields the valid safe sequence , so the request is granted immediately.
8.4 Deadlock Detection and Recovery
When neither prevention nor avoidance is used, the OS runs a periodic detection algorithm (wait-for graph cycle detection for single-instance resources, or a Banker-like matrix check for multi-instance resources). Once a deadlock is confirmed, recovery proceeds via two routes: (1) Process Termination—either aborting all deadlocked processes at once or aborting one process at a time based on priority/progress until the cycle breaks; or (2) Resource Preemption—selecting a victim process, rolling it back to a safe checkpoint, and reassigning its resources while guarding against repeated starvation of the same victim.
8.5 Classic Synchronization & Scheduling Extensions
Beyond basic single-queue scheduling, modern operating systems implement Multi-Level Queue (MLQ) and Multi-Level Feedback Queue (MLFQ) schedulers. An MLQ scheduler partitions the ready queue into permanently separated classes—for example, system processes, interactive foreground processes, and batch background processes—each with its own scheduling algorithm (such as RR for interactive and FCFS for batch) and fixed inter-queue priority or time-slice shares (e.g., 80% CPU to foreground, 20% to background). An MLFQ improves on static MLQ by allowing processes to migrate dynamically between queues: a new process enters the highest-priority queue with a short quantum; if it consumes its entire quantum (indicating CPU-bound behavior), it is demoted to a lower-priority queue with a longer quantum; if it blocks early for I/O (interactive behavior), it remains at high priority; and periodic aging boosts starved processes back to top queues.
On multi-core Symmetric Multiprocessing (SMP) systems, schedulers must also manage processor affinity and load balancing. Because migrating a running thread from Core 0 to Core 1 invalidates Core 0's warm L1/L2 cache lines, Linux's Completely Fair Scheduler (CFS) and Windows schedulers enforce soft affinity (preferring the last-used core) or hard affinity (pinning threads via sched_setaffinity()), while running periodic push/pull load balancing only when core run-queue lengths diverge significantly.
8.6 Worked Numerical Example: Preemptive Priority & SRTF Scheduling
Consider four processes arriving at different times: , , , . Under Shortest-Remaining-Time-First (SRTF):
- At : only is ready (remaining = 7), so runs from to .
- At : arrives with burst 4 < remaining (5). preempts and runs from to (remaining = 2).
- At : arrives with burst 1 < remaining (2). preempts and finishes at .
- At : arrives with burst 4. Remaining bursts: . runs , then runs , then runs .
Computing Turnaround Time () and Waiting Time (): ; ; ; . The average waiting time is , substantially lower than non-preemptive FCFS () on the exact same arrival workload.
8.7 Hardware Synchronization Primitives and Peterson's Solution
Before semaphores or mutexes can be built in kernel code, the OS must solve mutual exclusion at the lowest level. Peterson's Solution is a classic software-only algorithm for two processes () sharing two variables: int turn and boolean flag[2]. When wishes to enter its critical section, it sets flag[i] = true and politely yields priority via turn = j, spinning in while (flag[j] && turn == j);. Although provably correct under sequential consistency, modern out-of-order CPUs can reorder reads/writes unless memory barriers are inserted. Therefore, real kernels rely on atomic hardware instructions such as test_and_set() (which atomically reads a boolean lock word and sets it to true) and compare_and_swap() (CAS, which atomically updates a memory word only if it matches an expected old value), enabling lock-free counters and kernel spinlocks.
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); /* Check left neighbor */
test((i + 1) % 5); /* Check right neighbor */
}
void test(int i) {
if ((state[(i + 4) % 5] != EATING) &&
(state[i] == HUNGRY) &&
(state[(i + 1) % 5] != EATING)) {
state[i] = EATING;
self[i].signal();
}
}
}8.8 Worked IPC & Synchronization: POSIX Shared Memory and Readers–Writers
In production UNIX systems, high-bandwidth Interprocess Communication relies on POSIX shared memory rather than copying megabytes through pipes. A producer process creates a shared-memory object via shm_open("/os_shm", O_CREAT | O_RDWR, 0666), sets its byte capacity with ftruncate(fd, 4096), and maps it into its virtual address space with mmap(0, 4096, PROT_WRITE, MAP_SHARED, fd, 0). A consumer process opens the same named object, maps it with PROT_READ, and reads directly from RAM without kernel copy overhead. When either process finishes, it unmaps via munmap() and the creator removes the name via shm_unlink().
Because concurrent shared-memory updates require strict coordination, OS textbooks formalize the Readers–Writers Problem. In the First Readers–Writers Problem, no reader is kept waiting unless a writer already holds the shared database; multiple readers execute concurrently while a writer waits, which can starve writers under continuous read traffic. In the Second Readers–Writers Problem, once a writer is ready, no new readers may start, prioritizing write freshness at the risk of reader starvation. Below is the classic semaphore-based First Readers–Writers solution using a read_count protected by mutex and a shared rw_mutex:
semaphore rw_mutex = 1; /* Mutual exclusion for writers */
semaphore mutex = 1; /* Protects read_count updates */
int read_count = 0;
void writer(void) {
wait(rw_mutex);
/* Write to shared dataset exclusively */
signal(rw_mutex);
}
void reader(void) {
wait(mutex);
read_count++;
if (read_count == 1) wait(rw_mutex); /* First reader locks out writers */
signal(mutex);
/* Read shared dataset concurrently with other readers */
wait(mutex);
read_count--;
if (read_count == 0) signal(rw_mutex); /* Last reader releases writers */
signal(mutex);
}8.9 Deadlock Detection Algorithm Trace and Recovery Trade-Offs
To detect deadlocks in a system with multiple instances per resource type, the OS maintains Available[m], Allocation[n][m], and Request[n][m] (representing current pending requests, not future maximums). Initialize Work = Available and Finish[i] = false if Allocation[i] != 0 (else true). Repeatedly find an index such that Finish[i] == false and Request[i] ≤ Work; set Work = Work + Allocation[i] and Finish[i] = true. When no such exists, any process with Finish[i] == false is deadlocked. Running this algorithm costs operations, so kernels invoke it either periodically (e.g., every 10 seconds) or when CPU utilization drops sharply alongside blocked queues. When recovering via process termination or resource preemption, the OS weighs victim selection criteria—process priority, elapsed computation time, resources already held, remaining time to completion, and whether the process is interactive or batch—and tracks rollback counts to prevent the same victim from being starved indefinitely.
int is_safe_state(int n, int m, int avail[], int max[][10], int alloc[][10]) {
int work[10], finish[20], need[20][10], safe_seq[20], count = 0;
for (int j = 0; j < m; j++) work[j] = avail[j];
for (int i = 0; i < n; i++) {
finish[i] = 0;
for (int j = 0; j < m; j++) need[i][j] = max[i][j] - alloc[i][j];
}
while (count < n) {
int found = 0;
for (int i = 0; i < n; i++) {
if (!finish[i]) {
int ok = 1;
for (int j = 0; j < m; j++) {
if (need[i][j] > work[j]) { ok = 0; break; }
}
if (ok) {
for (int j = 0; j < m; j++) work[j] += alloc[i][j];
safe_seq[count++] = i;
finish[i] = 1;
found = 1;
}
}
}
if (!found) return 0; /* System is in an unsafe state */
}
return 1; /* Safe sequence found in safe_seq[0..n-1] */
}8.10 Linux Completely Fair Scheduler (CFS) and Real-Time Priority Classes
Rather than fixed Round-Robin time slices, the Linux kernel's default Completely Fair Scheduler (CFS) models an ideal multitasking processor by tracking each runnable task's virtual runtime (vruntime)—the actual CPU time consumed scaled inversely by the task's nice weight. Runnable tasks are stored in a time-ordered Red-Black Tree keyed by vruntime. Whenever a scheduling decision occurs, CFS simply picks the leftmost node in the Red-Black Tree (the task with the smallest vruntime) in amortized time, guaranteeing smooth interactive responsiveness for I/O-bound tasks without arbitrary starvation.
Module III: Memory Management
Chapter 9: Memory Management Strategies and Contiguous Allocation
9.1 Background, Address Binding, and Logical vs. Physical Addresses
Main memory is a large array of addressable bytes or words shared by the CPU and I/O devices. Before a program can execute, its instructions and data must be brought from disk into main memory. To protect the OS and separate user processes, hardware provides each process with a base register (holding the smallest legal physical memory address) and a limit register (specifying the size of the range). Every memory access generated in user mode is checked by hardware: if an address falls outside , a trap to the OS occurs immediately.
Translating symbolic program addresses into physical RAM locations—known as address binding—occurs at one of three stages: (1) Compile Time (if physical load address is known beforehand, producing absolute code); (2) Load Time (generating relocatable code bound when loaded into RAM); or (3) Execution Time (when processes can move in memory during runtime, requiring hardware support from a Memory-Management Unit (MMU)). An address generated by the CPU is a logical (virtual) address, whereas an address seen by the memory unit is a physical address. Under execution-time binding, the MMU maps logical addresses to physical addresses dynamically.
9.2 Swapping and Contiguous Memory Allocation
Swapping allows the total virtual memory of active processes to exceed physical RAM by moving an entire inactive process (or pages in modern systems) from main memory to a high-speed backing store on disk and bringing it back when scheduled. Because transferring megabytes to and from disk is slow, modern OSes swap individual pages rather than whole processes.
In contiguous memory allocation, each process occupies a single contiguous section of physical memory. Early systems used fixed-sized partitions, which restricted multiprogramming degree and wasted space inside oversized partitions (internal fragmentation). Modern variable-partition schemes maintain a list of free memory blocks (holes) and allocate space using one of three dynamic strategies:
- First Fit: Allocates the first hole in the list that is large enough. Fast, as searching stops immediately upon finding a match.
- Best Fit: Searches the entire list (unless ordered by size) to allocate the smallest hole that is large enough, leaving the smallest leftover hole.
- Worst Fit: Allocates the largest available hole, attempting to leave a leftover hole large enough to remain useful for future requests.
First Fit and Best Fit consistently outperform Worst Fit in both speed and storage utilization. However, all contiguous variable-partition schemes suffer from external fragmentation: enough total free memory exists to satisfy a request, but it is shattered into non-contiguous small holes. Compaction resolves external fragmentation by shuffling processes together in memory, but it is expensive and only possible under execution-time relocation.
Chapter 10: Paging and Segmentation
10.1 Paging Architecture and Translation Lookaside Buffer (TLB)
Paging eliminates external fragmentation and the need for contiguous physical allocation by breaking physical memory into fixed-sized blocks called frames and breaking logical memory into blocks of identical size called pages (typically 4 KB to 2 MB, always a power of 2). When a process executes, its pages are loaded into any available physical frames. The MMU translates every logical address—partitioned into a page number () and a page offset ()—by using as an index into a per-process page table to retrieve the corresponding physical frame number (), then concatenating with .
Because storing the page table in main memory would require two memory accesses per instruction (one for the page-table entry, one for the actual datum), CPUs include a fast associative hardware cache called the Translation Lookaside Buffer (TLB). On a TLB hit, the frame number is obtained in nanoseconds and only one main-memory access () is needed. On a TLB miss, the MMU reads the page table in RAM () and then accesses the target datum (). For example, if , , and , then —a mere 4% slowdown compared to direct physical access.
10.2 Page Table Structures and Segmentation
Modern 64-bit address spaces make flat single-level page tables impossibly large. Systems therefore employ hierarchical (multi-level) paging (paging the page table itself so unused regions occupy no RAM), hashed page tables (mapping sparse 64-bit virtual page numbers via hash buckets), or inverted page tables (maintaining exactly one entry per physical RAM frame rather than per virtual page, saving massive memory at the cost of search time).
Segmentation is a memory-management scheme supporting the programmer's logical view of a program as a collection of variable-sized logical units (main program, functions, stack, symbol table, arrays). Each logical address is a two-tuple <segment-number, offset>. A hardware segment table stores each segment's physical base address and limit (length). If the offset is less than the limit, it is added to the base; otherwise, an addressing-error trap fires. While segmentation simplifies sharing and protection of logical modules, variable-sized segments reintroduce external fragmentation—leading architectures like x86 to combine segmentation with paging.
| Feature | Paging | Segmentation |
|---|---|---|
| Division Unit | Fixed-size physical frames and logical pages (hardware-driven). | Variable-size logical segments (programmer/compiler-driven). |
| Address Format | Linear integer partitioned by hardware into . | Explicit two-dimensional tuple . |
| Fragmentation | Zero external fragmentation; minor internal fragmentation on last page. | Zero internal fragmentation; suffers from external fragmentation. |
| Protection & Sharing | Per-page valid/read/write/execute bits; may span logical boundaries. | Naturally aligns protection and code sharing with logical functions/data. |
Chapter 11: Virtual Memory, Demand Paging, and Thrashing
11.1 Virtual Memory and Demand Paging
Virtual memory separates the user's logical memory view from physical memory, enabling execution of programs that are only partially loaded in RAM. Programs often contain error-handling routines, rarely used options, and oversized arrays that are seldom touched during normal execution. By keeping only active portions in RAM, virtual memory allows logical address spaces to vastly exceed physical RAM, increases the degree of multiprogramming, and minimizes I/O needed to load programs.
Virtual memory is commonly implemented via demand paging: pages are loaded into physical frames only when they are demanded during execution. Each page-table entry carries a valid-invalid bit. When a process attempts to access a page marked invalid (not currently in RAM), the hardware triggers a page-fault trap. The OS handles the page fault in six steps: (1) check an internal table to verify whether the reference is valid or an illegal access; (2) if valid, locate a free physical frame; (3) schedule a disk read to load the desired page into the free frame; (4) update the page table and set the valid bit; (5) restart the instruction that caused the trap. Under Copy-on-Write (COW), parent and child processes created via fork() initially share identical read-only physical frames; the OS duplicates a page only if one process attempts to write to it.
11.2 Frame Allocation and Thrashing
When multiple processes run concurrently, the OS must allocate physical frames among them using equal allocation, proportional allocation (scaled to virtual process size), or priority-weighted allocation, applying either global replacement (a process can steal a frame from another process) or local replacement (a process selects victims only from its own allocated frames).
If a process does not hold enough physical frames to cover its actively used pages—its working set—it immediately page-faults, replaces an active page, and faults again on the replaced page. This high-paging activity where a system spends more time swapping pages than executing instructions is called thrashing. As CPU utilization drops during thrashing, naive schedulers may admit even more processes, compounding the collapse. Operating systems prevent thrashing using the Working-Set Model (allocating frames equal to the sum of active working-set sizes , suspending a process if total demand available frames) or Page-Fault Frequency (PFF) control (granting frames when fault rate exceeds an upper threshold and reclaiming frames when it drops below a lower threshold).
Chapter 12: Page Replacement Algorithms and Worked Traces
12.1 Basic Page Replacement Mechanism
When a page fault occurs and no free physical frame exists, the OS must select a victim frame to evict. To reduce unnecessary disk I/O, each frame's page-table entry includes a hardware modify (dirty) bit: if the page was never modified since being loaded, it need not be written back to swap space; only dirty pages are written back before loading the new page. The goal of a page-replacement algorithm is to minimize the total number of page faults across a given memory reference string.
12.2 FIFO, Optimal, and LRU Algorithms
- First-In, First-Out (FIFO): Tracks the arrival order of pages in a queue and always evicts the oldest page in memory. Simple to implement, but performs poorly when heavily used pages happen to be oldest. Counterintuitively, FIFO suffers from Belady's Anomaly: for certain reference strings, giving a process more physical frames can actually increase the number of page faults.
- Optimal Page Replacement (OPT / MIN): Evicts 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 fixed frame count and never suffers from Belady's Anomaly, but cannot be implemented in a real OS because future memory references are unknown; it serves as a theoretical benchmark.
- Least Recently Used (LRU): Approximates OPT by looking backward instead of forward: it evicts the page that has not been used for the longest time in the past. LRU is a stack algorithm and never exhibits Belady's Anomaly. Because updating timestamps or a linked stack on every memory reference is expensive in software, real hardware approximates LRU using a reference bit (Clock / Second-Chance algorithm).
12.3 Worked Numerical Trace: FIFO vs. LRU vs. Optimal
Consider the 12-access page reference string: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3 with 3 physical frames (initially empty). An asterisk (*) marks a page fault.
| Ref | FIFO (3 Frames) | Optimal (3 Frames) | LRU (3 Frames) |
|---|---|---|---|
| 7 | [7, -, -] * | [7, -, -] * | [7, -, -] * |
| 0 | [7, 0, -] * | [7, 0, -] * | [7, 0, -] * |
| 1 | [7, 0, 1] * | [7, 0, 1] * | [7, 0, 1] * |
| 2 | [2, 0, 1] * (evicts 7) | [2, 0, 1] * (evicts 7) | [2, 0, 1] * (evicts 7) |
| 0 | [2, 0, 1] (hit) | [2, 0, 1] (hit) | [2, 0, 1] (hit) |
| 3 | [2, 3, 1] * (evicts 0) | [2, 0, 3] * (evicts 1) | [2, 0, 3] * (evicts 1) |
| 0 | [2, 3, 0] * (evicts 1) | [2, 0, 3] (hit) | [2, 0, 3] (hit) |
| 4 | [4, 3, 0] * (evicts 2) | [2, 4, 3] * (evicts 0) | [4, 0, 3] * (evicts 2) |
| 2 | [4, 2, 0] * (evicts 3) | [2, 4, 3] (hit) | [4, 0, 2] * (evicts 3) |
| 3 | [4, 2, 3] * (evicts 0) | [2, 0, 3] * (evicts 4) | [4, 3, 2] * (evicts 0) |
| 0 | [0, 2, 3] * (evicts 4) | [2, 0, 3] (hit) | [0, 3, 2] * (evicts 4) |
| 3 | [0, 2, 3] (hit) | [2, 0, 3] (hit) | [0, 3, 2] (hit) |
Summary of Page Faults: FIFO incurs 10 page faults (hit rate 16.7%), LRU incurs 9 page faults (hit rate 25.0%), and Optimal incurs only 7 page faults (hit rate 41.7%), demonstrating why temporal locality heuristics outperform pure age-based eviction.
12.4 Belady's Anomaly, Second-Chance (Clock), and Kernel Memory Allocation
Intuitively, allocating more physical frames to a process should never increase its page faults. Yet under FIFO, certain reference strings violate this monotonicity—a phenomenon called Belady's Anomaly. Consider the reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5: with 3 frames, FIFO incurs 9 page faults; with 4 frames, FIFO incurs 10 page faults! By contrast, stack algorithms such as LRU and Optimal satisfy the inclusion property (the set of pages in frames is always a subset of the pages in frames), guaranteeing they never suffer from Belady's Anomaly.
Because exact LRU requires hardware counters or doubly linked list updates on every single memory reference, production kernels use LRU-Approximation algorithms built around a single hardware reference bit per page-table entry (set to 1 by the MMU whenever the page is accessed). In the Second-Chance (Clock) Algorithm, frames are arranged in a circular buffer with a clock hand pointer. When a page must be evicted, the OS inspects the page under the hand: if its reference bit is 0, it is evicted immediately; if its reference bit is 1, the OS clears the bit to 0, advances the clock hand, and gives the page a "second chance." An Enhanced Second-Chance algorithm examines both the (reference, modify) bit pair in four priority classes: (0,0) best victim (not recently used, clean); (0,1) not recently used, dirty (requires disk write); (1,0) recently used, clean; (1,1) worst victim.
Inside the kernel itself, dynamic memory requests (such as 28-byte file descriptors, 128-byte semaphores, or 1.7-KB PCBs) are often much smaller than a 4 KB page. Using full pages for small kernel objects would cause massive internal fragmentation. Operating systems therefore deploy two specialized kernel allocators above the page frame allocator:
- Buddy System Allocator: Allocates memory from a fixed-size segment consisting of physically contiguous pages in power-of-2 chunks (e.g., 4 KB, 8 KB, 16 KB, 32 KB). If a 21 KB request arrives, a 32 KB block is split into two 16 KB "buddies," one of which is allocated (with 11 KB internal fragmentation); when adjacent buddies are freed, they coalesce back into a single larger block in time.
- Slab Allocator: Used in Linux and Solaris, a slab consists of one or more physically contiguous pages partitioned into pre-initialized object caches for specific kernel data structures (e.g., an
inode_cacheortask_struct_cache). Allocation is instantaneous with zero internal fragmentation, and freed objects return to the cache in an already-initialized state.
12.5 Worked Numerical: Contiguous Partitioning & Multi-Level Paging
1. Contiguous Allocation Strategies: Suppose memory holes of sizes 100 KB, 500 KB, 200 KB, 300 KB, 600 KB (in order) are available, and four processes request 212 KB, 417 KB, 112 KB, 426 KB in sequence:
- First Fit: 212 KB → 500 KB hole (leaves 288 KB); 417 KB → 600 KB hole (leaves 183 KB); 112 KB → 288 KB hole (leaves 176 KB); 426 KB must wait (largest remaining hole is 300 KB).
- Best Fit: 212 KB → 300 KB hole (leaves 88 KB); 417 KB → 500 KB hole (leaves 83 KB); 112 KB → 200 KB hole (leaves 88 KB); 426 KB → 600 KB hole (leaves 174 KB). Best Fit satisfies all four processes!
- Worst Fit: 212 KB → 600 KB hole (leaves 388 KB); 417 KB → 500 KB hole (leaves 83 KB); 112 KB → 388 KB hole (leaves 276 KB); 426 KB must wait.
2. Two-Level Paging Bit-Splitting: Consider a 32-bit logical address space with a 4 KB ( byte) page size and 4-byte page-table entries. A single-level page table has entries ( per process). Paging the page table itself places entries in each inner page-table page, splitting the 32-bit address into: 10-bit outer page number () + 10-bit inner page number () + 12-bit offset (). Only the 4 KB outer directory and actively used inner tables need reside in RAM.
int lru_page_faults(int pages[], int n, int capacity) {
int frames[16], last_used[16], faults = 0, time = 0;
for (int i = 0; i < capacity; i++) { frames[i] = -1; last_used[i] = -1; }
for (int i = 0; i < n; i++) {
int p = pages[i], hit = 0;
time++;
for (int j = 0; j < capacity; j++) {
if (frames[j] == p) { last_used[j] = time; hit = 1; break; }
}
if (!hit) {
int victim = 0;
for (int j = 1; j < capacity; j++) {
if (last_used[j] < last_used[victim]) victim = j;
}
frames[victim] = p;
last_used[victim] = time;
faults++;
}
}
return faults;
}12.6 Virtual Memory Optimization: Memory-Mapped Files and Prepaging
Memory-mapped files (invoked via POSIX mmap()) allow a process to map a disk file directly into its virtual address space, treating file I/O as ordinary memory pointer reads and writes. Rather than copying bytes through kernel buffers on every read() or write() system call, pages are demand-paged on access and flushed back to disk asynchronously, enabling multiple processes to share read-only code libraries (such as libc.so) or shared-memory IPC regions effortlessly. Complementing demand paging, prepaging reduces the initial burst of cold-start page faults by predicting and loading a process's previous working set simultaneously when a swapped-out process is resumed.
12.7 Dynamic Loading, Dynamic Linking, and Shared Libraries
To keep memory footprints small before virtual memory or even alongside paging, operating systems separate when routines are loaded and linked:
- Dynamic Loading: A routine is not loaded into memory until it is actually called. All routines reside on disk in a relocatable load format; the main program loads a routine dynamically only when invoked (e.g., rare error-handling or help modules), saving RAM without OS kernel intervention.
- Static vs. Dynamic Linking: Under static linking, system library routines (such as
printfinlibc.a) are copied directly into every executable binary, wasting disk and RAM when hundreds of processes run simultaneously. Under dynamic linking, a small stub is placed in the binary for each library reference; at runtime, the OS dynamic linker (ld-linux.soor Windowsntdll.dll) maps a single shared copy of the library (.soor.dll) into the virtual address spaces of all processes, enabling transparent security patching of libraries without recompiling applications.
12.8 Inverted Page Tables, Hashed Page Tables, and TLB Reach
In 64-bit architectures, even a 3-level or 4-level hierarchical page table consumes noticeable memory when address spaces are sparse. Two alternative hardware/OS structures address this scale:
- Hashed Page Tables: The virtual page number is hashed into a hash table whose buckets contain linked lists of elements comparing
(virtual page number, mapped frame number, next pointer). In 64-bit systems, clustered page tables store mappings for 16 consecutive virtual pages per hash entry, slashing pointer overhead. - Inverted Page Tables: Instead of maintaining one page table per process (which scales with virtual address space), the system maintains a single global table with exactly one entry per physical RAM frame, storing
<process-id, page-number>. Memory overhead is fixed by physical RAM size regardless of active process count, though lookup requires hashing (plus a TLB) because entries are indexed by physical frame rather than virtual page.
Hardware designers also track TLB Reach—the total amount of memory accessible from the TLB at once, given by . With 64 TLB entries and 4 KB pages, TLB reach is only 256 KB; workloads manipulating gigabyte databases or neural-network tensors suffer frequent TLB misses. Modern CPUs and OSes therefore support Huge Pages (e.g., 2 MB or 1 GB pages on x86-64 Linux), expanding TLB reach by 512× without enlarging expensive associative TLB silicon.
12.9 Worked Numerical: Belady's Anomaly & Page-Fault Rate Impact
1. Belady's Anomaly Trace: On reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 under FIFO:
- With 3 Frames:
1* [1],2* [1,2],3* [1,2,3],4* [2,3,4],1* [3,4,1],2* [4,1,2],5* [1,2,5],1 (hit),2 (hit),3* [2,5,3],4* [5,3,4],5 (hit)→ 9 page faults. - With 4 Frames:
1* [1],2* [1,2],3* [1,2,3],4* [1,2,3,4],1 (hit),2 (hit),5* [2,3,4,5],1* [3,4,5,1],2* [4,5,1,2],3* [5,1,2,3],4* [1,2,3,4],5* [2,3,4,5]→ 10 page faults!
2. Effective Access Time with Page Faults: Suppose main-memory access time is and average page-fault service time (including swap I/O) is . To keep performance degradation below 10% (), we solve , giving —meaning fewer than 1 memory access in 400,000 may trigger a page fault.
12.10 Summary Comparison of Page Replacement Policies
| Algorithm | Eviction Criterion | Belady's Anomaly? | Implementation Overhead |
|---|---|---|---|
| FIFO | Oldest loaded page in physical memory queue. | Yes | Minimal: single FIFO pointer or circular index. |
| Optimal (OPT) | Page unused for longest future duration. | No | Impossible in practice (requires future knowledge); theoretical benchmark. |
| LRU | Page unused for longest past duration. | No | High in software (stack/timestamps); approximated in hardware. |
| Clock (Second-Chance) | Circular scan clearing hardware reference bit from 1 to 0. | No | Low: 1 reference bit per PTE + single circular clock hand. |
| LFU / MFU | Least-frequently or most-frequently referenced counter. | Varies | Moderate: requires periodic counter decay to avoid stale counts. |
12.11 Virtual Memory in Production Operating Systems (Windows & Linux)
Real-world operating systems adapt textbook demand paging and replacement policies to handle multi-gigabyte workloads efficiently:
- Linux Page Replacement (Two-List LRU / Active–Inactive Lists): Because strict LRU is too expensive on every memory read, Linux maintains two doubly linked lists per memory zone: an Active List (hot pages) and an Inactive List (eviction candidates). Newly faulted pages enter the Inactive List; a second access promotes them to the Active List. A background kernel daemon (
kswapd) scans the tail of the Inactive List, writing dirty pages to swap and reclaiming clean frames when free RAM drops below a low watermark. - Windows Working-Set Trimming: Windows manages virtual memory using a local working-set model with dynamic trimming. Each process starts with a minimum and maximum working-set size. When free physical memory becomes plentiful, the OS lets processes expand their working sets; when free memory drops below a threshold, the Balance Set Manager trims older pages from processes exceeding their minimum working-set bounds using a Clock-based aging sweep.
- Out-of-Memory (OOM) Killer: When physical RAM and swap space are completely exhausted and no further pages can be reclaimed, Linux invokes the OOM Killer, which scores every running process using a heuristic (
oom_score) proportional to its RSS memory footprint and inversely scaled by system-critical priority, terminating the highest-scoring non-essential process to restore kernel stability.
12.12 Memory Protection Keys, ASLR, and Copy-on-Write Deep Dive
Modern MMUs do more than translate virtual addresses to physical frames; every Page Table Entry (PTE) enforces hardware-level access control via Read (R), Write (W), Execute-Disable (NX/XD), and User/Supervisor (U/S) permission bits. Setting the NX bit on stack and heap pages prevents attackers from executing injected shellcode stored in data buffers, while marking text segments read-only prevents accidental self-modification and enables safe code sharing across processes.
To defeat predictable memory-layout exploits such as Return-Oriented Programming (ROP), modern OS loaders enable Address Space Layout Randomization (ASLR), randomizing the base virtual addresses of the stack, heap, shared libraries, and position-independent executables on every process launch. Meanwhile, when a parent process spawns a child via fork(), the kernel avoids copying gigabytes of RAM by marking all shared writable PTEs as read-only with a Copy-on-Write (COW) flag. As long as both processes only read data, they share identical physical frames; the instant either process attempts a write, the MMU triggers a protection fault, and the kernel allocates a fresh private frame, copies the single 4 KB page, and marks both copies writable.
#include <stdint.h>
#include <stdio.h>
#define PAGE_SHIFT 12 /* 4 KB pages (2^12 bytes) */
#define OFFSET_MASK 0xFFF /* Low 12 bits */
uint32_t translate_address(uint32_t logical_addr, const uint32_t page_table[], uint32_t num_pages) {
uint32_t page_num = logical_addr >> PAGE_SHIFT;
uint32_t offset = logical_addr & OFFSET_MASK;
if (page_num >= num_pages || !(page_table[page_num] & 0x80000000U)) {
printf("Page Fault / Invalid Access at logical 0x%08X\n", logical_addr);
return 0;
}
uint32_t frame_num = page_table[page_num] & 0x000FFFFFU;
return (frame_num << PAGE_SHIFT) | offset;
}12.13 Thrashing Prevention: Working-Set Window Worked Example
Suppose a process executes with working-set window size memory references over the reference trace 2, 6, 1, 5, 7, 7, 7, 7, 5, 1, 6, 2, 3, 4, 1, 2, 3, 4, 4, 4. At (after the first 10 references 2,6,1,5,7,7,7,7,5,1), the distinct pages referenced in the window are , giving working-set size frames. At (the last 10 references 6,2,3,4,1,2,3,4,4,4), the distinct pages are , again giving frames. If the OS allocates at least 5 frames to this process, page faults remain minimal; if total system demand exceeds available physical frames , the medium-term scheduler suspends the lowest-priority process to eliminate thrashing.
12.14 NUMA-Aware Memory Allocation, Page-Size Trade-Offs, and I/O Interlock
On multi-socket server architectures, physical RAM is distributed across processor sockets using Non-Uniform Memory Access (NUMA): a CPU core accesses RAM attached to its own local socket significantly faster than RAM attached to a remote socket across an interconnect bus. Modern OS memory allocators therefore enforce NUMA-aware first-touch placement, allocating physical frames from the memory node local to the CPU core where the faulting thread runs. In addition, when choosing system page sizes, designers balance a classic trade-off: smaller pages (4 KB) reduce internal fragmentation and improve working-set precision, whereas larger pages (2 MB/1 GB) shrink page-table size, reduce disk seek overhead per page fault, and dramatically boost TLB hit rates.
Finally, virtual memory subsystems must support I/O Interlock (Page Pinning). When a user process initiates an asynchronous DMA disk read into a buffer in its virtual address space, the kernel must temporarily pin (lock) that physical frame in RAM so the page-replacement daemon cannot evict the frame to another process before the DMA controller finishes writing data into it—preventing silent cross-process memory corruption.
12.15 Worked Numerical: Multi-Level Paging Overhead & Copy-on-Write Savings
Suppose a 64-bit virtual address space uses 4 KB ( byte) pages and 8-byte page-table entries, with 48 bits of usable virtual address (standard x86-64). Each page-table page holds entries, requiring 4 levels of page tables ( bits: PML4, PDPT, PD, PT, plus 12-bit offset). If a process allocates only 16 MB of active memory (4,096 pages), a 4-level hierarchy needs just 1 PML4 page + 1 PDPT page + 1 PD page + 8 PT pages = 11 pages (44 KB) of page-table overhead, whereas a flat table would be physically impossible. Similarly, when a 2 GB database server forks a tiny helper utility via exec(), Copy-on-Write avoids copying 524,288 physical pages, duplicating only the few stack pages touched before exec() replaces the address space.
Module IV: Storage Management
Chapter 13: File System Structure, Implementation, and Allocation Methods
13.1 File Concept and File System Structure
To users, the most visible aspect of an operating system is the file system, which provides uniform logical persistence over physical storage media such as HDDs, SSDs, and optical discs. A file is a named collection of related information recorded on secondary storage, characterized by attributes including name, identifier, type, location, size, protection permissions, and timestamps. Operating systems support operations such as create, write, read, reposition (seek), delete, and truncate.
File systems are engineered as a layered architecture to isolate hardware specifics from high-level directory semantics:
- I/O Control Layer: Consists of device drivers and interrupt handlers that transfer blocks between main memory and disk controllers.
- Basic File System: Issues generic commands to the appropriate device driver to read and write physical blocks on the disk (identified by drive and logical block number), while managing memory buffers and disk caches.
- File-Organization Module: Maps logical file blocks to physical disk blocks and manages free-space tracking structures so unused blocks can be allocated to growing files.
- Logical File System: Manages metadata—all file system structures except the actual file contents—including directory structures, ownership, access permissions, and File Control Blocks (FCBs) (termed inodes in UNIX/Linux).
13.2 File System Implementation and Directory Structures
On-disk structures store persistent metadata: a boot control block (first block of a partition, holding OS boot code), a volume control block (superblock in UNIX / Master File Table metadata in NTFS tracking block count, block size, and free-block counts), a directory structure organizing filenames, and per-file FCBs. In-memory structures cache performance-critical state: a mount table, an in-memory directory cache, a system-wide open-file table (holding one entry per open file across the OS), and a per-process open-file table (storing current read/write file offsets and access modes pointing into the system-wide table).
Directory implementations map human-readable filenames to FCBs using either a linear list of <filename, pointer> pairs (simple, but requires slow linear scans on large directories) or a hash table (computes a hash of the filename for average lookup, supplemented by B-trees or B+ trees in modern file systems like NTFS, XFS, and ext4). Free disk blocks are tracked using a bit vector (bitmap) (one bit per block: 1 = free, 0 = allocated), a linked free list (chaining free blocks together without extra metadata overhead), grouping, or counting (storing starting address and contiguous run length).
13.3 File Allocation Methods
How disk blocks are allocated to files directly governs sequential access speed, random-access efficiency, and external fragmentation.
| Allocation Method | Metadata Structure | Sequential & Random Access | Fragmentation & Limitations |
|---|---|---|---|
| Contiguous Allocation | Directory records only starting block address and total length. | Fastest sequential and direct random access (single disk seek). | Severe external fragmentation; difficult to grow files dynamically without relocation. |
| Linked Allocation | Each block holds a pointer to the next block; directory holds start & end pointers. | Good sequential access; poor random access ( pointer-chasing reads). | Zero external fragmentation; pointer overhead per block and vulnerability to a single corrupt pointer. |
| FAT (File Allocation Table) | Linked pointers extracted into a dedicated table at start of volume, cached in RAM. | Fast random access in RAM; minimal disk seeks compared to raw linked allocation. | Table size scales linearly with total disk blocks; requires locking on shared volumes. |
| Indexed Allocation | Dedicated index block holds an array of all data-block pointers for the file. | Direct random access without external fragmentation. | Small files waste an entire index block; huge files require multi-level or combined UNIX inodes. |
In the classic UNIX inode (combined indexed scheme), each inode stores 12 direct block pointers (serving small files instantly without extra index-block reads), 1 single-indirect pointer (pointing to a block of data pointers), 1 double-indirect pointer, and 1 triple-indirect pointer—allowing a single inode to address multi-terabyte files while keeping small-file access ultra-fast.
Chapter 14: Disk Structure and Disk Scheduling Algorithms
14.1 Physical Disk Structure and Access Latency
Modern magnetic Hard Disk Drives (HDDs) consist of stacked circular platters coated with magnetic material rotating at constant angular velocity (5,400 to 15,000 RPM). Data is organized into concentric tracks, divided radially into fixed-size sectors (512 bytes or 4 KB); the set of tracks at the same radial arm position across all platter surfaces forms a cylinder. Total disk access time is dominated by mechanical movement:
Because Seek Time (typically 3–10 ms) dominates total HDD latency, operating systems schedule pending disk I/O requests to minimize total head movement. (By contrast, Solid-State Drives have zero mechanical seek or rotational latency, using flash translation layers and I/O schedulers focused on wear leveling and parallelism.)
14.2 Disk Scheduling Algorithms: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK
- FCFS (First-Come, First-Served): Services requests strictly in arrival order. Fair and starvation-free, but produces wild back-and-forth head swings when requests are scattered.
- SSTF (Shortest-Seek-Time-First): Always selects the pending request closest to the current head position. Substantially reduces total seek distance compared to FCFS, but can starve requests located near the inner or outer edges of the disk.
- SCAN (Elevator Algorithm): The disk arm starts at one end of the disk and sweeps across to the other end (cylinder 0 or max cylinder), servicing every request in its path; upon reaching the boundary, it reverses direction and sweeps back. Prevents starvation, though requests just behind the arm wait a full sweep.
- C-SCAN (Circular SCAN): Sweeps in only one direction (e.g., toward higher cylinders), servicing requests; upon reaching the end, it immediately returns to cylinder 0 without servicing requests on the return trip. Provides much more uniform waiting time across all cylinders 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 the current direction rather than all the way to the physical disk boundary (0 or max cylinder), eliminating wasted boundary travel.
14.3 Worked Numerical Example: Comparing Disk Scheduling Algorithms
Suppose a disk drive has 200 cylinders numbered 0 to 199. The read/write head is currently at cylinder 53 (moving toward higher cylinder numbers), and the pending request queue is: 98, 183, 37, 122, 14, 124, 65, 67. Let us compute the exact total head movement (in cylinders) for each algorithm:
| Algorithm | Service Sequence | Step-by-Step Distance Calculation | Total Head Movement |
|---|---|---|---|
| FCFS | 53 → 98 → 183 → 37 → 122 → 14 → 124 → 65 → 67 | 45 + 85 + 146 + 85 + 108 + 110 + 59 + 2 | 640 cylinders |
| SSTF | 53 → 65 → 67 → 37 → 14 → 98 → 122 → 124 → 183 | 12 + 2 + 30 + 23 + 84 + 24 + 2 + 59 | 236 cylinders |
| SCAN (upward) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 199 → 37 → 14 | (199 − 53) + (199 − 14) = 146 + 185 | 331 cylinders |
| C-SCAN (upward) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 199 → 0 → 14 → 37 | (199 − 53) + 199 + (37 − 0) = 146 + 199 + 37 | 382 cylinders |
| LOOK (upward) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 37 → 14 | (183 − 53) + (183 − 14) = 130 + 169 | 299 cylinders |
| C-LOOK (upward) | 53 → 65 → 67 → 98 → 122 → 124 → 183 → 14 → 37 | (183 − 53) + (183 − 14) + (37 − 14) = 130 + 169 + 23 | 322 cylinders |
Notice that SSTF achieves the lowest movement (236 cylinders) here, while LOOK (299) and C-LOOK (322) save 32 and 60 cylinders respectively compared to SCAN and C-SCAN by reversing at cylinder 183 and 14 instead of traversing empty boundary cylinders 199 and 0.
14.4 File Access Methods, Directory Graphs, and Virtual File System (VFS)
Files store structured or unstructured byte streams and are accessed using three primary methods: (1) Sequential Access—records are processed in order from start to end using a current file-position pointer (standard for compilers, log processors, and streaming media); (2) Direct (Relative) Access—blocks are read or written in arbitrary order via block number , essential for relational databases and B-tree indexes; and (3) Indexed Access—an auxiliary index file stores keys paired with direct block pointers so large datasets can be searched via binary search in before fetching the target data block.
Similarly, directory hierarchies evolved from flat Single-Level Directories (causing filename collisions across users) and Two-Level Directories (one master folder per user) to modern Tree-Structured Directories (supporting absolute paths like /home/bca/os.pdf and relative paths). To allow two users to share a common file or subdirectory without duplicating data, OSes support Acyclic-Graph Directories using hard links (multiple directory entries pointing directly to the same inode, tracked by a link counter) and symbolic (soft) links (a small special file containing the target's pathname). Care must be taken to prevent infinite directory-traversal loops when general-graph cycles are permitted.
To support diverse on-disk and network file systems (ext4, XFS, FAT32, NTFS, NFS) behind a single uniform API (open(), read(), write()), UNIX and Linux kernels insert a Virtual File System (VFS) layer. VFS defines four standard object interfaces—superblock (mounted volume), inode (file metadata), dentry (directory entry cache), and file (open file handle)—allowing new file systems to plug into the kernel cleanly. Furthermore, modern file systems protect metadata integrity against sudden power loss using Journaling (Write-Ahead Logging): before modifying scattered directory and inode blocks, the OS writes an intention record to a sequential circular journal; after a crash, the OS replays committed journal entries in seconds rather than scanning the entire multi-terabyte disk with fsck.
14.5 RAID Architectures, SSD Management, and Swap-Space
Because single disk drives have finite throughput and eventual mechanical failure, enterprise storage systems combine multiple physical drives into a Redundant Array of Independent Disks (RAID) to boost performance via parallel striping and improve reliability via mirroring or parity:
| RAID Level | Mechanism | Min Disks | Fault Tolerance & Storage Efficiency |
|---|---|---|---|
| RAID 0 | Block-level striping across disks with zero redundancy. | 2 | Zero fault tolerance (100% capacity); maximum raw read/write throughput. |
| RAID 1 | Full mirroring: every block written identically to two drives. | 2 | Survives 1 disk failure (50% capacity); fast parallel reads. |
| RAID 5 | Block-level striping with distributed XOR parity rotated across all drives. | 3 | Survives 1 disk failure ( capacity); eliminates single parity-disk bottleneck. |
| RAID 6 | Block-level striping with dual independent distributed parity (P + Q). | 4 | Survives any 2 simultaneous disk failures ( capacity). |
| RAID 10 (1+0) | Striped array of mirrored pairs (combines RAID 1 + RAID 0). | 4 | Survives multiple failures if not in the same mirror pair (50% capacity); high random I/O speed. |
For Solid-State Drives (SSDs) built from NAND flash memory, data can be read and written at page granularity (4–16 KB) but can only be erased in much larger blocks (512 KB–4 MB), and each cell endures a finite number of program/erase (P/E) cycles. An internal microcontroller running the Flash Translation Layer (FTL) maps logical block addresses to physical flash pages, performs wear leveling to distribute writes evenly across all blocks, and executes background garbage collection to reclaim invalidated pages. Operating systems also manage swap space—either as a raw dedicated disk partition (faster, bypassing file-system overhead) or as a dynamically resized swap file—and perform low-level formatting (writing sector headers/trailers with ECC) followed by logical formatting (creating the initial superblock, root directory, and free-space bitmap) while remapping defective bad blocks to spare sectors.
14.6 Worked Numerical: Free-Space Bitmap Size & UNIX Inode Max File Size
1. Free-Space Bitmap Calculation: Consider a 1 TB ( bytes) disk using a 4 KB ( bytes) block size. The total number of blocks is blocks. Since a bitmap uses 1 bit per block, the bitmap requires bits = bytes = 32 MB (less than 0.003% of total disk capacity).
2. UNIX Inode Maximum File Size: Suppose a 4 KB block holds 4-byte block pointers. With 12 direct pointers, 1 single-indirect, 1 double-indirect, and 1 triple-indirect pointer, the maximum number of addressable data blocks is: blocks, which at 4 KB per block yields a maximum file size exceeding 4 Terabytes.
#include <stdlib.h>
int cmp_int(const void *a, const void *b) {
return (*(const int *)a - *(const int *)b);
}
int scan_disk_movement(int req[], int n, int head, int max_cyl, int moving_up) {
qsort(req, n, sizeof(int), cmp_int);
int total = 0;
if (moving_up) {
/* Sweep up to max_cyl, then reverse to lowest request */
total += (max_cyl - head);
if (req[0] < head) total += (max_cyl - req[0]);
} else {
/* Sweep down to 0, then reverse to highest request */
total += head;
if (req[n - 1] > head) total += req[n - 1];
}
return total;
}14.7 File System Mounting, File Sharing, and Protection
Just as a file must be opened before it can be read, a file system must be mounted before it becomes accessible to processes on the system. The OS is given the device name (e.g., /dev/nvme0n1p2) and a mount point—an existing empty directory in the root namespace (such as /mnt/data). The kernel verifies that the device contains a valid file-system superblock, records the mount in the in-memory mount table, and splices the remote or secondary volume's root directory onto the mount point.
When multiple users collaborate on a multi-user system, the OS enforces file protection against improper access across six core operations: read, write, execute, append, delete, and list. Two complementary models implement access control:
- Access Control Lists (ACLs): Each file stores an explicit list of user identities and allowed operations. ACLs offer fine-grained per-user flexibility, though variable-length lists complicate directory entry sizing.
- Condensed UNIX Permission Bits: Classifies users into three buckets—Owner (u), Group (g), and Others (o)—assigning 3 bits (Read=4, Write=2, Execute=1) to each class (e.g.,
0750grants fullrwxto Owner,r-xto Group, and zero access to Others). Modern POSIX file systems combine both by supporting extended ACLs atop base 9-bit mode masks.
14.8 Free-Space Management Techniques and Efficiency
Because disk space is finite, the OS tracks unallocated blocks using a free-space list implemented via four principal structures:
- Bit Vector (Bitmap): Each block is represented by 1 bit (1 = free, 0 = allocated). Finding the first free block or contiguous free blocks is hardware-accelerated via CPU bit-scan instructions (
BSF/TZCNT), though the entire bitmap should ideally stay cached in RAM for speed. - Linked List: Links all free disk blocks together, storing the address of the first free block in a special superblock field and placing a pointer to the next free block inside each free block. Zero extra disk space is consumed, but traversing the list requires slow disk I/O unless blocks are cached.
- Grouping: Stores the addresses of free blocks inside the first free block; the first addresses point to actual free blocks, while the -th address points to another block holding the next addresses—allowing rapid bulk allocation.
- Counting: Exploits the fact that several contiguous blocks are often allocated or freed simultaneously by storing pairs
(first_free_block_address, contiguous_count), dramatically shrinking list size on extent-based file systems like ext4 and XFS.
14.9 Performance Tuning: Disk Caching, I/O Elevators, and NVMe Queues
Modern kernels combine multiple software optimizations above the physical disk scheduler. A unified Page Cache / Buffer Cache keeps recently accessed disk blocks in spare physical RAM so repeated reads complete in nanoseconds rather than milliseconds, using read-ahead (prefetching) to load sequential blocks before the application requests them. Write operations are buffered in RAM and flushed asynchronously by background kernel threads (pdflush/kworker) or forced immediately via fsync() for database ACID durability. While legacy SATA HDDs relied on Linux's single-queue CFQ/Deadline elevator schedulers to minimize seek arm travel, modern NVMe Solid-State Drives connect directly over PCIe lanes and support up to 64,000 parallel hardware submission/completion queues, prompting kernels to adopt multi-queue block layers (blk-mq) that map I/O queues directly per CPU core to eliminate lock contention.
14.10 Worked Numerical: Rotational Latency, Transfer Time, and C-LOOK Trace
Consider a 7,200 RPM magnetic disk with an average seek time of and a transfer rate of . Let us compute the total time to read a 4 KB () block:
- Average Rotational Latency: One full revolution takes ; average half-rotation delay is .
- Transfer Time: .
- Total Block Access Time: . Notice that mechanical seek and rotational delays account for over 99.6% of total time—explaining why contiguous/extent allocation and disk scheduling are vital for HDDs.
14.11 File System Consistency Checking, Log-Structured File Systems, and Trim
Because file-system metadata updates (creating a file, allocating a data block, updating a directory entry, and clearing a free-space bitmap bit) involve multiple separate disk writes, a sudden power failure mid-operation can leave the volume in an inconsistent state—for instance, a block marked allocated in the bitmap yet belonging to no inode, or an inode referenced by two directories with a link count of 1. Traditional non-journaled file systems (such as UNIX ext2) required running a full-volume consistency checker (fsck) at boot time, scanning every inode and directory block on disk in time.
Modern file systems solve this via two architectures: (1) Journaling File Systems (ext3, ext4, XFS, NTFS), which record metadata transactions in a sequential write-ahead journal before applying them in-place, reducing crash recovery to replaying only the tiny active journal; and (2) Copy-on-Write (CoW) / Log-Structured File Systems (ZFS, Btrfs), which never overwrite live data blocks in place—instead writing modified data and metadata to fresh free blocks and atomically updating a root pointer, enabling instantaneous snapshots and end-to-end checksum verification against silent bit rot.
On Solid-State Drives, deleting a file in the OS traditionally only cleared bits in the file system's free-space bitmap without informing the SSD's internal Flash Translation Layer (FTL), forcing the SSD to preserve and copy deleted garbage pages during background garbage collection (known as write amplification). Modern operating systems therefore issue the TRIM (ATA) or UNMAP (SCSI/NVMe) command whenever blocks are freed, allowing the SSD controller to erase invalidated flash blocks proactively during idle periods and sustain peak write throughput.
14.12 Storage Attachment Models: DAS, NAS, and SAN
| Storage Architecture | Access Granularity | Transport Protocol | Typical Use Case |
|---|---|---|---|
| DAS (Direct-Attached Storage) | Block-level | SATA, SAS, PCIe / NVMe | Local workstation/server internal drives and boot volumes. |
| NAS (Network-Attached Storage) | File-level | TCP/IP over Ethernet (NFS, SMB/CIFS) | Shared team directories, media repositories, home folders. |
| SAN (Storage Area Network) | Block-level | Fibre Channel, iSCSI, NVMe-oF | High-performance enterprise databases and VMware/KVM cluster shared storage. |
14.13 Worked Numerical: File Allocation Overhead & C-SCAN vs. C-LOOK
1. Linked vs. Indexed Allocation Disk Reads: Suppose a file consists of 100 disk blocks, and only the file's directory entry (and FCB/inode) is cached in RAM. To read logical block 50:
- Under Contiguous Allocation: requires 1 disk read (compute
start + 50directly). - Under Linked Allocation: requires 51 disk reads (must sequentially read blocks 0, 1, ..., 49 to follow the embedded next-block pointers before reading block 50).
- Under Single-Level Indexed Allocation: requires 2 disk reads (1 read to fetch the index block into RAM if not cached, plus 1 read for data block 50).
2. RAID 5 Parity Reconstruction: Consider a 4-disk RAID 5 array storing 3 data blocks per stripe () and 1 XOR parity block (). Suppose at a given stripe, , , and , while Disk 2 holding fails. The RAID controller reconstructs instantaneously in hardware without downtime using bitwise XOR: .
#include <stdlib.h>
#include <limits.h>
int sstf_disk_movement(int req[], int n, int head) {
int visited[128] = {0};
int total = 0, curr = head;
for (int step = 0; step < n; step++) {
int best_idx = -1, best_dist = INT_MAX;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
int d = abs(req[i] - curr);
if (d < best_dist) { best_dist = d; best_idx = i; }
}
}
visited[best_idx] = 1;
total += best_dist;
curr = req[best_idx];
}
return total;
}14.14 Disk Partitioning (MBR vs. GPT) and Logical Volume Management (LVM)
Before a file system can be formatted on a physical drive, the disk is divided into logical partitions (slices). Legacy PCs used the Master Boot Record (MBR) scheme stored in Sector 0, which limits disks to 2 TB (32-bit LBA) and at most 4 primary partitions. Modern UEFI systems use the GUID Partition Table (GPT), supporting 64-bit block addresses (up to 9.4 ZB), up to 128 standard partitions without extended-partition workarounds, a backup partition table at the end of the disk, and CRC32 integrity checksums.
Above raw partitions, enterprise Linux and UNIX servers deploy a Logical Volume Manager (LVM). LVM aggregates multiple physical disks or partitions into Physical Volumes (PVs), pools them into a unified Volume Group (VG), and carves out flexible Logical Volumes (LVs) that can be dynamically grown, shrunk, or snapshotted online without unmounting active databases or rebooting.
14.15 Comparison of Production File Systems: ext4, XFS, NTFS, and ZFS
| File System | Allocation & Directory Indexing | Crash Recovery & Integrity | Primary Platform & Strengths |
|---|---|---|---|
| ext4 | Extent-based allocation; HTree hashed B-tree directories. | Metadata + optional data journaling (jbd2). |
Default Linux desktop/server; mature, fast, backward-compatible. |
| XFS | B+ tree extent allocation & parallel allocation groups. | Metadata journaling with delayed allocation. | High-throughput Linux enterprise workloads and huge multi-TB files. |
| NTFS | Master File Table (MFT) B-tree; small files embedded inside MFT. | USN Journal + transactional metadata logging. | Windows OS; rich ACL security descriptors, compression, BitLocker. |
| ZFS | Copy-on-Write dynamic variable-block striping. | End-to-end Merkle-tree data/metadata checksums & self-healing. | Storage appliances; atomic snapshots, deduplication, built-in RAID-Z. |
Selecting an appropriate disk scheduling and file-system architecture depends directly on workload I/O patterns. Random transactional databases (OLTP) benefit from direct access, extent-based B+ tree indexing, write-ahead journaling, and NVMe multi-queue parallelism, whereas sequential media-streaming or archival backups prioritize contiguous extents, aggressive read-ahead caching, and elevator-style C-SCAN/C-LOOK request batching to maximize sustained MB/s throughput.
14.16 Backup, Snapshots, and Directory Consistency Recovery
Even with RAID redundancy and journaling file systems, logical user errors (accidental rm -rf), ransomware encryption, or site-wide hardware loss require offline backups. Enterprise storage administrators combine full backups (copying every block on a volume) with incremental backups (copying only blocks modified since the last full or incremental run) or differential backups (copying all blocks changed since the last full backup). Copy-on-Write file systems like ZFS and Btrfs complement backups with instantaneous, space-efficient snapshots that freeze a read-only point-in-time view of the directory tree by retaining existing block pointers while directing new writes to fresh blocks.
When recovering from an unclean shutdown on non-journaled volumes, consistency checkers verify two invariants: every block in the volume must appear either in exactly one file's allocation map or in the free-space bitmap (fixing lost blocks or duplicate-claimed blocks), and every inode's stored link count must match the exact number of directory entries pointing to it (placing orphaned inodes with non-zero link counts into /lost+found).
14.17 Memory-Mapped Files vs. Direct Block I/O and Scatter-Gather DMA
Operating systems offer applications two contrasting I/O paradigms when reading large datasets. Standard Buffered I/O (read()/write()) copies blocks from disk into the kernel page cache and then copies them again into a user-space buffer, whereas Direct I/O (O_DIRECT on Linux) bypasses the kernel page cache entirely—allowing database engines like PostgreSQL or Oracle that manage their own buffer pools to avoid double-caching and CPU copy overhead. Additionally, scatter-gather DMA (readv()/writev()) allows a single system call to transfer non-contiguous memory buffers directly to or from a contiguous disk stream in one hardware operation, maximizing bus efficiency.
14.18 Tertiary Storage, Optical Media, and Tape Archival Systems
Beneath high-speed NVMe SSDs and magnetic HDDs sits tertiary storage, designed for massive, low-cost, long-term archival retention and regulatory compliance. Magnetic tape cartridges (such as LTO-9) offer multi-terabyte capacity per cartridge at a fraction of disk cost per gigabyte, though sequential tape winding imposes access latencies measured in tens of seconds rather than milliseconds. Optical discs (CD-ROM, DVD, Blu-ray) store bits as microscopic pits read by laser optics, providing write-once archival immutability. Operating systems integrate robotic tape libraries and optical jukeboxes through Hierarchical Storage Management (HSM), automatically migrating cold, infrequently accessed files from expensive primary disk tiers down to tertiary tape while leaving transparent stub pointers in the main directory tree.
Module V: Distributed Systems, Real-Time OS & Modern Extensions
Chapter 15: Distributed Operating Systems, Virtualization, and Containers
15.1 Motivation for Distributed Operating Systems
A distributed operating system coordinates a collection of autonomous computer nodes interconnected via a high-speed network so that they appear to users and applications as a single coherent computing system. Four core motivations drive distributed OS adoption: (1) Resource Sharing—allowing users at any node to access expensive printers, specialized GPUs, or enterprise databases hosted elsewhere; (2) Computation Speedup—partitioning large computational problems into sub-tasks executed concurrently across multiple nodes (load sharing and load balancing); (3) Reliability and Fault Tolerance—replicating critical data and services across independent nodes so hardware failure at one site does not halt system operation; and (4) Communication—enabling geographically separated users and services to exchange messages, synchronize workflows, and collaborate seamlessly.
15.2 Types of Distributed Operating Systems and Architectural Models
Distributed systems are categorized along a spectrum of coupling and autonomy:
- Network Operating Systems (NOS): Each node runs its own local OS with autonomous scheduling and memory management, supplemented by network protocols (SSH, SMB, NFS) for remote login and file transfer. Users remain explicitly aware of hostnames and remote boundaries.
- True Distributed Operating Systems: Provide global transparency—a single uniform kernel interface across all nodes where process migration, global IPC, and distributed memory management occur automatically without user intervention.
- Middleware-Based Distributed Systems: Run on top of heterogeneous local OSes (Linux, Windows) using a software layer (such as gRPC, CORBA, or Kubernetes control planes) that provides uniform naming, security, and remote procedure calls (RPC).
- Client–Server vs. Peer-to-Peer (P2P) Models: In Client–Server architectures, dedicated servers provide services (web, database, authentication) to requesting clients. In P2P architectures, all nodes act as symmetric peers capable of both requesting and serving resources without a single central bottleneck.
15.3 Virtualization and OS-Level Containers
Modern cloud-native distributed operating systems rely heavily on virtualization and containerization to multiplex workloads securely across cluster hardware. A Hypervisor (Virtual Machine Monitor) abstracts physical CPU, RAM, and I/O devices into isolated Virtual Machines (VMs), each running a complete guest operating system. Type-1 (bare-metal) hypervisors (e.g., KVM, VMware ESXi, Xen) run directly on host hardware for near-native performance, whereas Type-2 (hosted) hypervisors (e.g., VirtualBox) run atop a host OS.
By contrast, OS-level virtualization (Containers)—exemplified by Docker and Linux LXC—eliminates guest OS kernels entirely. Multiple isolated user-space containers share the single host OS kernel while enforcing strict isolation through two Linux kernel primitives: Namespaces (isolating process trees, network interfaces, mount points, and hostnames per container) and Control Groups (cgroups) (enforcing hard limits on CPU shares, memory, and disk I/O). Consequently, containers start in milliseconds and consume megabytes of RAM rather than gigabytes.
| Dimension | Virtual Machine (Hypervisor) | Container (OS-Level Virtualization) |
|---|---|---|
| Isolation Boundary | Hardware-assisted CPU/MMU virtualization; full separate guest OS kernel per VM. | Kernel namespaces and cgroups sharing a single host OS kernel. |
| Startup Latency & Footprint | Seconds to minutes to boot guest kernel; gigabytes of disk/RAM overhead. | Milliseconds to start; megabytes of layered image footprint. |
| OS Heterogeneity | Can run Windows, Linux, and BSD guests simultaneously on one host. | Must share the host kernel ABI (e.g., Linux containers require a Linux kernel). |
| Security Attack Surface | Strong hypervisor boundary; guest kernel compromise does not directly expose host kernel. | Shared host kernel syscall surface requires seccomp, AppArmor, or SELinux hardening. |
Chapter 16: Distributed File Systems (DFS)
16.1 Naming and Transparency in Distributed File Systems
A Distributed File System (DFS) extends the local file-system abstraction across a network so clients can create, read, and share files stored on remote servers. Designing a DFS centers on two foundational transparency properties:
- Location Transparency: The pathname of a file does not reveal its physical storage server (for example,
/projects/report.pdfrather thanserver4:/disk2/report.pdf). - Location Independence: The pathname of a file does not need to change when the file's physical storage location is migrated from one server or disk volume to another.
DFS naming is typically implemented via three schemes: (1) combining host and local pathnames (violates both location transparency and independence); (2) mounting remote directories onto local directory trees (as in NFS, achieving partial transparency); or (3) maintaining a single global name space (as in AFS or HDFS) where every client sees an identical unified directory hierarchy regardless of physical server placement.
16.2 Remote File Access, Caching, and Stateful vs. Stateless Servers
When a client reads or writes a remote file, a DFS chooses between two remote access strategies: Remote Service (every read() or write() request travels across the network to the server, ensuring consistency but incurring high network latency) and Client-Side Caching (blocks or entire files are cached in client memory or local disk so subsequent accesses run locally). Caching drastically boosts throughput but introduces the cache-consistency problem: if one client modifies a cached block, other clients holding stale copies must be updated or invalidated via write-through policies, delayed-write policies, or server callbacks.
Servers also differ in whether they track client session state:
- Stateful Servers (e.g., NFSv4, SMB): The server maintains open-file tables, current file offsets, and byte-range locks in RAM for each active client. Operations are shorter and locking is native, but server crashes lose volatile state unless complex recovery protocols reconstruct it.
- Stateless Servers (e.g., NFSv3): Each client request must be completely self-contained, specifying the file handle, exact byte offset, and access credentials. If a stateless server crashes and reboots, clients simply retry idempotent requests without complex state-recovery handshakes, at the cost of larger request headers and external lock daemons.
Chapter 17: Real-Time Systems and OS Security Case Studies
17.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 physical time at which results are produced. Real-time systems are divided into two strict classes:
- Hard Real-Time Systems: Missing a deadline constitutes a total system failure—potentially causing physical injury or catastrophic equipment damage (e.g., aircraft flight control, anti-lock braking systems, cardiac pacemakers). Hard real-time systems avoid unbounded delays such as virtual memory demand paging or deep disk queues, keeping critical code and data locked in deterministic RAM.
- Soft Real-Time Systems: Critical tasks receive highest scheduling priority over non-real-time tasks, and deadlines are normally met; occasional deadline misses degrade Quality of Service (QoS) without causing system failure (e.g., live video streaming, VoIP telephony, virtual reality rendering).
17.2 Features of Real-Time Kernels and Scheduling
Conventional desktop kernels optimize average throughput, whereas real-time kernels optimize worst-case determinism and bounded latency:
- Preemptive, Priority-Based Kernel: Kernel routines themselves must be preemptible so a high-priority real-time thread never waits behind a long low-priority system call.
- Minimized Interrupt & Dispatch Latency: Interrupt latency (time from hardware interrupt assertion to ISR start) and dispatch latency (time to stop a running thread and start the highest-priority ready thread) are strictly bounded in microseconds.
- Priority Inheritance Protocol: Prevents priority inversion—a hazard where a high-priority task waits on a lock held by a low-priority task that is itself preempted by medium-priority tasks—by temporarily elevating the lock holder's priority to that of the highest waiting task.
- Deterministic Scheduling Algorithms: Rate-Monotonic (RM) Scheduling assigns fixed priorities inversely proportional to task period (shorter period = higher priority). Earliest-Deadline-First (EDF) Scheduling dynamically assigns highest priority to the task whose absolute deadline is nearest, achieving up to 100% theoretical CPU utilization on uniprocessors (, where is execution time and is period).
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
void configure_realtime_thread(pthread_attr_t *attr, int priority) {
struct sched_param param;
pthread_attr_init(attr);
/* Enforce explicit scheduling attributes rather than inheriting parent */
pthread_attr_setinheritsched(attr, PTHREAD_EXPLICIT_SCHED);
/* Use real-time FIFO preemptive policy */
pthread_attr_setschedpolicy(attr, SCHED_FIFO);
param.sched_priority = priority;
pthread_attr_setschedparam(attr, ¶m);
}17.3 Operating System Security Case Studies: Linux Capabilities and Windows Access Control
Modern operating systems enforce defense-in-depth across user space and kernel space to mitigate privilege escalation, buffer overflows, and container breakouts. Two production security architectures illustrate how OS theory translates into practice:
- Case Study 1 — Linux POSIX Capabilities, SELinux, and Seccomp: Traditional UNIX relied on a binary root/non-root split where any privileged utility (such as
ping) needed full root UID 0 rights. Modern Linux partitions root power into granular POSIX Capabilities (e.g.,CAP_NET_RAW,CAP_SYS_TIME) so processes hold only the minimal privilege required. Layered atop discretionary permissions (rwx), Mandatory Access Control (MAC) frameworks such as SELinux and AppArmor enforce kernel-level security labels restricting even compromised root processes to approved files and sockets, while seccomp-bpf filters individual system calls inside sandboxed containers and browsers. - Case Study 2 — Windows Security Reference Monitor (SRM) and Access Control Lists: Windows kernels centralize authorization in the Security Reference Monitor. Every authenticated user session receives an Access Token containing their Security Identifier (SID), group memberships, and privileges. Every kernel object (file, registry key, process handle) carries a Security Descriptor containing a Discretionary Access Control List (DACL) of explicit Allow/Deny Access Control Entries (ACEs). Combined with User Account Control (UAC) token filtering and Virtualization-Based Security (VBS)—which isolates credential guards inside a hypervisor-protected enclave—modern OS kernels defend against both user-space malware and kernel-level exploits.
17.4 Distributed Transparency Dimensions, Logical Clocks, and Mutual Exclusion
Building a coherent Distributed Operating System requires addressing eight standard transparency dimensions: Access transparency (identical local and remote data access syntax), Location transparency (resources accessed without knowing physical addresses), Migration transparency (resources move without changing names), Relocation transparency (resources move while actively in use), Replication transparency (users unaware of multiple physical copies), Concurrency transparency (multiple users share resources without mutual interference), Failure transparency (faults masked automatically), and Persistence transparency (storage media hidden).
Because physically separate nodes lack a single shared hardware clock, distributed operating systems cannot rely on wall-clock timestamps to order concurrent events. Leslie Lamport introduced Logical Clocks based on the happened-before relation (): each process maintains a monotonically increasing counter , incrementing it before each local event and attaching to every outgoing message; upon receiving a message with timestamp , the receiver updates . Building on logical clocks, Distributed Mutual Exclusion algorithms—such as the Centralized Coordinator, Ricart–Agrawala Distributed Algorithm (broadcasting timestamped requests and collecting OK replies), and Token Ring—coordinate exclusive access to shared distributed resources without shared memory.
17.5 Worked Numerical: Rate-Monotonic & EDF Real-Time Schedulability
Consider two periodic real-time tasks: Task has execution time and period ; Task has execution time and period . Let us test schedulability under both Rate-Monotonic (RM) and Earliest-Deadline-First (EDF) algorithms:
Since , the Liu–Layland sufficient condition guarantees that both tasks are schedulable under Rate-Monotonic Scheduling (assigning higher fixed priority to because ). Notice that if increased to , total utilization would rise to : RM could miss deadlines (as ), whereas EDF remains guaranteed schedulable because . Furthermore, in a real-time kernel, if a low-priority task holds a mutex needed by , the Priority Inheritance Protocol or Priority Ceiling Protocol must elevate the lock holder's priority immediately to prevent unbounded priority inversion.
17.6 Container Architecture, Orchestration, and Security Hardening
In enterprise cloud deployments, containerized microservices run atop Linux hosts coordinated by container orchestrators (such as Kubernetes). Each container runs as a standard Linux user-space process isolated by six core kernel namespaces: pid (process IDs), net (virtual network interfaces and routing tables), mnt (filesystem mount points via OverlayFS union mounts), ipc (System V / POSIX IPC), uts (hostname), and user (mapping container UID 0 to an unprivileged host UID). Because all containers on a host share one kernel, defense-in-depth requires dropping unnecessary POSIX capabilities (--cap-drop=ALL), mounting root filesystems read-only, applying seccomp profiles that block dangerous syscalls (e.g., kexec_load, ptrace), and enforcing SELinux MCS labels so even a compromised container process cannot escape its cgroup and namespace sandbox.
| DFS / Cloud System | Naming & Namespace Model | Server State & Consistency | Primary Target Workload |
|---|---|---|---|
| NFSv3 / NFSv4 | Client-side remote directory mounting into local VFS tree. | v3: Stateless; v4: Stateful with integrated locking & leases. | POSIX LAN file sharing and home directories. |
| AFS (Andrew File System) | Single global uniform namespace (/afs/...) across cells. |
Stateful callbacks; whole-file caching with close-to-open consistency. | Campus-scale distributed academic/enterprise workspaces. |
| HDFS (Hadoop DFS) | Single NameNode metadata namespace; 128 MB blocks on DataNodes. | Write-once, read-many (append-only); 3× block replication. | Batch big-data analytics and MapReduce/Spark pipelines. |
17.7 Remote Procedure Calls (RPC) and Distributed Communication
Unlike single-machine IPC where processes share RAM or local pipes, distributed operating systems rely on Remote Procedure Calls (RPC) to make inter-node communication resemble ordinary local function calls. When a client invokes a remote function, a local client stub packs the function identifier and parameters into a canonical network byte order—a process called marshalling—and transmits the message via UDP or TCP to the target server. On the server side, a server stub unmarshalls the arguments, invokes the actual server procedure, marshalls the return value, and sends it back. Because networks can drop or duplicate packets, RPC runtimes enforce delivery semantics: at-most-once (using unique request timestamps/sequence IDs to discard duplicates) or exactly-once (combining persistent server logs with client acknowledgments).
17.8 Hypervisor Architectures: Full Virtualization, Paravirtualization, and Hardware Assist
Historically, x86 CPUs were difficult to virtualize because several sensitive instructions behaved differently or failed silently in unprivileged ring 3 rather than trapping to the hypervisor (violating the Popek–Goldberg virtualization requirements). Early hypervisors overcame this using two software techniques:
- Binary Translation (Full Virtualization): The hypervisor dynamically scans guest kernel instruction streams at runtime and rewrites unsafe privileged instructions into safe emulation sequences, allowing unmodified guest OSes to run at moderate CPU overhead.
- Paravirtualization: The guest OS kernel source code is explicitly modified to replace non-virtualizable hardware instructions with explicit hypercalls into the hypervisor (pioneered by Xen), delivering near-native speed at the cost of requiring modified guest kernels.
- Hardware-Assisted Virtualization (Intel VT-x / AMD-V): Modern processors introduce dedicated hardware root/non-root execution modes and Extended Page Tables (EPT / Nested Page Tables) inside the MMU, enabling unmodified guest OSes to execute directly on silicon while automatically trapping privileged state changes to the hypervisor with minimal overhead.
17.9 Real-Time Kernel Design: VxWorks, FreeRTOS, and Linux PREEMPT_RT
Real-time kernels span ultra-compact microcontrollers to full-featured embedded Linux workstations:
- FreeRTOS: A deterministic, open-source microkernel (often < 15 KB flash footprint) designed for ARM Cortex-M and RISC-V microcontrollers, providing fixed-priority preemptive scheduling, tickless idle power saving, queues, and priority-inheriting mutexes.
- VxWorks / QNX Neutrino: Commercial hard real-time microkernels certified for aerospace, medical, and automotive safety standards (DO-178C, ISO 26262), isolating device drivers in user-space processes so a driver fault never crashes flight or braking control loops.
- Linux
PREEMPT_RT: Patches the mainline Linux kernel by converting spinlocks into sleeping priority-inheriting mutexes (rt_mutex) and moving hardware interrupt handlers into scheduled kernel threads, enabling bounded microsecond worst-case latency on standard POSIX Linux systems.
17.10 End-to-End OS Security Hardening Checklist for Production Servers
Combining the protection mechanisms from Modules I through V yields a cohesive defense-in-depth posture for modern Linux and cloud-native servers: (1) enforce UEFI Secure Boot with signed kernels and initramfs images to block bootkit rootkits; (2) enable hardware ASLR (Address Space Layout Randomization) and NX/XD (No-Execute) page-table bits to thwart stack/heap code-injection exploits; (3) mount sensitive partitions with noexec,nosuid,nodev flags and encrypt data at rest via kernel dm-crypt/LUKS; (4) confine network-facing daemons inside dedicated cgroups, unprivileged user namespaces, SELinux/AppArmor MAC policies, and restrictive seccomp-bpf syscall allowlists; and (5) stream kernel audit logs (auditd / eBPF telemetry) to an immutable remote collector for tamper-evident forensics.
17.11 Distributed Load Balancing, Process Migration, and Fault Tolerance
A core promise of distributed operating systems is balancing computational load dynamically across cluster nodes. Load-balancing algorithms are classified as static (assigning tasks using fixed round-robin or probabilistic weights without inspecting runtime load) or dynamic (monitoring per-node CPU queue lengths and memory pressure to migrate tasks). Dynamic schemes use either sender-initiated policies (overloaded nodes push tasks to lightly loaded peers) or receiver-initiated policies (idle nodes poll busy peers to pull work). When a running process is moved mid-execution via process migration, the OS must freeze the process, transfer its PCB, registers, open file descriptors, and dirty virtual memory pages (often via iterative pre-copying to minimize downtime), and redirect pending IPC messages to the new host.
Because hardware and network failures are inevitable at cluster scale, distributed operating systems rely on checkpointing and rollback recovery (periodically saving consistent global state snapshots to stable storage) alongside consensus protocols such as Raft and Paxos to elect a single leader and replicate state-machine logs safely across a quorum of nodes even when minority nodes crash or network partitions occur.
17.12 Case Study: Container Isolation Primitives in Linux (Namespaces & Cgroups)
To understand how containers achieve VM-like isolation without a hypervisor, consider launching an isolated web-server container. The container runtime (such as containerd or runc) invokes the Linux clone() system call with namespace flags (CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWUSER), creating a process that believes it is PID 1 on its own private host with its own virtual Ethernet pair (veth) bridged to the host network. Simultaneously, the runtime writes resource caps into the kernel's cgroup v2 virtual filesystem (/sys/fs/cgroup/), enforcing hard ceilings such as memory.max = 512M and cpu.max = 50000 100000 (50% of one CPU core). Finally, pivot_root() switches the container's root directory to an OverlayFS union mount combining read-only image layers with a thin writable container layer, ensuring multiple containers share base OS libraries in RAM while remaining isolated from each other's writes.
# Create a cgroup v2 slice for a containerized microservice mkdir -p /sys/fs/cgroup/web_service echo "536870912" > /sys/fs/cgroup/web_service/memory.max # Hard 512 MB RAM cap echo "50000 100000" > /sys/fs/cgroup/web_service/cpu.max # Cap at 50% of 1 CPU core # Launch an isolated process inside private PID, mount, UTS, and network namespaces unshare --pid --fork --mount-proc --uts --net /bin/sh -c \ "hostname isolated-node && exec /usr/local/bin/app_server"
17.13 Worked Numerical: Lamport Logical Clocks & Real-Time Utilization Bounds
1. Lamport Logical Clock Trace: Suppose three distributed processes start with clocks . executes a local event () and sends message with timestamp 1 to . executes a local event (), receives and updates , then sends with timestamp 2 to . Meanwhile executes two local events () and then receives , updating . Thus , preserving strict causal ordering across nodes without synchronized physical clocks.
2. Priority Inversion Mitigation: Consider three real-time tasks: (high priority), (medium priority), and (low priority). At , acquires mutex . At , preempts and requests , blocking on . At , arrives; without Priority Inheritance, preempts and runs indefinitely, starving . With Priority Inheritance, immediately inherits 's high priority at , preventing from preempting so releases quickly and meets its hard deadline.
17.14 Distributed Mutual Exclusion: Centralized vs. Ricart–Agrawala vs. Token Ring
| Algorithm | Messages per Critical Section | Synchronization Delay | Failure Vulnerability |
|---|---|---|---|
| Centralized Coordinator | 3 messages (Request, Grant, Release). | 2 message times. | Single point of failure if coordinator crashes. |
| Ricart–Agrawala (Distributed) | messages (N-1 Requests + N-1 OKs). | 2 message times. | Any crashed node blocks replies unless timeout/election runs. |
| Token Ring | 1 to (continuous token circulation). | 0 to hops. | Lost token requires ring regeneration; crashed node breaks ring. |
17.15 Microkernel vs. Unikernel vs. Containerized Cloud Architectures
Beyond traditional hypervisors and Docker containers, modern cloud and edge operating systems explore lightweight specialized execution models. Unikernels (such as MirageOS or OSv) compile an application together with only the minimal OS library drivers it actually calls into a single-address-space bootable VM image, eliminating user/kernel mode-switch overhead and shrinking attack surface to near zero. Conversely, microVMs (such as AWS Firecracker) strip legacy BIOS, PCI, and USB emulation from KVM hypervisors so each serverless function boots inside a hardware-virtualized VT-x sandbox in under 125 milliseconds—combining the strong security isolation of VMs with the rapid elasticity of containers.
17.16 Real-Time Interrupt Latency vs. Dispatch Latency Breakdown
In real-time kernels, total responsiveness to an external sensor event is bounded by two sequential intervals. Interrupt Latency is the period from arrival of an interrupt at the CPU until the start of the corresponding Interrupt Service Routine (ISR), determined by how long the kernel disables interrupts while updating critical data structures. Dispatch Latency is the period required by the scheduling dispatcher to stop one process and start another, composed of a conflict phase (preempting any lower-priority process running in kernel mode and releasing resources needed by the high-priority task) and a dispatch phase (performing the actual context switch). By keeping interrupt-disabled regions tiny and making the kernel itself fully preemptible, modern RTOSes guarantee worst-case response latencies in the low tens of microseconds.
17.17 Distributed Consensus, Clock Synchronization, and Edge Real-Time Cloud
Beyond logical Lamport clocks, distributed systems that require physical time ordering (such as financial ledgers or distributed databases like Google Spanner) employ Network Time Protocol (NTP) or GPS/atomic-clock TrueTime bounds to synchronize physical clocks within milliseconds or microseconds across data centers. To agree on a single authoritative state across replicated servers despite node crashes or packet loss, modern distributed operating planes use leader-based consensus protocols such as Raft, which partitions consensus into three clean sub-problems: Leader Election (randomized election timers elect one leader per term), Log Replication (the leader appends client commands and commits once a majority quorum acknowledges), and Safety (preventing stale nodes from overwriting committed entries).
At the convergence of distributed systems, virtualization, and real-time computing, modern industrial 5G edge deployments run real-time control workloads inside deterministic PREEMPT_RT Kubernetes worker nodes, pinning critical sensor-processing pods to isolated CPU cores (cpuset cgroups) with hugepages and SR-IOV network pass-through so distributed cloud orchestration coexists with hard microsecond latency guarantees.
17.18 Fault-Tolerant Distributed File Replication: CAP Theorem & Quorum Reads/Writes
When a Distributed File System replicates data across geographically separated servers, it faces the fundamental trade-off formalized by Eric Brewer's CAP Theorem: during a network partition (P), a distributed storage system must choose between strict Consistency (C) (blocking writes or reads if a node is unreachable so no stale data is ever returned) and high Availability (A) (serving reads/writes from reachable replicas with eventual reconciliation). Systems such as HDFS and Amazon Dynamo-style stores configure Quorum Consensus with replicas, write quorum , and read quorum satisfying and , guaranteeing that every read overlaps with at least one replica holding the latest committed write.
17.19 Distributed Directory Services and Global Authentication (Kerberos & LDAP)
In large distributed operating systems spanning thousands of workstations and file servers, per-machine /etc/passwd files are unmanageable. Enterprises centralize user identities, group memberships, and host mappings in hierarchical Directory Services such as LDAP (Lightweight Directory Access Protocol) or Active Directory. To authenticate users across untrusted networks without transmitting plaintext passwords, distributed OSes employ Kerberos: a trusted Key Distribution Center (KDC) issues time-limited, cryptographically signed Ticket-Granting Tickets (TGTs) and per-service session tickets using symmetric cryptography, enabling single sign-on (SSO) across NFSv4 mounts, SSH hosts, and cloud microservices simultaneously.
17.20 Live VM Migration and Distributed Snapshot Consistency
In enterprise virtualized clusters, administrators perform live VM migration to evacuate running virtual machines from a physical host undergoing hardware maintenance without interrupting active client connections. The source hypervisor copies the VM's memory pages to the destination host iteratively while the VM continues executing (pre-copy phase), tracks dirty pages modified during each round, briefly pauses the vCPU for a few milliseconds once the dirty set becomes tiny (stop-and-copy phase) to transfer CPU registers and final pages, and sends a gratuitous ARP packet so network switches immediately route traffic to the new host. Similarly, distributed monitoring systems capture consistent global state snapshots across independent nodes using the Chandy–Lamport Distributed Snapshot Algorithm, injecting special marker messages along FIFO channels so local state and in-flight channel messages are recorded coherently without halting cluster execution.
17.21 Real-Time Memory Locking and Deterministic I/O Subsystems
In hard real-time operating systems, even a single unexpected page fault or dynamic heap compaction can violate a millisecond control deadline. Therefore, POSIX real-time standards provide mlockall(MCL_CURRENT | MCL_FUTURE) to pin all current and future virtual pages of a critical process permanently into physical RAM, eliminating swap latency. Furthermore, real-time kernels replace unbounded dynamic memory allocators with fixed-block pool allocators (O(1) deterministic allocation time) and utilize memory-mapped Direct Memory Access (DMA) ring buffers for sensor and actuator I/O, ensuring predictable worst-case execution time (WCET) across every control loop iteration.
University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 6 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 Concepts and Techniques (University of Kerala BCA Sem 6)
Operating System Concepts and Techniques (UK6DSCCAP306 • 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 concepts and techniques. 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 Concepts and Techniques 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 a foundational layer of system software that acts as an intermediary between computer hardware and application users. Because bare digital hardware—comprising processor cores, main memory arrays, system buses, and peripheral controllers—exposes only low-level machine instructions and electrical register interfaces, direct hardware programming for every application would be error-prone, non-portable, and insecure.
Process Management
The objective of multiprogramming is to have some process running at all times to maximize CPU utilization, while the objective of time-sharing is to switch the CPU among processes so frequently that users can interact with each program while it is running. To achieve this, the operating system maintains several scheduling queues. When a process enters the system, it is placed in the job queue (or admitted directly into memory).
Memory Management
Main memory is a large array of addressable bytes or words shared by the CPU and I/O devices. Before a program can execute, its instructions and data must be brought from disk into main memory. To protect the OS and separate user processes, hardware provides each process with a base register (holding the smallest legal physical memory address) and a limit register (specifying the size of the range). Every memory access generated in user mode is checked by hardware: if an address falls outside [ base, base + limit ), a trap to the OS occurs immediately.
Storage Management
To users, the most visible aspect of an operating system is the file system, which provides uniform logical persistence over physical storage media such as HDDs, SSDs, and optical discs. A file is a named collection of related information recorded on secondary storage, characterized by attributes including name, identifier, type, location, size, protection permissions, and timestamps. Operating systems support operations such as create, write, read, reposition (seek), delete, and truncate.
Distributed Systems, Real-Time OS & Modern Extensions
A distributed operating system coordinates a collection of autonomous computer nodes interconnected via a high-speed network so that they appear to users and applications as a single coherent computing system.
Core Curriculum & Key Topics
- What Operating Systems Do and Computer System Organization
- 1 Definition and Dual Role of an Operating System
- 2 Computer System Organization and Interrupt-Driven Execution
- 3 Storage Hierarchy and Computer System Architecture
- Operating System Structure and Distributed Systems
- 1 Operating System Operations: Dual-Mode Execution and Timers
- 2 Operating System Architectural Structures
- 3 Distributed Systems Overview
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of operating system concepts and techniques.
- 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 Concepts and Techniques
The evaluation framework for Operating System Concepts and Techniques (UK6DSCCAP306) 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 UK6DSCCAP306 (Operating System Concepts and Techniques) 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 Concepts and Techniques
What is What Operating Systems Do and why is it important in Operating System Concepts and Techniques?
An Operating System (OS) is system software acting as an intermediary between computer hardware and users, providing an execution environment where programs run safely and conveniently.
What is User-Facing Services and why is it important in Operating System Concepts and Techniques?
Encompasses User Interface (CLI/GUI), Program Execution, I/O Operations, File-System Manipulation, Interprocess Communications, and hardware/software Error Detection.
What is CPU Scheduling Mechanics & Criteria and why is it important in Operating System Concepts and Techniques?
The dispatcher and scheduler govern how CPU bursts are assigned across competing processes.
What is Dynamic Loading & Linking and why is it important in Operating System Concepts and Techniques?
Dynamic loading defers loading routines until called; dynamic linking maps a single shared library (.so/.dll) across all processes via runtime stubs.
What is File Allocation Methods and why is it important in Operating System Concepts and Techniques?
Block-mapping strategies determine sequential throughput, direct random-access speed, and fragmentation.
What is the official course code and credit structure for Operating System Concepts and Techniques at University of Kerala?
Operating System Concepts and Techniques carries the official course code UK6DSCCAP306 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 Concepts and Techniques?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Operating System Concepts and Techniques (UK6DSCCAP306) 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 6 Subjects
Browse study notes for other courses in BCA Sem 6:
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.