PadhaikoAll subjects

Introduction

Operating System (ENCT 254)

Open in the Padhaiko app

1.1 Introduction to operating systems

An Operating System (OS) is a system software program that acts as an intermediary interface between computer hardware and the user (or application programs). It controls and coordinates the execution of user programs and the allocation of hardware resources such as the CPU, memory space, file storage, and input/output (I/O) devices.

Fundamentally, an operating system operates at the boundary where raw hardware meets user software, pursuing three primary objectives:

  1. Convenience and Usability: Hiding the intricate, low-level physical details of peripheral controllers and hardware instructions behind user-friendly abstractions.
  2. Efficiency and Resource Management: Ensuring fair, optimized, and deadlock-free utilization of scarce system resources among competing tasks.
  3. Protection and Isolation: Preventing unauthorized or malicious processes from interfering with one another or crashing the host system.
Definition

Operating System

An Operating System is an integrated suite of software modules that executes in a privileged CPU mode, managing system hardware, providing core services for application software, and enforcing access control across concurrent processes.

Dual-Mode Operation in Hardware

To prevent faulty or malicious user programs from compromising system stability, modern processors implement hardware-enforced execution privilege levels (often referred to as rings, such as Ring 0 and Ring 3 in x86 architecture):

AspectUser Mode (Ring 3)Kernel / Supervisor Mode (Ring 0)
Privilege LevelUnprivileged / RestrictedFully Privileged
Instruction ExecutionOnly non-privileged CPU instructions are permittedCan execute all machine instructions, including privileged CPU opcodes (cli, sti, hlt, invlpg)
Memory AccessRestricted strictly to the process's own virtual address spaceUnrestricted direct access to physical memory and all hardware device registers
Hardware AccessCannot execute direct I/O port instructions (in, out) or modify control registersDirect read and write access to all peripheral device controllers and hardware ports
Crash ImpactIf a user program crashes, the OS terminates it safely without affecting other processesA crash or unhandled page fault here halts the entire machine (Kernel Panic / Blue Screen of Death)

The CPU transitions from User Mode to Kernel Mode exclusively through hardware-enforced entry mechanisms:


1.2 OS as an extended machine and resource manager

Operating system theorists view the OS from two distinct, complementary perspectives: top-down (as an Extended Machine) and bottom-up (as a Resource Manager).

Top-Down vs. Bottom-Up Architectural ViewText
       +---------------------------------------------+
       |   User Applications / Utilities / Shell     |
       +---------------------------------------------+
                            |
   [ TOP-DOWN VIEW: Extended Machine / Abstraction ]
   Turns ugly, complex hardware into elegant abstractions:
   (Disks -> Files; CPU -> Processes; RAM -> Virtual Memory)
                            v
       +=============================================+
       |              OPERATING SYSTEM               |
       +=============================================+
                            ^
   [ BOTTOM-UP VIEW: Resource Manager / Multiplexing ]
   Manages scarce hardware via Time- and Space-Division:
   (CPU Scheduling, Memory Allocation, I/O Arbitration)
                            |
       +---------------------------------------------+
       |   Raw Hardware: CPU, RAM, Disk, Bus, NIC    |
       +---------------------------------------------+

The Top-Down View: The OS as an Extended Machine

Bare computer hardware is notoriously difficult, cumbersome, and error-prone to program directly. Consider writing data to a physical magnetic disk without an operating system:

As an extended machine (or virtual machine), the operating system provides clean, high-level abstractions that hide these messy physical details. Instead of writing sectors to cylinder , head , sector , the application simply calls write(fd, buffer, bytes). The OS transforms raw, ugly hardware into an elegant, extended machine that presents files, directories, processes, address spaces, and network sockets.

The Bottom-Up View: The OS as a Resource Manager

Modern computers execute multiple programs simultaneously. Multiple processes concurrently demand the CPU, write to disks, allocate memory, and send packets over a single network card. Without centralized coordination, chaos would ensue—processes would overwrite each other's memory and scramble disk blocks.

As a resource manager, the OS acts as an impartial arbiter, tracking who is using which resource, granting requests, measuring usage, and deallocating resources when tasks terminate. Hardware resources are shared through two fundamental multiplexing strategies:

Resource Multiplexing Strategies
Multiplexing StrategyMechanismExample Resources Managed
Time MultiplexingDifferent processes take turns using the resource sequentially over discrete time intervals.CPU Scheduling: Each process runs for a short time slice (quantum) before being preempted.
Printer Sharing: Print spooler sequences print jobs one after another.
Space MultiplexingThe total capacity of a resource is subdivided simultaneously among multiple active tasks.Main Memory (RAM): Physical memory is divided into frames or segment regions allocated to separate programs.
Hard Disk Storage: Storage blocks are partitioned among thousands of distinct files.

1.3 History of operating system

The development of operating systems closely mirrors the underlying hardware generations:

Chronological Generations of Operating Systems
GenerationEra & Hardware BasisTypical ArchitectureDominant OS Concepts & Systems
First Generation1945–1955
Vacuum Tubes, Plugboards
Huge mainframe mainframes; no operating system. Programmers signed up for physical time blocks.Bare machine programming in absolute machine language. No OS, no assemblers, punch cards used later.
Second Generation1955–1965
Transistors, Magnetic Tapes
Mainframes (e.g., IBM 7094); human computer operators loaded punched card decks.Batch Systems: Grouping jobs with similar requirements into batches. FMS (Fortran Monitor System) and IBSYS.
Third Generation1965–1980
Integrated Circuits (ICs)
Single computer family serving scientific and commercial workloads (IBM System/360).Multiprogramming: Multiple jobs kept in memory simultaneously.
Spooling: Simultaneous Peripheral Operations On-Line.
Time-Sharing: MULTICS, CTSS, early UNIX.
Fourth Generation1980–Present
LSI / VLSI Microprocessors
Personal Computers (PCs), workstations, handheld mobile devices, multicore servers.GUI-based personal OS (MS-DOS, Windows, classic Mac OS), modern UNIX/Linux, Android, iOS. Distributed and cloud virtualization.

Multiprogramming vs. Uniprogramming

In early uniprogramming batch systems, only one program resided in memory at a time. Whenever the running program initiated an I/O operation (such as reading a card or tape block), the CPU sat completely idle, waiting for mechanical devices to complete.

Definition

Multiprogramming

Multiprogramming is an operating system technique where multiple independent programs are kept resident in main memory simultaneously. When the currently running program pauses to await an I/O event, the OS CPU scheduler switches the processor to execute another ready program, keeping the CPU continuously productive.

Probabilistic Model of CPU Utilization

If a process spends a fraction of its execution time waiting for I/O operations to complete, the probability that all independent processes in memory are simultaneously waiting for I/O is .

The theoretical CPU utilization with degree of multiprogramming is given by:


1.4 Type of operating system: Mainframe, server, personal, smartphone and handheld, IOT and embedded, real-time, smart-card

Operating systems are tailored to the physical constraints, user workloads, and performance objectives of their target environments:

Taxonomy of Operating System Types
OS TypePrimary Design GoalsResource ConstraintsTypical Examples
Mainframe OSMassive batch processing, heavy transaction throughput, continuous uptime, and massive I/O capacity.Huge memory arrays, dedicated I/O channels, clustered disk subsystems.IBM z/OS, OS/390
Server OSServing multiple concurrent network clients, sharing files, hosting databases, and web services.Multi-socket multicore processors, hundreds of gigabytes of RAM, high-bandwidth NICs.Linux (RHEL, Ubuntu Server), Windows Server, FreeBSD
Personal OS (Desktop)Fast interactive responsiveness, rich Graphical User Interface (GUI), multimedia playback, office applications.Single-user desktop/laptop hardware; gigabytes of RAM, high-resolution display adapters.Microsoft Windows 11, Apple macOS, Fedora Workstation
Smartphone & Handheld OSTouchscreen gestures, energy conservation, power management, wireless connectivity, cellular telephony.Strict battery limits, flash storage, limited thermals, constrained RAM.Google Android, Apple iOS
IoT & Embedded OSMinimal footprint, ROM-resident execution, continuous unattended operation, real-world sensor acquisition.Ultra-low RAM (often kilobytes to megabytes), low-clock microcontrollers, battery-powered.FreeRTOS, Zephyr, Contiki, Embedded Linux
Real-Time OS (RTOS)Deterministic latency: Correctness depends not only on the logical output but also on meeting strict time deadlines.Predictable interrupt latency, bounded context-switch times, priority inheritance.QNX Neutrino, VxWorks, RTLinux
Smart-Card OSSecure cryptographic transactions, electronic payment, SIM authentication.Extreme resource limits: 8-bit/32-bit secure CPU, few kilobytes of RAM, small EEPROM/ROM.Java Card, Multos

Hard Real-Time vs. Soft Real-Time Systems

AspectHard Real-Time SystemSoft Real-Time System
Deadline RigidityDeadlines are absolute and non-negotiable.Deadlines are important, but occasional misses do not cause system failure.
Consequence of FailureMissing a single deadline causes catastrophic failure, financial loss, or loss of human life.Missing a deadline causes service degradation (jitter, dropped video frames), but the system survives.
DeterminismFully deterministic; worst-case execution time (WCET) must be mathematically provable.Best-effort or probabilistic scheduling; average response time is optimized.
Paging & Virtual MemoryVirtual memory paging is strictly disabled to avoid non-deterministic page fault latencies.Virtual memory and caching are permitted.
ApplicationsPacemakers, automotive ABS braking systems, aircraft fly-by-wire flight controllers.Video streaming (YouTube), online multiplayer gaming, voice-over-IP (VoIP).

1.5 Operating system components: Kernel, shell, utilities, applications

A complete operating system software architecture consists of four distinct structural layers:

The Four Operational Layers of an OS
LayerExecution ModeResponsibilities & BehaviorExamples
ApplicationsUser ModeSoftware designed to accomplish end-user business or computational goals. Interacts with the OS exclusively through system calls or runtime libraries.Web browsers (Firefox), IDEs (VS Code), Database engines (PostgreSQL), Office suites.
UtilitiesUser ModeSpecialized system programs provided alongside the OS to configure hardware, manage files, monitor performance, and administer user accounts.File manipulation tools (cp, mv, tar), process inspectors (ps, top), network tools (ping, netstat).
ShellUser ModeThe primary user command interpreter. Reads textual commands or captures graphical mouse/touch events from the user, interprets them, and spawns corresponding processes.Command Line Interfaces (CLI): bash, zsh, sh, Windows PowerShell.
Graphical User Interfaces (GUI): GNOME, KDE, Windows Explorer.
KernelKernel ModeThe central, foundational core of the OS that remains resident in main memory at all times. Directly controls hardware, handles interrupts, enforces protection, and exposes system calls.Linux Kernel, Windows NT Kernel, Mach Microkernel, XNU Kernel.

Core Subsystems of the Operating System Kernel

Inside the kernel, five foundational subsystems collaborate to deliver reliable computing:

  1. Process Management Subsystem: Handles process and thread creation, termination, CPU scheduling, inter-process communication (IPC), and synchronization.
  2. Memory Management Subsystem: Allocates and tracks physical memory frames, maintains page tables for virtual memory, manages swapping, and prevents unauthorized cross-process memory access.
  3. File System Subsystem: Organizes persistent storage media into logical directories and files, manages disk block allocation maps, maintains inodes, and enforces read/write permissions.
  4. I/O & Device Driver Subsystem: Provides a uniform device interface (block, character, and network drivers), hides hardware controller quirks, manages interrupt service routines (ISRs), and controls I/O buffering and caching.
  5. Protection and Security Subsystem: Verifies user credentials, validates file access permissions (read/write/execute), and checks capability tokens for privileged operations.

1.6 Types of OS kernel: Monolithic, micro, nano, layered, hybrid, exo-kernel

Operating system kernels are classified by how their internal subsystems are structured and partitioned between user mode and kernel mode:

Architectural Comparison of Kernel Types
Kernel TypeArchitectural OrganizationKey AdvantagesPrimary DisadvantagesReal-World Examples
Monolithic KernelAll OS services (scheduler, memory manager, file systems, device drivers, network stack) run together in a single, large address space in kernel mode.Maximum Performance: Communication between subsystems consists of fast, direct C function calls without context switching.Poor Fault Isolation: A crash or memory leak in a third-party device driver can bring down the entire kernel. Massive codebase.Linux, traditional UNIX, FreeBSD
MicrokernelOnly the absolute bare minimum primitives (low-level address space management, thread scheduling, and IPC) remain in kernel mode. File systems, drivers, and network stacks run in user mode as isolated server daemons.High Reliability & Modularity: If a file system or network driver crashes, it can be restarted automatically without rebooting the system. Highly secure.Performance Overhead: Every service request requires multiple user-to-kernel mode switches and inter-process message copies across IPC channels.MINIX 3, QNX Neutrino, L4, Mach
NanokernelAn ultra-compact kernel that provides even less than a microkernel—essentially virtualizing the raw hardware timer, interrupt dispatching, and CPU registers.Extremely small footprint (often a few kilobytes of code), verifiable formal correctness.Applications require a heavy runtime library or guest OS layer to provide practical computing services.KeyKOS, early Symbian EKA1
Layered KernelThe OS is decomposed into hierarchical layers ( to ). Layer encapsulates bare hardware; Layer handles user applications. Each layer may only invoke routines in layer .Conceptual Elegance & Modularity: Verification and debugging are straightforward because each layer can be tested independently.Rigid Partitioning & Overhead: Difficult to define strict one-way layer dependencies in practice. Deep function call stacks degrade performance.THE multiprogramming system (Dijkstra)
Hybrid KernelCombines the raw speed of a monolithic kernel with the modular organization of a microkernel. Drivers and file systems run in kernel mode for speed, but are designed as modular subsystems communicating via messaging protocols.High performance coupled with clean subsystem boundaries and dynamic loadable kernel modules.Still susceptible to system-wide crashes if an in-kernel module executes an illegal memory pointer.Microsoft Windows NT / 10 / 11, Apple macOS (XNU)
Exo-kernelDecouples resource allocation from resource management. The kernel only securely allocates raw physical hardware slices (blocks, page frames) via capabilities and never provides high-level abstractions (files, processes).Applications can tailor their own OS abstractions via custom User-Space Library Operating Systems (LibOS) for optimal speed.Applications must link custom LibOSes; non-standard programming model.MIT Aegis, MIT Xok, Nemesis

1.7 System calls, shell commands, shell programming

System Calls

A system call is the programmatic interface provided by the operating system kernel that allows user-level applications to request privileged services from the hardware.

Definition

System Call

A System Call is a controlled mechanism by which a user-mode process requests a privileged service from the operating system kernel, causing a hardware-enforced mode switch from User Mode to Kernel Mode via a software trap or specialized CPU instruction.

The Step-by-Step Mechanism of a System Call

When a user program calls a standard C library wrapper function such as read(fd, buffer, nbytes):

Detailed Execution Sequence of a System CallText
User Space                              Kernel Space
===========                              ============
1. User application calls read()
2. read() library wrapper puts
   arguments on stack/registers
3. Places system call ID for read
   (e.g., 3 on x86) into register EAX
4. Executes trap instruction
   (e.g., syscall / int 0x80) --------> 5. Hardware switches CPU to Kernel Mode
                                         6. CPU looks up Interrupt Vector Table (IVT)
                                            and jumps to system_call handler
                                         7. Handler indexes System Call Dispatch Table
                                            using call number in EAX: sys_read()
                                         8. Kernel executes sys_read(): checks
                                            permissions, reads device driver buffer
                                         9. Kernel places return value into register EAX
11. User code resumes with return <---- 10. Kernel executes sysret / iret to switch
    value in EAX; stack restored            CPU back to User Mode (Ring 3)

Categories of Standard System Calls

System calls in modern operating systems (such as UNIX/Linux and Windows) fall into five broad functional categories:

Core System Call Categories
CategoryUNIX / POSIX FunctionWindows Equivalent APIPrimary Action
Process Controlfork(), execve(), wait(), exit()CreateProcess(), WaitForSingleObject(), ExitProcess()Spawns, monitors, executes, and terminates active processes.
File Managementopen(), read(), write(), close(), unlink()CreateFile(), ReadFile(), WriteFile(), CloseHandle()Creates, manipulates, reads, writes, and deletes file records.
Device Managementioctl(), read(), write()DeviceIoControl()Configures peripheral controllers, requests hardware buffer reads/writes.
Information Maintenancegetpid(), alarm(), time(), sleep()GetCurrentProcessId(), SetTimer(), GetSystemTime()Retrieves and sets system clocks, timers, process IDs, and CPU counters.
Communication & IPCpipe(), shmget(), socket(), send(), recv()CreatePipe(), CreateFileMapping(), connect()Establishes communication pipes, shared memory regions, and network sockets between processes.

Shell Commands and Shell Programming

The shell is an interactive command-line interpreter that reads user inputs, executes utility binaries, and facilitates task automation.

Commands executed inside a shell are split into two groups:

  1. Built-in Commands: Executed directly inside the shell process itself without spawning a child process (cd, pwd, echo, exit, history). For instance, cd must be a built-in because changing the current working directory of a child process would not affect the parent shell's working directory.
  2. External Commands: Separate executable binary files stored on disk in system paths (such as /bin, /usr/bin, or /usr/local/bin). When the user types ls, grep, cat, or gcc, the shell executes fork(), locates the binary in the \$PATH environment variable, calls execve() to replace the child process image, and executes wait() until the command completes.

Shell scripts allow sequence automation using control structures, variables, and process pipes:

Demonstration POSIX Shell ScriptText
#!/bin/sh
# Process monitoring shell script demonstrating pipeline and conditions
THRESHOLD=80
CURRENT_USAGE=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')

if [ "$CURRENT_USAGE" -gt "$THRESHOLD" ]; then
    echo "Warning: Root filesystem usage is at ${CURRENT_USAGE}%!"
else
    echo "Filesystem status healthy: ${CURRENT_USAGE}% utilized."
fi

1.8 POSIX standard

POSIX stands for Portable Operating System Interface (officially designated as IEEE 1003 and ISO/IEC 9945).

In the late 1970s and 1980s, dozens of incompatible UNIX derivatives emerged (AT&T System V, BSD UNIX, SunOS, AIX, HP-UX, Xenix). A C program written for BSD UNIX frequently failed to compile or run on AT&T System V because system call names, header files, argument types, and utility flags differed widely.

Definition

POSIX Standard

The POSIX Standard is a family of open standards maintained by the IEEE Computer Society and The Open Group that defines the standard Application Programming Interface (API), shell environment, and command-line utilities for operating systems to ensure source-code portability across diverse computing platforms.

Key Pillars of the POSIX Standard

  1. POSIX.1 (Core Services & C API): Defines the standard C programming language library interfaces for process creation (fork, exec), signals (sigaction), file operations (open, read, write), terminal I/O (termios), and threading (POSIX Threads or Pthreads, pthread_create).
  2. POSIX.2 (Shell and Utilities): Standardizes standard shell syntax (the POSIX shell, based on Bourne shell) and approximately command-line utilities (awk, sed, grep, find, make), ensuring that shell scripts run identically on compliant systems.
  3. Real-Time Extensions (POSIX.1b): Defines priority scheduling, real-time signals, asynchronous I/O, semaphores, message queues, and high-resolution timers.

1.9 Bootloader, MBR/GPT, UEFI and legacy boot

The boot process (bootstrapping) is the sequential procedure by which a computer initializes its hardware components and loads the operating system kernel into main memory following power application or system reset.

Sequential Stages of System BootingText
 [ Power-On / CPU Reset ]
            |
            v
 [ Firmware Phase: BIOS / UEFI ]
   - CPU executes code at reset vector
   - Performs POST (Power-On Self-Test)
   - Discovers hardware, reads boot priority
            |
            v
 [ Bootloader Phase: Stage 1 & Stage 2 ]
   - Firmware loads Stage 1 bootloader (MBR / EFI System Partition)
   - Stage 2 bootloader (GRUB2 / systemd-boot) presents OS selection menu
   - Loads kernel binary (vmlinuz) and RAM disk (initramfs) into memory
            |
            v
 [ Kernel Initialization Phase ]
   - Decompresses kernel, sets up page tables, configures CPU interrupts
   - Mounts initramfs as temporary root filesystem, loads storage drivers
   - Switches to real root filesystem on persistent disk
            |
            v
 [ User Space Initialization Phase ]
   - Kernel spawns the first user-space process (PID 1: systemd / init)
   - Starts system daemons, network services, and GUI display manager (login)

MBR vs. GPT Partitioning Schemes

Every persistent storage drive (HDD/SSD) is partitioned into logical regions defined by a partition table:

AspectMaster Boot Record (MBR)GUID Partition Table (GPT)
Standard OriginIntroduced with IBM PC DOS 2.0 (1983)Modern standard defined as part of the UEFI specification
Sector LocationLives in the very first 512-byte sector of the drive (Sector 0 / LBA 0)Uses LBA 1–33 at the start of the drive, plus a backup array at the disk's end
Max Primary PartitionsExactly 4 primary partitions (or 3 primary + 1 extended partition containing logical drives)Up to 128 partitions natively by default without needing extended partitions
Addressing Scheme32-bit Logical Block Addressing (LBA)64-bit Logical Block Addressing (LBA)
Maximum Disk SizeLimited to ()Up to ()
Data RedundancyZero redundancy; if Sector 0 is corrupted, all partition information is permanently lostDual partition tables: Primary at disk beginning, Secondary (Backup) at disk end; CRC32 checksums for integrity verification

Structure of an MBR Sector (Sector 0)

A standard MBR sector occupies exactly and is formatted into three distinct regions:

  1. Bootstrap Code (446 bytes): Machine instructions executed by the BIOS to locate the active (bootable) partition and load its Volume Boot Record (VBR).
  2. Partition Table (64 bytes): Four 16-byte partition records defining the status (bootable flag), starting Cylinder-Head-Sector (CHS), partition type, starting LBA sector, and total sector count for each primary partition ().
  3. Boot Signature (2 bytes): The magic number 0x55AA at offset 510–511, verifying to the BIOS that the sector contains valid boot code.

Legacy BIOS vs. UEFI Boot

Legacy BIOS vs. Modern UEFI Boot Architecture
FeatureLegacy BIOS (Basic Input/Output System)UEFI (Unified Extensible Firmware Interface)
Processor Mode16-bit x86 Real Mode (limited to 1 MB addressable RAM during boot).32-bit or 64-bit protected/long mode (can access all system RAM).
Boot MechanismReads raw executable code from the MBR (LBA 0) into physical address 0x7C00.Reads executable EFI bootloader binaries (.efi files) directly from a dedicated FAT32 EFI System Partition (ESP).
Partition SupportMBR only (max 2 TB).GPT native, with Protective MBR at LBA 0 for backwards compatibility.
Security FeatureNone; boot sectors can be overwritten by malicious bootkit malware.Secure Boot: Firmware verifies the cryptographic digital signature of bootloader and kernel binaries before executing them.
Speed & InterfaceSlow sequential POST hardware probing; text-only 80x25 character display.Fast parallel hardware initialization; rich graphical user interface with mouse and network support.

Worked Out Examples

Example 1.1

1.1

In a multiprogramming computer system, four independent processes are currently loaded in main memory. Measurements demonstrate that each process spends of its time waiting for I/O operations to complete.

  1. Calculate the theoretical CPU utilization using the probabilistic multiprogramming model.
  2. If main memory is expanded to allow eight processes to reside in memory concurrently, calculate the new CPU utilization and determine the percentage increase in processor productivity.

Evaluating CPU utilization for processes: Let denote the probability that an individual process is waiting for I/O:

Under the assumption that processes behave independently, the probability that all processes are simultaneously waiting for I/O is:

The theoretical CPU utilization is the probability that at least one process is ready to use the CPU:

Evaluating CPU utilization for processes: When memory is expanded to hold concurrent processes:

The updated CPU utilization is:

Calculating the percentage increase in CPU productivity: The percentage increase in CPU utilization achieved by expanding memory from 4 to 8 processes is:

Answer:
  1. For , the CPU utilization is ().
  2. For , the CPU utilization rises to (). Expanding memory provides a relative improvement in processor utilization.
Example 1.2

1.2

A legacy Master Boot Record (MBR) uses a 32-bit field to record the total number of sectors addressable in a partition.

  1. Show mathematically why an MBR partition table with standard physical sectors cannot address a storage drive larger than .
  2. If an Advanced Format drive employing () sectors is partitioned using the same 32-bit addressing field, calculate the maximum drive capacity in terabytes ().

Calculating maximum addressable capacity with sectors: A 32-bit sector address field can reference at most distinct sector numbers:

With a standard sector size of , the maximum total bytes addressable by the MBR partition table is:

Converting bytes into binary terabytes ( / standard operating system where ):

Hence, any disk storage beyond cannot be indexed using a 32-bit MBR field and remains completely inaccessible.

Calculating capacity with Advanced Format () sectors: With per sector, the total addressable storage with 32-bit LBA indexing becomes:

Converting this capacity to terabytes:

Answer:
  1. With 32-bit LBA and 512-byte sectors, the maximum addressable disk capacity is exactly ().
  2. With 4096-byte (4 KB) Advanced Format sectors, the maximum capacity expands to ().
Example 1.3

1.3

A computational process performs iterations. In Design A, each iteration executes an in-memory user function call that takes . In Design B, each iteration invokes a system call that requests hardware status, which requires an in-kernel execution time of plus a round-trip trap/mode switch overhead of ().

  1. Calculate the total CPU time expended by Design A and Design B.
  2. Calculate the slowdown factor caused by system call context-switching overhead.

Calculating total time for Design A (User-space function calls): Each iteration takes . For operations:

Calculating total time for Design B (System calls with mode switches): Each system call requires the actual execution plus mode switch overhead:

For iterations:

Evaluating the slowdown factor: The slowdown factor is the ratio of total execution times:

Answer:
  1. Total CPU time: Design A requires (); Design B requires ().
  2. The mode switch overhead makes Design B slower than pure user-space function calls.

Exercises

Chapter 1 Review Exercises

Question 1

Explain how the operating system functions as an Extended Machine and as a Resource Manager. Provide two concrete examples of hardware managed under each perspective. [2078, 2070]

Operating System as an Extended Machine (Top-Down View): From the programmer's perspective, bare computer hardware (disk drive heads, interrupt lines, timer chips) is complex, primitive, and difficult to program. The OS acts as an Extended Machine (or Virtual Machine) by providing clean, high-level abstractions that hide messy physical details.

  • Example 1 (Storage): The OS abstracts raw disk tracks, cylinders, and sectors into logical files and directories.
  • Example 2 (Processor): The OS abstracts raw CPU instruction execution into the concept of a process equipped with a private virtual address space.

Operating System as a Resource Manager (Bottom-Up View): From the hardware perspective, modern systems run multiple programs concurrently that compete for limited physical resources. The OS acts as a Resource Manager, arbitrating conflicts, enforcing fairness, and optimizing throughput using two techniques:

  • Time Multiplexing: Allocating the resource to different tasks sequentially over time slices. Example: Scheduling the CPU among ready processes using timer interrupts.
  • Space Multiplexing: Dividing the physical capacity of the resource simultaneously among multiple tasks. Example: Partitioning physical RAM into page frames allocated to distinct processes.
Answer:

As an Extended Machine, the OS provides elegant abstractions (files instead of disk sectors, processes instead of raw CPU instructions) hiding low-level hardware complexity. As a Resource Manager, the OS multiplexes scarce hardware resources fairly and efficiently through time sharing (CPU scheduling) and space sharing (main memory page frame allocation).

Question 2

Compare Monolithic, Microkernel, and Exo-kernel architectures. Explain why an exo-kernel does not require re-mapping of resources. [2078, 2073, 2070]

Architectural comparison:

  • Monolithic Kernel: All operating system services (file system, VFS, device drivers, scheduler, network stack) run together in kernel mode within a single large address space. It delivers top performance due to direct function calls, but suffers from poor fault tolerance—a single buggy device driver can crash the entire kernel.
  • Microkernel: Only minimal primitives (thread management, address spaces, and inter-process communication) run in kernel mode. All other services (file systems, drivers) run as unprivileged user-space servers. It provides exceptional fault isolation and security, but incurs performance overhead due to frequent IPC context switches.
  • Exo-kernel: Eliminates high-level operating system abstractions entirely. The kernel's sole duty is to safely allocate raw hardware resources to user-space applications using capabilities. Applications link custom Library Operating Systems (LibOS) to implement domain-specific abstractions.

Why an Exo-kernel does not require re-mapping of resources: Traditional operating systems map physical hardware resources (e.g., physical disk sectors, raw network packets) into intermediate generic kernel abstractions (e.g., file system buffers, socket queues). This forces the kernel to continually translate and remap structures back and forth.

In contrast, an exo-kernel grants applications direct, unabstracted ownership of physical resources via hardware capabilities and secure bindings. The kernel only validates authorization checks; the application's user-level Library OS manages the raw disk blocks or physical memory frames directly. Because no synthetic kernel-level abstraction exists between the hardware and the application, no re-mapping of resources is needed.

Answer:

Monolithic kernels run all services in kernel space for speed; microkernels run only basic primitives in kernel space for reliability; exo-kernels eliminate intermediate abstractions entirely. An exo-kernel does not require resource re-mapping because it allocates raw physical resources directly to applications via secure bindings, allowing user-space Library OSes to manage them without kernel translation.

Question 3

Trace the detailed sequence of steps that occurs when a user application invokes the read() system call, explaining the transition between User Mode and Kernel Mode. [2078, 2073]

User Space Preparation:

  1. The user program calls the library function read(fd, buffer, count).
  2. The C runtime library wrapper places the arguments onto the stack or into designated CPU registers according to the system calling convention.
  3. The wrapper stores the unique system call number corresponding to read (e.g., __NR_read) into an architecture register (such as EAX / RAX).
  4. The wrapper executes a software trap instruction (syscall, sysenter, or int 0x80).

Kernel Space Dispatch and Execution:

  1. The CPU hardware traps the instruction, saves the user Program Counter and register state onto the kernel stack, and switches the hardware mode bit from User Mode (Ring 3) to Kernel Mode (Ring 0).
  2. The CPU jumps to the kernel's central trap handler vector address.
  3. The trap handler reads the system call number from EAX and indexes into the System Call Dispatch Table to locate the handler pointer sys_read().
  4. The kernel verifies the validity of parameter addresses and caller permissions, then calls the underlying device driver or file system routine to transfer data into the user buffer.

Return to User Space:

  1. The kernel places the operation's result (e.g., number of bytes read or negative error code) into EAX / RAX.
  2. The kernel executes the return-from-trap instruction (sysret or iret), which restores the saved user program state and transitions the CPU mode bit back to User Mode.
  3. The library wrapper reads the return code from EAX and returns control to the user application.
Answer:

A system call transitions from User Mode to Kernel Mode via a hardware trap (syscall), which indexes the kernel's System Call Dispatch Table using a registered call ID. The kernel verifies arguments, performs the privileged hardware operation, writes the result to a register, and executes sysret to restore User Mode execution.

Question 4

Distinguish between Hard Real-Time and Soft Real-Time operating systems. Explain why standard general-purpose operating systems like Linux or Windows cannot guarantee hard real-time deadlines. [2078, 2074]

Differences in deadline criticality and failure impact:

  • In a Hard Real-Time System, meeting operational deadlines is an absolute physical constraint. Missing a single deadline represents a total system failure and can cause catastrophic loss of life or equipment destruction (e.g., aircraft flight controls, automotive airbag deployment, pacemakers).
  • In a Soft Real-Time System, missing a deadline degrades the quality of service (QoS) but does not cause system collapse. The utility of the result diminishes after the deadline, but the system continues operating (e.g., audio/video streaming, multiplayer online gaming).

Why standard desktop/server operating systems cannot meet hard real-time guarantees: General-purpose operating systems (standard Linux, Microsoft Windows) are engineered to optimize average throughput and fair resource sharing, which directly conflicts with deterministic worst-case latency:

  1. Virtual Memory Paging: Standard OSes employ demand paging. If an instruction references an unmapped virtual page, a page fault triggers disk I/O, stalling process execution for several milliseconds—a fatal delay for hard real-time tasks.
  2. Non-Preemptible Kernel Sections and Interrupts: Long critical sections inside the kernel disable interrupts or hold spinlocks, introducing non-deterministic scheduling jitter.
  3. Fairness-Oriented Schedulers: Completely Fair Schedulers distribute CPU time dynamically rather than strictly honoring absolute temporal deadlines.
Answer:

Hard real-time systems treat deadline misses as catastrophic failures; soft real-time systems tolerate occasional misses with degraded quality. General-purpose OSes cannot guarantee hard deadlines because demand paging, fair-share scheduling, and non-deterministic kernel interrupt disabling introduce unpredictable latency spikes.

Question 5

An operating system runs batch jobs where each job spends of its active time awaiting I/O operations.

  1. Determine the CPU utilization when jobs reside concurrently in memory.
  2. Calculate the CPU utilization when the multiprogramming level is increased to jobs and jobs.
  3. Explain why adding further processes beyond a certain limit produces diminishing returns in CPU utilization.

Calculating CPU utilization for , , and : Let be the I/O wait probability for each process.

  • For :
  • For :
  • For :

Diminishing returns analysis: Increasing from to (+2 processes) boosts utilization by . However, increasing from to (+1 process) only adds . As increases, the probability approaches zero asymptotically. Moreover, adding too many processes exhausts physical RAM, causing the OS to spend more time swapping pages than executing code—a pathological condition known as thrashing.

Answer:
  1. With , CPU utilization is .
  2. With , CPU utilization is ; with , it is .
  3. Diminishing returns occur because decays exponentially toward zero; excessive multiprogramming exhausts physical RAM and induces thrashing.
Question 6

Compare Master Boot Record (MBR) and GUID Partition Table (GPT). Why must the operating system prevent unprivileged users from accessing the boot sector? [2073]

Comparison of MBR vs. GPT:

  • Partitioning Limits: MBR supports only 4 primary partitions (or 3 primary + 1 extended); GPT supports up to 128 partitions natively.
  • Drive Capacity: MBR uses 32-bit sector addressing, limiting disk size to (). GPT uses 64-bit addressing, supporting disks up to .
  • Data Integrity and Redundancy: MBR stores a single copy of partition data in Sector 0 with no checksums. GPT maintains primary partition tables at the beginning of the disk and backup tables at the end, protected by CRC32 checksums.
  • Firmware Integration: MBR pairs with legacy 16-bit BIOS; GPT pairs with modern 32/64-bit UEFI supporting Secure Boot.

Why user access to the boot sector must be prevented: Allowing direct write access to Sector 0 compromises both system integrity and security:

  1. An accidental write would corrupt the partition table, rendering all disk partitions unreadable upon reboot.
  2. A malicious user or malware could install a bootkit into the Master Boot Record. Because boot code executes before the operating system kernel is loaded into memory, a bootkit runs at a higher privilege than the OS, allowing it to bypass all kernel security mechanisms, modify system calls, and conceal itself completely from antivirus scanners.
Answer:

MBR is limited to 4 primary partitions and 2 TB disk sizes with zero redundancy, whereas GPT supports 128 partitions, 9.4 ZB capacities, and backup partition tables with CRC32 verification. The OS prohibits user write access to the boot sector to prevent partition table destruction and stop bootkits from hijacking system control prior to OS kernel initialization.

Past exam questions for Operating System

Process description, states and control · Scheduling algorithms →