OS NOTES
OS NOTES
md 2026-07-26
Think of it like a restaurant manager: you (the user) don't go into the kitchen (hardware) and cook yourself.
You tell the manager (OS) what you want, and the manager coordinates the kitchen staff (CPU, memory, disk,
etc.) to get it done.
Key point: The OS is always running in the background — it's the one program that never stops as long as
the computer is on.
Ability to Evolve Should allow new features to be added without breaking existing services
Resource Management Fairly allocates CPU, memory, disk, and I/O among competing programs
Error Detection – catching and handling hardware/software errors so the system stays stable
Job Accounting – keeping track of resource usage (useful for billing/auditing in shared systems)
In short: the OS hides hardware complexity and gives you a clean interface (sometimes called a "virtual
machine") to work with.
1. No OS (1940s) – Programs were fed directly in machine language; no software layer existed at all.
2. Batch Processing Systems – Similar jobs were grouped ("batched") on punch cards and fed to the
computer one batch at a time, with no user interaction during execution. This removed the need for an
operator to manually handle each job.
3. Multiprogramming Systems – Multiple programs are kept in memory together. When one program is
waiting for I/O (which is slow), the CPU switches to another ready program instead of sitting idle. This
was the real turning point in OS design because it boosted CPU utilization.
4. Time-Sharing Systems – An extension of multiprogramming where the CPU's time is split into small
slices and given to multiple users, so each one feels like they have the system to themselves.
5. Modern/Distributed/Mobile/AI-integrated Systems – Today's OS (Windows, Linux, Android, iOS)
handle networking, multiple cores, mobile devices, and even AI-based features like voice assistants.
Note: Newer generations didn't fully replace older ones — batch and time-sharing concepts still exist in
specific niche use-cases (e.g., mainframes, servers) alongside modern systems.
Used in
Real-Time OS Designed to meet strict timing deadlines for critical
embedded/avionics
(RTOS) tasks (hard or soft real-time)
systems
This "resource manager" view is one of the fundamental ways to define and understand what an OS actually
does — instead of thinking of it purely as a user interface, you think of it as a fair, efficient traffic controller for
hardware.
8. System Calls
A system call is the only official doorway a user program has into the OS kernel. Whenever a program needs
something only the kernel can safely provide (like reading a file, creating a process, or talking over the
network), it must go through a system call — it cannot touch hardware or protected resources directly.
Why it matters: This keeps the system stable and secure — user programs run in user mode (restricted),
while the kernel runs in kernel mode (privileged). A system call temporarily switches the CPU into kernel
mode to safely perform the requested operation, then switches back.
3/6
Module1_Fundamentals_of_OS_Notes.md 2026-07-26
Information
Get/set system data like time, process ID getpid(), alarm(), sleep()
Maintenance
Good to remember: A system call causes a mode switch (user → kernel), but it doesn't automatically cause a
context switch — a context switch only happens if the calling process actually has to block/wait.
9. Shell
The shell is the outer layer of the OS that a user directly interacts with — it takes commands from the user
(typed or scripted) and translates them into actions the kernel can perform.
Kernel = inner core, handles hardware-level work (process, memory, I/O management)
Shell = outer layer, handles user interaction (also called "user space")
Types of Shells
Command-Line Shell (CLI) — user types text commands (e.g., Bash in Linux). Lightweight, fast,
preferred by developers/sysadmins.
Graphical Shell (GUI) — user interacts via windows, icons, and menus (e.g., Windows Explorer, GNOME
Shell).
Shell scripting lets you write a sequence of commands into a file so the shell can run them automatically —
useful for automating repetitive tasks, and it supports loops and conditional logic.
The entire OS — process management, memory management, file systems, device drivers — is built as
one large program running in a single address space (kernel mode).
Advantage: Fast, since components can call each other directly without overhead.
4/6
Module1_Fundamentals_of_OS_Notes.md 2026-07-26
Disadvantage: Poor fault isolation — a bug in any part can crash the whole system; hard to maintain as
it grows large. MS-DOS is a simple/monolithic example; UNIX and Linux use a monolithic kernel.
b) Layered Structure
The OS is broken into a stack of layers (Layer 0 at the bottom = hardware, topmost layer = user
interface).
Each layer only uses services from the layer directly below it — this is called abstraction, since a layer
doesn't need to know how lower layers actually work internally.
Advantage: Easier to design, debug, and maintain since responsibilities are isolated per layer.
Disadvantage: Slower — a request may have to pass through many layers to get serviced, and careful
planning is needed to decide the order of layers. Example: Windows NT partly follows this approach.
c) Microkernel Structure
Keeps only the bare minimum inside the kernel — typically just IPC (inter-process communication),
basic process scheduling, and minimal hardware handling.
Everything else (device drivers, file systems, network services) runs as separate processes in user space,
and they talk to the microkernel via message passing.
Advantage: More secure and reliable — if a user-space service crashes, the whole system doesn't go
down; also easier to extend without touching the kernel.
Disadvantage: Message passing between user space and kernel is slower than direct function calls in a
monolithic kernel, so raw performance can suffer. Example: MINIX, Mach.
Where services run All in kernel space Only essentials in kernel; rest in user space
Stability/Security One failure can crash system Failures isolated to individual services
(Hybrid kernels, like macOS's XNU, blend both approaches — monolithic speed with some microkernel-style
modularity.)
e) Client-Server Model
The OS (or a system) is organized around two roles: clients that request services, and servers that
provide them.
The "kernel" can be reduced to just handling communication (message passing) between clients and
servers — most actual work (file service, process service, etc.) is done by server processes, often running
in user space.
This model works whether the client and server are on the same machine or across a network, which
makes it a natural fit for distributed systems.
5/6
Module1_Fundamentals_of_OS_Notes.md 2026-07-26
Advantage: Centralized control of services, easier to scale (add more servers), easier security
enforcement.
Disadvantage: Communication (request–response) adds overhead compared to direct function calls.
Source basis: GeeksforGeeks Operating Systems articles, rewritten and simplified for study purposes.
6/6
Module2_Process_Management_Notes.md 2026-07-26
1. What is a Process?
A process is simply a program in execution. A program sitting on disk is just static code and data — the
moment it starts running, the OS turns it into an active process by giving it memory, a program counter,
registers, and other runtime resources.
Program Process
Has no resources of its own Owns CPU time, memory, open files, etc.
Attributes of a Process
A process isn't just "the code" — the OS needs to track several attributes for it, including:
All of this information is stored together in a structure called the Process Control Block (PCB).
Process ID (PID)
Process State
Program Counter
CPU registers
CPU scheduling info (priority, pointers to scheduling queues)
1/7
Module2_Process_Management_Notes.md 2026-07-26
Context Switching: When the OS switches from one process to another, it saves the current process's
CPU register values into its PCB, and loads the incoming process's saved values from its own PCB — this
is exactly what lets a paused process resume later as if nothing happened.
Resource Sharing: The PCB records exactly what resources (files, memory) a process is holding, so the
OS can manage sharing and avoid conflicts.
Security: The PCB is kept in protected OS memory so ordinary user programs can't tamper with it.
All PCBs together are stored in the Process Table — an array/list where the OS can quickly look up a process's
PCB using its PID.
3. Process Creation
Processes are created when:
On Unix-like systems, a new process is normally created using the fork() system call:
fork() makes a copy of the calling process. The process that called it becomes the parent, and the
new copy is the child.
The child gets its own unique PID, but starts out as an (almost) identical copy of the parent — same
code, but a separate memory space.
After fork(), both parent and child continue running from the same point in the code — the return
value tells them apart (0 in the child, child's PID in the parent).
Very often, the child then calls exec() to replace its own memory image with a completely new
program — this is the classic fork + exec pattern used to launch new programs from a shell.
Process Termination
Normal exit – it finishes its work and calls exit(); the OS reclaims its memory, files, and other
resources.
Killed by the OS or its parent – e.g., the task is no longer needed, or it exceeded its resource limit.
Cascading termination – if a parent process is terminated, all its child processes are terminated too.
4. Process States
A process moves through several states during its lifetime. The simplest model has just 2 states, but real
operating systems use a richer model.
2/7
Module2_Process_Management_Notes.md 2026-07-26
State Meaning
Running Currently executing on the CPU (only one process per CPU core at a time)
New → Ready – after creation and admission into the ready queue
Ready → Running – the scheduler picks this process ("dispatch")
Running → Ready – time slice expires (preemption) even though the process isn't done
Running → Blocked – process requests I/O or waits for an event/resource
Blocked → Ready – the awaited event completes, process rejoins the ready queue
Running → Terminated – process finishes or is aborted
Some systems add two more states to handle memory pressure — moving a waiting/ready process out of
main memory into secondary storage (swapping):
(This gives the well-known "7-state process model" seen in some textbooks.)
Tip for the transition diagram in your exam: always show the 5 core states as boxes with arrows labeled by
the reason for transition (dispatch, timeout, I/O wait, I/O completion, exit) — that's what examiners look for.
5. Types of Schedulers
The OS uses different schedulers to decide which process gets a resource and when. They operate at different
frequencies and levels:
Also
Scheduler Job Frequency
Called
Long-Term Job Decides which jobs/programs are Runs rarely (controls degree
Scheduler Scheduler admitted into memory (New → Ready) of multiprogramming)
3/7
Module2_Process_Management_Notes.md 2026-07-26
Also
Scheduler Job Frequency
Called
Short-Term CPU Decides which ready process gets the Runs very frequently
Scheduler Scheduler CPU next (Ready → Running) (milliseconds)
Can OS interrupt a Yes — CPU can be forcibly taken No — process keeps the CPU until it
running process? away finishes or blocks itself
Time-sharing/interactive
Use case Simple batch systems
systems
Simple way to remember: Preemptive = "the CPU can be taken away from you"; Non-preemptive = "once you
have the CPU, you keep it till you're done or you ask to wait."
SRTF (Shortest Preemptive version of SJF — a new Same starvation risk for
Remaining arrival with a shorter remaining time Yes long jobs, plus more
Time First) can interrupt the current process context switches
Priority Each process gets a priority number; Can be either Low-priority processes
Scheduling highest priority runs first may starve; solved using
aging (gradually raising
4/7
Module2_Process_Management_Notes.md 2026-07-26
7. Types of Threads
A thread is the smallest unit of CPU execution within a process — sometimes called a "lightweight process." A
single process can have multiple threads that share the same memory/resources but execute independently.
Created and managed entirely by a user-level thread library — the kernel doesn't even know they
exist; it just sees one regular process.
Fast to create and switch between (no kernel involvement needed).
Drawback: If one user thread makes a blocking system call, the entire process can get blocked, since
the kernel only sees a single thread of control.
5/7
Module2_Process_Management_Notes.md 2026-07-26
The kernel is aware of each individual thread, so it can schedule them independently — allowing true
parallel execution on multiple CPU cores.
Drawback: Slower to create/switch than user-level threads, since every thread operation needs a
system call into the kernel.
Blocking system call Blocks entire process Only that thread blocks
8. Multithreading Models
These models describe how user-level threads are mapped to kernel-level threads.
a) Many-to-One Model
b) One-to-One Model
c) Many-to-Many Model
Many user-level threads are multiplexed over a smaller or equal number of kernel threads.
Combines the best of both worlds: the OS can create as many kernel threads as needed for parallelism,
while the application can still create as many user threads as it wants without overloading the kernel.
Considered the most flexible model — if one thread blocks, the kernel can schedule another user
thread on a different kernel thread, so the whole process doesn't stall.
Source basis: GeeksforGeeks Operating Systems articles, rewritten and simplified for study purposes.
7/7
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
PART A: CONCURRENCY
1. Principles of Concurrency
Concurrency means multiple processes (or threads) making progress "at the same time" — either truly in
parallel (multiple CPUs) or interleaved on a single CPU that switches rapidly between them.
Independent – don't share data with any other process, so they can't affect or be affected by others.
Cooperating – share data or resources with other processes, which means their outcomes can depend
on execution order — this is exactly where synchronization problems come from.
Why concurrency is tricky: when cooperating processes access shared data at the same time without
coordination, the final result can depend on the unpredictable order in which their instructions get interleaved
by the CPU scheduler. This is called a race condition, and avoiding it is the whole point of process
synchronization.
Example: think of an ATM system — one process reads your card and PIN, another checks your account
balance, and a third dispenses the cash. These separate processes must communicate to complete a single
transaction correctly.
1/9
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
Processes exchange data via Slower Safer — processes don't touch each
Message
send()/receive() calls; the (kernel other's memory directly, so fewer
Passing
kernel manages delivery overhead) synchronization headaches
Pipes – a one-way (or two-way) communication channel, often used between a parent and child
process
Message Queues – messages sit in a kernel-managed queue until the receiving process picks them up;
supports asynchronous communication
Semaphores – used alongside shared memory to control access and avoid conflicts
Signals – used to notify a process that an event has occurred
Challenges of IPC
Poor coordination between communicating processes can lead to race conditions, deadlock, starvation,
and data inconsistency — which is exactly why synchronization tools exist.
Critical Section: the part of a program where a process accesses shared resources (variables, files,
memory) that must not be touched by more than one process at the same time.
Race Condition: occurs inside a critical section when the final outcome depends on the unlucky/lucky
order in which multiple processes' instructions get interleaved.
Preemption: the OS pausing a running process to give the CPU to another — if this happens in the
middle of a critical section without protection, it can cause an inconsistent read/write.
Classic example of a race condition: Suppose balance = 100. Process P1 wants to add 10; Process P2
wants to subtract 10. If P1 reads balance=100, gets interrupted before writing back, and P2 also reads
balance=100, subtracts 10, and writes 90 — then when P1 resumes and writes 110, the final balance ends up
wrong (should have been 100, but ends up as 90 or 110 depending on timing). This is why unsynchronized
access to shared data is dangerous.
1. Mutual Exclusion – no two processes may be inside their critical sections at the same time.
2. Progress – if no process is in the critical section, and some processes want to enter, the decision of who
enters next cannot be postponed indefinitely (no unnecessary blocking).
3. Bounded Waiting – there must be a limit on how many times other processes are allowed to enter the
critical section before a waiting process gets its turn (prevents starvation).
Mutual Exclusion simply means: no two processes can be executing in their critical section at the same point in
time. It was a term first introduced by Dijkstra, and it's the foundation every synchronization mechanism is
built on.
Peterson's Algorithm – a classic solution for exactly two processes; uses a turn variable and flag
array to guarantee mutual exclusion, progress, and bounded waiting.
Dekker's Algorithm – one of the earliest two-process solutions, also using flags and a turn variable.
Bakery Algorithm – extends the idea to multiple processes, working like a "take-a-number" system at a
shop counter — whoever has the lowest number goes first.
(Drawback: software solutions are relatively complex to get exactly right and can be error-prone.)
Test-and-Set (TSL): Atomically checks a lock variable's value and sets it to "locked" in a single
indivisible step — so no other process can sneak in between the check and the set.
Swap Instruction: Similarly exchanges the values of two variables atomically.
Hardware instructions are fast, since they're a single indivisible CPU instruction, but on their own they still rely
on busy waiting (a process keeps checking the lock in a loop, wasting CPU cycles) and don't fully guarantee
bounded waiting or fairness.
Because of the drawbacks of both software and hardware locks, operating systems introduced higher-
level tools: Semaphores and Monitors.
A semaphore is an integer variable that can only be accessed through two special atomic operations:
wait() (also called P) – decrements the semaphore; if the result is negative, the calling process is
blocked.
signal() (also called V) – increments the semaphore and wakes up a waiting process, if any.
Because a blocked process is put to sleep (rather than busy-waiting in a loop), semaphores avoid wasting CPU
cycles.
Types of Semaphores:
3/9
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
Counting Any non-negative Used to manage a pool of identical resources (e.g., a fixed
Semaphore integer number of printers)
A mutex is a simpler locking mechanism specifically meant for mutual exclusion — think of it as a key:
whichever thread holds the mutex "key" can enter the critical section; everyone else must wait.
Locking mechanism, strictly for Signaling mechanism; can also coordinate between
Purpose
mutual exclusion different threads
Only the thread that locked it can Can be signaled by a different thread than the one
Ownership
unlock it that waited on it
Value
Locked / Unlocked 0 or 1
range
Simple way to remember: Mutex = "only I can unlock what I locked." Semaphore = "a more general signaling
tool that anyone can raise or lower."
PART B: DEADLOCK
6. Principles of Deadlock
Deadlock is a situation where a set of processes are all blocked, each holding a resource while waiting for
another resource that's held by a different process in the same set — so nobody can move forward.
Classic analogy: two trains approaching each other on the same single track — once they're face-to-face,
neither can move, because moving forward requires the other to move first (which it also can't do).
Important property: Deadlock is not something that resolves itself — once a set of processes is deadlocked,
they stay that way forever unless there's outside intervention (like the OS killing a process).
4/9
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
Condition Meaning
Mutual At least one resource must be held in a non-shareable way — only one process can
Exclusion use it at a time (e.g., a printer)
A process is holding at least one resource while waiting to acquire additional resources
Hold and Wait
held by others
A resource cannot be forcibly taken away from a process — it can only be released
No Preemption
voluntarily
A closed chain of processes exists where each one is waiting for a resource held by the
Circular Wait
next process in the chain
Remember: breaking even one of these four conditions is enough to prevent deadlock — this is exactly the
logic behind deadlock prevention techniques (see below).
In short: a cycle is a necessary condition for deadlock, but only sufficient when every resource type in the
cycle has just a single instance.
9. Deadlock Prevention
Deadlock prevention works by making sure at least one of the four Coffman conditions can never happen in
the system:
Condition to
How
Break
Hard to eliminate for inherently non-shareable resources (like a tape drive); for others
Mutual
like printers, use spooling — jobs are queued instead of directly waiting for the device,
Exclusion
so processes don't have to wait for exclusive access
5/9
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
Condition to
How
Break
Hold and Require a process to request all the resources it will ever need before it starts executing,
Wait or force it to release everything it's currently holding before requesting anything new
Allow the OS to forcibly take resources away from a waiting process (and give them back
No
later), or require a process to release all held resources if a new request can't be
Preemption
immediately satisfied
Impose a strict, unique numbering on all resource types, and require every process to
Circular Wait request resources only in increasing order of that number — this makes a circular chain
of requests impossible
Trade-off: Prevention techniques tend to be conservative — they reduce resource utilization and system
throughput because they restrict how freely processes can request resources.
Safe State: a state where there exists at least one order (a "safe sequence") in which all processes can
finish, one after another, using only the currently available resources plus what gets released as each
process completes.
Unsafe State: a state where no such safe sequence can be guaranteed — this doesn't necessarily mean
deadlock has happened, but it means deadlock could happen. The OS avoids ever entering such a state.
1-D array of
Available Available[j] = k → k instances of resource type Rj are currently free
size m
6/9
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
3. Assume Pi gets all resources it needs, finishes, and releases them back: Work = Work +
Allocation[i]; set Finish[i] = true; go back to step 2.
4. If Finish[i] = true for all processes, the system is in a safe state.
1. Check Request[i] ≤ Need[i] — if not, the process has exceeded its declared maximum, which is an
error.
2. Check Request[i] ≤ Available — if not enough resources are free, Pi must simply wait.
3. Pretend to allocate the requested resources (temporarily update Available, Allocation, and Need).
4. Run the Safety Algorithm on this new hypothetical state:
If it comes out safe → the request is genuinely granted.
If it comes out unsafe → roll back the pretend allocation, and Pi must wait.
(This same logic extends naturally to multiple resource types — you just work with vectors instead of single
numbers for Available/Allocation/Need/Max across all resource columns simultaneously.)
Limitation of Banker's Algorithm: it requires knowing the maximum resource demand of every process in
advance, which isn't always practical in real systems — and it tends to be conservative (a process might finish
using far less than its declared maximum).
Detection Techniques
Wait-For Graph: A simplified version of the resource allocation graph, showing only process-to-
process edges (P1 → P2 means P1 is waiting for a resource held by P2). A cycle in this graph indicates a
deadlock.
Resource Allocation Graph: As discussed above — look for cycles, keeping in mind the single-instance
vs multi-instance distinction.
Detection Algorithm (multi-instance case): Similar in structure to the Banker's Safety Algorithm —
using Available, Allocation, and Request matrices, the algorithm checks whether every process can
eventually get what it needs; if some processes are left permanently unable to proceed, they're
deadlocked.
Recovery Techniques
1. Process Termination
Abort all deadlocked processes – breaks the deadlock immediately but wastes all their work-in-
progress.
7/9
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
Abort one process at a time – terminate processes one by one (checking after each) until the
deadlock cycle is broken; less wasteful, but requires repeated detection checks.
2. Resource Preemption – forcibly take resources away from some processes in the deadlock and give
them to others. This raises three practical issues:
3. Process Rollback – roll a deadlocked process back to an earlier safe checkpoint (requires the system to
periodically save process state), rather than aborting it completely.
Choosing a victim usually considers: process priority, how much execution time would be lost, how many
resources it holds, and how expensive rollback would be — interactive processes are generally spared over
batch processes where possible.
Setup: n philosophers sit around a circular table. Between every adjacent pair of philosophers, there is exactly
one chopstick (so n chopsticks total for n philosophers). Each philosopher alternates between thinking and
eating — but to eat, a philosopher needs both chopsticks on either side of them.
Where deadlock can arise: If every philosopher simultaneously picks up the chopstick to their left first, then
all chopsticks get taken at once, and every philosopher is left waiting forever for the chopstick to their right
(which their neighbor is holding) — this is a circular wait, and the system deadlocks.
Common solutions:
8/9
Module3_Concurrency_and_Deadlock_Notes.md 2026-07-26
Source basis: GeeksforGeeks Operating Systems articles, rewritten and simplified for study purposes.
9/9
Module4_Memory_Management_Notes.md 2026-07-26
Every good memory management scheme needs to satisfy a few key requirements:
Processes must be prevented from interfering with each other's memory (accidentally
or maliciously). This check must actually be enforced by the processor hardware (not
Protection
just the OS), because the OS can't monitor every single memory access while a process
is running on the CPU.
Despite needing protection, the system must also allow controlled sharing — e.g.,
Sharing multiple processes using the same library or file can share a single copy in memory
instead of each having a separate copy, saving space.
Programs are typically organized into modules that are written and compiled
Logical
independently — memory management should support this structure (this is one of the
Organization
ideas behind segmentation).
Memory is organized into two levels in most systems — a smaller, faster main memory
Physical
(RAM) and a larger, slower secondary memory (disk). The OS must manage the flow
Organization
of information between the two.
Why relocation matters so much: most programming languages allow addresses to be calculated
dynamically at runtime, so the memory management system needs a flexible way to translate a program's
own internal addresses into wherever it actually ends up sitting in physical memory.
2. Memory Partitioning
Partitioning is about how the OS divides up main memory to give different processes their own space.
Memory is divided into a fixed number of partitions, decided in advance (at system configuration time) —
and this layout doesn't change afterward.
1/8
Module4_Memory_Management_Notes.md 2026-07-26
Pros: Simple to implement, easy to debug, no complex allocation needed, predictable performance — good
for batch systems with a known, fixed set of processes. Cons: Wastes memory via internal fragmentation; the
number of processes that can run at once is limited by the number of partitions.
Instead of pre-deciding partition sizes, the OS creates a partition at runtime, sized to exactly match the
memory needs of the process requesting it.
Pros: No internal fragmentation (since each partition is sized exactly to the process); better memory
utilization; supports more processes running concurrently. Cons: Still suffers from External Fragmentation —
as processes come and go, memory gets broken into small scattered free "holes" that individually may be too
small for a new process, even though the total free space might be sufficient. Solved (partially) using
compaction — shifting all occupied memory together to consolidate the free space into one large contiguous
block. Managing dynamic partitions is also more complex than fixed ones.
Partition size Decided in advance, unchanging Created at runtime, matches process size
2/8
Module4_Memory_Management_Notes.md 2026-07-26
Scans memory from the beginning Tends to fill up the start of memory
Fast (stops at
First Fit and allocates the first hole large quickly, causing fragmentation
first match)
enough for the process there over time
Is Best-Fit really "best"? Not always — even though it minimizes leftover wasted space per allocation, it takes
more time to search (since it must check every hole), and can actually perform worse than other strategies in
the long run because of the many small unusable fragments it leaves scattered around.
Logical (Virtual) The address generated by the CPU/program itself — it's from the process's own
Address perspective and doesn't physically exist as-is.
The actual, real location in main memory (RAM) where the data or instruction truly
Physical Address
resides.
The Memory Management Unit (MMU) — a piece of hardware — automatically translates every logical
address the CPU generates into the correct physical address, transparently, every time memory is accessed.
This translation is exactly what allows a process to be relocated in physical memory without the program itself
needing to know or care where it physically ends up.
3/8
Module4_Memory_Management_Notes.md 2026-07-26
5. Paging
Paging is a memory management technique that allows a process's memory to be non-contiguous —
instead of needing one unbroken chunk, the process is split into fixed-size pieces.
The process's logical memory is divided into fixed-size blocks called pages.
Physical memory (RAM) is divided into blocks of the same fixed size, called frames.
Pages of a process can be scattered across any available frames in physical memory — they don't need
to be next to each other.
1. A logical address is split into two parts: a page number and a page offset.
2. The page number is used to look up the corresponding frame number in the process's page table.
3. The frame number combined with the offset gives the final physical address.
Solves the problem of needing one large contiguous block of memory for a process.
Since memory is managed in uniform fixed-size chunks, allocation/deallocation bookkeeping is
simplified.
Eliminates external fragmentation completely (any free frame can hold any page) — though a small
amount of internal fragmentation can still occur in the last page of a process if it doesn't perfectly fill
a frame.
Downsides
Extra memory access needed to consult the page table before reaching the actual data (partly solved
using a hardware cache called a Translation Lookaside Buffer, or TLB).
The page table itself can get quite large for processes with big address spaces.
Requires more complex hardware/software support (MMU, page tables, page replacement algorithms).
6. Segmentation
Segmentation divides a program into logical, variable-sized chunks called segments — e.g., one segment for
code, one for the stack, one for a data array — based on how the programmer naturally organizes the
program, rather than forcing everything into equal fixed-size pieces.
Segments can differ in size (unlike pages, which are always the same fixed size).
A Segment Table keeps track of each segment's base address (where it starts in physical memory) and
limit (its size).
The logical address in segmentation is two-dimensional: a segment number and an offset within that
segment.
4/8
Module4_Memory_Management_Notes.md 2026-07-26
(Some systems combine both approaches — called Paged Segmentation or Segmented Paging — to get the
logical clarity of segmentation with the fragmentation-avoidance of paging.)
Demand Paging
Demand Paging is the practice of loading pages into physical memory only when they're actually needed,
instead of loading a process's entire address space upfront.
1. A process starts execution with only some of its pages loaded into memory.
2. If the CPU tries to access a page that isn't currently in memory, it generates an interrupt called a Page
Fault.
3. The OS puts the interrupted process into a blocked/waiting state.
4. The OS locates the required page (on disk, in the logical address space).
5. If memory is full, a page replacement algorithm decides which existing page to evict to make room.
6. The required page is brought into physical memory, and the page table is updated to reflect its new
location.
7. The process is placed back in the ready state and resumes as if nothing happened — the whole process
is transparent to the running program.
Benefits: Since only actively-needed parts of a program are loaded, memory is used efficiently, more
processes can be run concurrently (better multiprogramming), and even programs larger than physical RAM
can execute successfully.
Single-Level (Hierarchical/Simple) Paging: One large table directly maps every page number to a
frame number. Simple, but the table itself can become huge for large address spaces (e.g., a 32-bit
address space with 4KB pages needs roughly a million entries per process).
Multilevel Paging: Breaks a large page table down into smaller pieces organized across multiple levels
(like a tree), so the whole table doesn't need to be fully resident in memory at once — this saves space
for sparsely-used address spaces.
Hashed Page Tables: Uses a hash function on the page number to quickly locate the matching entry —
useful for very large (e.g., 64-bit) address spaces.
Inverted Page Tables: Instead of one entry per logical page (which could be huge), keeps just one
entry per physical frame — much smaller overall, but requires an extra search step to find the right
entry.
a) FIFO (First-In-First-Out)
Replaces the page that has been in memory the longest, regardless of how often or recently it was actually
used.
Replaces the page that won't be used for the longest time in the future.
Gives the theoretically lowest possible page fault rate — used purely as a benchmark to measure
how other algorithms perform.
Downside: Impossible to implement in a real system, since it requires knowing the future sequence of
page references in advance.
Replaces the page that hasn't been used for the longest time in the past — based on the idea that a page
unused for a while is unlikely to be needed again soon (the "locality of reference" principle).
Replaces the page that has been accessed the fewest number of times overall — instead of looking at
recency, it looks at raw frequency of use.
Works well for programs with consistent, predictable access patterns, where genuinely rarely-used
pages are correctly identified.
Downside: A page that was very popular early on but hasn't been used in a while can still "look"
important based on its old high count, even though it's no longer needed — this is called the problem
of not adapting to changing access patterns. (Ties are often broken using FIFO — whichever tied page
arrived first gets replaced.)
(There's also a related "opposite" idea — Most Frequently Used, MFU — which replaces the page with the
highest access count, based on the reasoning that a heavily-used page has probably already served its purpose
and is less likely to be needed further; it's far less common in practice than LFU.)
Belady's Anomaly
Normally, giving a process more page frames should reduce the number of page faults. Belady's Anomaly is
the surprising exception where, for certain reference patterns, increasing the number of frames actually
increases the number of page faults.
Occurs in: FIFO (and a few similar algorithms like Second-Chance and Random).
Never occurs in: Optimal, LRU, and LFU — because these are all "stack-based" algorithms, meaning
the set of pages kept in memory with n frames is always a subset of what would be kept with n+1
frames, so adding more frames can never make things worse.
Belady's
Algorithm Basis for Replacement Practical?
Anomaly?
y
Memory management requirements: Relocation, Protection, Sharing, Logical & Physical organization.
Fixed Partitioning: predefined partitions → internal + external fragmentation, simple but rigid.
Dynamic Partitioning: runtime-sized partitions → no internal fragmentation, but external
fragmentation remains (needs compaction).
Allocation strategies: First Fit (fast), Next Fit (spreads allocations), Best Fit (minimizes waste but slow,
leaves tiny holes), Worst Fit (leaves large usable leftover).
Relocation works via Logical (virtual) → Physical address translation, done by the MMU.
Paging: fixed-size pages/frames, non-contiguous allocation, eliminates external fragmentation, uses a
page table.
Segmentation: variable-size, logical/programmer view, uses a segment table, can suffer external
fragmentation.
Virtual Memory & Demand Paging: load pages only when needed; a page fault triggers loading the
missing page from disk.
Page Table structure: frame number, valid bit, dirty bit, reference bit, protection bits; can be single-
level, multilevel, hashed, or inverted.
Page Replacement: FIFO (simple, can suffer Belady's Anomaly), Optimal (best possible, impractical),
LRU (great practical approximation), LFU (frequency-based, struggles with changing patterns).
Source basis: GeeksforGeeks Operating Systems articles, rewritten and simplified for study purposes.
8/8
Module5_File_and_IO_Management_Notes.md 2026-07-26
User Application – programs that request file operations (create, read, write, delete)
Logical File System – manages metadata: file names, directories, and access permissions
Virtual File System (VFS) – acts as a bridge, letting many different underlying file systems work
through one common interface
Physical file system layer – actually reads/writes the raw blocks on the storage device
Editors, compilers —
Sequential The simplest method — records/information are read in anything that naturally
Access order, one after another, from the start of the file. processes data top-to-
bottom
Direct Allows jumping straight to any record by moving the file Databases, situations
(Random) pointer to a specific position/offset, without reading needing quick lookup of a
Access everything before it. specific record
1/8
Module5_File_and_IO_Management_Notes.md 2026-07-26
Content- Records/blocks are accessed based on their content Systems needing to fetch
Addressable rather than their address — a hash function generates a data by "what it is" rather
Access unique key for lookup. than "where it is"
How it Works
Faster than repeated read()/write() system calls, since it avoids the overhead of copying data
between kernel buffers and user buffers.
Lazy loading — only the parts of a (possibly huge) file that are actually accessed get loaded into RAM,
saving memory.
Supports sharing — multiple processes can map the same file, and if one process writes to it, the
changes become visible to all the other processes sharing that mapping (this is actually a common way
to implement shared memory).
Some systems support copy-on-write — processes can share a file in read-only mode, but if one
process writes, it gets its own private copy instead of affecting the others.
Limitations
a) Contiguous Allocation
Each file occupies a single, unbroken run of disk blocks — the directory entry just needs the starting block
address and the length of the file.
Advantages: Supports both sequential and direct access easily (the k-th block of a file starting at block
b is simply at b+k); extremely fast since very few disk-arm seeks are needed.
Disadvantages: Suffers from both internal and external fragmentation, making memory utilization
inefficient; growing a file's size is difficult since it depends on whether contiguous free space happens
to be available right next to it.
b) Linked Allocation
Each file is stored as a linked list of disk blocks, which don't need to be next to each other at all.
The directory entry holds a pointer to the file's starting block (and often the ending block too).
Every block contains a pointer to the next block in the file; the very last block's pointer is a null/−1,
marking the end.
Advantages: Very flexible — a file can grow easily since blocks can be scattered anywhere; no external
fragmentation.
Disadvantages: Doesn't support efficient direct/random access (you must follow the chain from the
start); each block "loses" a small amount of space to store the pointer; if a pointer gets corrupted, the
rest of the file chain can be lost.
c) Indexed Allocation
Brings all of a file's block pointers together into one dedicated index block, instead of scattering pointers
across the data blocks themselves.
Each file has its own index block, which simply lists all the disk block addresses that belong to that file.
Advantages: Supports direct access efficiently (just look up the index — no need to traverse a chain);
avoids the pointer-scattering problem of linked allocation.
Disadvantages: For very small files (2–3 blocks), reserving a whole separate index block is wasteful —
the pointer overhead is worse than linked allocation for tiny files; for very large files, a single index
block might not be big enough to hold every pointer (solved using multilevel index — an index block
pointing to other index blocks — or a combined scheme, where a few direct pointers are kept in the
file's own metadata, and only larger files use extra levels of indexing, as UNIX-style file systems do).
Quick Comparison
3/8
Module5_File_and_IO_Management_Notes.md 2026-07-26
Overhead None extra 1 pointer per block 1 index block per file
5. Directory Structures
A directory is a container the file system uses to organize files (and other directories) — think of it as a way to
store the "table of contents" for what's on the disk.
The simplest possible structure — there is only one directory (often called the root), and all files from
all users sit inside it, with no subdirectories at all.
Advantages: Very easy to implement; simple file operations (create, search, delete, update); fast
searching when the number of files is small.
Disadvantages: Every file must have a unique name system-wide — if two users both want to name a
file "test," there's a naming conflict; becomes cluttered and slow to search as the number of files grows;
no way to group related files together.
Introduces one User File Directory (UFD) per user — each user gets their own private directory space
(usually named after that user) to create files and subdirectories.
A system-wide Master File Directory (MFD) sits above all the UFDs, and is searched whenever a new
user's directory needs to be located.
Advantages: Solves the naming-conflict problem of single-level directories, since two different users
can now have files with the same name (they just live in different UFDs).
Disadvantages: Still limited — a single user can't create further subdirectories to organize their own
files into logical groups.
Goes a step further — users are now allowed to create subdirectories within their own directory,
nested as deep as needed, forming a full tree structure starting from a single root.
This is the structure most modern operating systems (Windows, Linux, macOS) actually use.
Advantages: Much better organization — users can group related files into folders/subfolders exactly
as they like; searching can be faster since it's scoped to relevant subdirectories; supports better access
control at each directory level.
Disadvantages: More complex to implement and manage than single or two-level structures; deleting
a non-empty directory needs careful handling (e.g., deleting everything inside it too).
(Some systems extend this further into a graph structure, allowing a file/directory to have more than one parent
via shared links — but the tree/hierarchical model is the one most commonly taught and used.)
4/8
Module5_File_and_IO_Management_Notes.md 2026-07-26
RAID
Technique Redundancy? Key Trade-off
Level
No — can't recover
Data striping — splits data into Maximizes speed and space, but
RAID 0 from a disk failure at
blocks spread across all disks zero fault tolerance
all
Mirroring — every bit of data is Great reliability and read speed, but
RAID 1 Yes (full duplication)
duplicated on a second disk uses double the disk space
Block-level striping with parity Avoids RAID 4's bottleneck, but data
Yes (survives 1 disk
RAID 5 distributed across all disks regeneration after a failure is more
failure)
(instead of one dedicated disk) complex
Like RAID 5, but with two Extra fault tolerance, but slower
independent parity Yes (survives 2 disk writes due to double parity
RAID 6
calculations distributed across failures) computation, and needs more disk
disks space for parity
Quick way to remember: RAID 0 = speed, no safety net. RAID 1 = full duplicate copies. RAID 5/6 = parity-
based protection (spread the "backup math" across disks). RAID 10 = best of both worlds, at a higher disk cost.
5/8
Module5_File_and_IO_Management_Notes.md 2026-07-26
Overall efficiency ranking (roughly): FCFS → SSTF → SCAN → C-SCAN → LOOK → C-LOOK (each an
improvement on wasted movement over the last, though SSTF trades efficiency for fairness issues).
Real-world note: These algorithms matter mainly for traditional spinning hard disks (HDDs), which have real
mechanical seek time. Modern SSDs have effectively zero seek time, so they typically just use simple
FCFS/FIFO ordering instead.
6/8
Module5_File_and_IO_Management_Notes.md 2026-07-26
A long string of bits, one per disk block — 1 typically means the block is free, 0 means it's allocated (or
vice versa, depending on convention).
Advantages: Simple to understand; finding the first free block is efficient — the OS scans in groups of
bits ("words") for a non-zero group, then pinpoints the exact free bit within it.
Disadvantages: For very large disks, the bitmap itself can become too large to comfortably keep
resident in memory.
b) Linked List
All free blocks are linked together, forming a chain — each free block simply stores a pointer to the
next free block, with the head pointer kept in a known/cached location.
Advantages: No wasted space computing/storing a full bitmap; efficient use of total available space.
Disadvantages: To find a free block somewhere in the middle of the list, the OS must traverse the chain
one block at a time — slow, and requires actual disk I/O for each step of the traversal, unlike the bitmap
which can often be scanned quickly in memory.
c) Grouping
A modification of the linked list idea — the first free block stores the addresses of the next n free
blocks (instead of just one). The last of those n addresses then points to another block that itself stores
the next batch of n free block addresses, and so on.
Advantages: Much faster to retrieve a whole batch of free blocks at once (fewer disk accesses overall)
compared to a plain linked list.
Disadvantages: Slightly more complex to manage than a simple linked list; not as beneficial if only one
or two free blocks are actually needed at a time.
d) Counting
Takes advantage of the fact that, in practice, several contiguous blocks are often freed (or allocated)
together. Instead of storing every free block's address individually, the system stores just the starting
address plus a count of how many contiguous free blocks follow it.
Example: an entry like (10, 3) represents blocks 10, 11, and 12 all being free.
Advantages: Greatly reduces the size of the free-space list when free blocks tend to occur in
contiguous runs.
Disadvantages: Less effective if free blocks are scattered randomly rather than in contiguous chunks;
adds a small amount of overhead per entry (needs to store both a starting address and a count).
Quick Comparison
Can be large for big Good (scan for non-zero Disk size is moderate; simplicity
Bitmap
disks word) valued
Linked Efficient (no separate Slow (must traverse, needs Simpler systems, less concern for
List table) disk I/O) lookup speed
7/8
Module5_File_and_IO_Management_Notes.md 2026-07-26
Very efficient for Efficient when runs are Disks with large contiguous free
Counting
contiguous runs common areas
Source basis: GeeksforGeeks Operating Systems articles, rewritten and simplified for study purposes.
8/8
Module6_RTOS_Notes.md 2026-07-26
1. Introduction to RTOS
A Real-Time Operating System (RTOS) is an OS designed to process data and respond to inputs within a
strict, predictable time limit — it's not just about being fast, it's about being on time, every time.
Every critical task must finish Missing a deadline causes a critical failure — equipment
Hard
within its deadline, no damage or even loss of human life (e.g., airbag systems,
RTOS
exceptions. pacemakers).
Deadlines still matter, and the Missing a deadline doesn't cause a catastrophe, but it does
Firm
system tries hard to meet make the output useless or undesirable — e.g., a big drop in
RTOS
them. product quality (a "late" result is basically as bad as no result).
Simple way to remember: Hard = disaster if late. Firm = the late result is worthless. Soft = late is okay, just less
ideal.
Every task has a defined time interval within which it must respond — this is the
Time Constraints
whole foundation of "real-time."
It's not enough to be fast — the result must also be correct, and correct within
Correctness
the time window.
RTOS provide critical safety guarantees and are built to run reliably for long
Safety
stretches without failure.
Stability Even under heavy load (many tasks running at once), the system still meets its
time constraints — it doesn't let the response get delayed just because things are
1/7
Module6_RTOS_Notes.md 2026-07-26
Real-Time Components/devices in the system often need to communicate with each other in
Communication real time too, not just process tasks independently.
Priority-Based
High-priority tasks are always executed before lower-priority ones.
Scheduling
4. Benefits of RTOS
Easy to design, develop, and run real-time applications on.
More compact than general-purpose OSes, so they need less memory.
Achieves maximum utilization of devices and system resources.
Focuses effort on the application actually running, rather than wasting attention on queued/waiting
applications.
Small program size means RTOS can be embedded into devices like transport systems and other
compact hardware.
Designed to be largely error-free.
Very efficient, well-managed memory allocation.
Real-time tasks are broadly split into hard real-time tasks and soft real-time tasks (matching the
RTOS types above).
The scheduler is the single most important component of a real-time system — typically a short-term
scheduler.
Its main focus is minimizing the response time of each process — rather than just trying to satisfy the
deadline directly, it's built around responding quickly.
Based on how schedulability is decided, whether the analysis is static or dynamic, and how the result is
produced, scheduling algorithms fall into four categories:
Static Table- Performs the scheduling analysis offline/in advance, and produces a schedule that
Driven tells the system exactly which task to start at which point in time.
Static Priority- Also uses static (advance) analysis, but instead of producing one fixed schedule, it
Driven assigns priorities to tasks — and the scheduler uses those priorities with
Preemptive preemption at runtime.
2/7
Module6_RTOS_Notes.md 2026-07-26
Property Description
Generated offline based on historical data or fixed priorities; it's static and never
Predefined Schedule
changes during runtime.
Deterministic Every task gets a fixed time slot or priority — execution always follows the
Execution specified order, with no runtime adjustments.
Can't respond to changing workloads or system conditions — the table stays the
Limited Adaptability
same even if new tasks appear or load shifts.
Simple Easy to implement since the schedule is already decided — no complex runtime
Implementation decision-making needed.
7. Cyclic Scheduling
Cyclic Scheduling (also called round-robin scheduling) is a dynamic approach that gives each task a fixed
time slot ("quantum") in a repeating, cyclic order — once a task's time is up (or it finishes early), the scheduler
moves on to the next task in the cycle, and the whole process repeats.
Property Description
Time slices are assigned based on a predetermined quantum; each task runs for
Dynamic Schedule that fixed amount of time before being preempted and sent to the back of the
queue.
Fairness and Every task gets an equal opportunity to run, preventing any single task from
Sharing monopolizing the CPU.
Runtime The scheduler can react to the current system state — task priorities, resource
Adjustments availability, waiting times.
Because every task gets guaranteed CPU time within a fixed slice, the system stays
Responsiveness
reasonably responsive to time-sensitive tasks.
3/7
Module6_RTOS_Notes.md 2026-07-26
Property Description
Overhead and Frequent context switches between tasks add overhead, and managing the task
Complexity queues/preemption needs more complex bookkeeping.
Priorities are assigned based on each task's absolute deadline — the task whose deadline is closest
gets the highest priority.
Priorities are not fixed — they're reassigned dynamically as time passes and deadlines shift.
EDF is highly efficient compared to other scheduling algorithms, and can push CPU utilization to close
to 100% while still guaranteeing every task's deadline is met.
Worked Example
P1 50 25
P2 75 30
1. P1's deadline is earlier, so initially P1 has higher priority and runs first, completing its 25 units of
execution.
2. After time 25, P2 starts executing, continuing until time 50 (when P1 becomes ready again).
3. At time 50, comparing deadlines — P1's deadline is 100, P2's is 75 — P2's deadline is closer, so P2
continues executing.
4. P2 finishes its processing at time 55.
5. P1 then executes from 55 until time 75 (when P2 becomes ready again).
6. At time 75, comparing deadlines again — P1's deadline is now 100, P2's is 150 — P1's deadline is
closer, so P1 continues.
7. This pattern repeats. Eventually, at time 150, both P1 and P2 have the same deadline — in that case,
P2 finishes its current processing first, and then P1 executes.
(This example shows EDF's core behavior: at every decision point, the scheduler simply re-checks which ready
task has the nearest deadline and runs that one — the priority ordering can flip dynamically as time progresses.)
Advantages of EDF
Meeting Deadlines: Prioritizing the earliest deadline minimizes the chance of any task missing its
deadline.
Optimal Utilization: Maximizes CPU utilization by keeping the processor busy as long as there's a task
with an active deadline, minimizing idle time.
4/7
Module6_RTOS_Notes.md 2026-07-26
Responsiveness: Provides fast scheduling/execution for time-critical tasks, improving overall system
performance.
Predictability: Scheduling decisions are deterministic and can be analyzed/predicted in advance —
important for real-time guarantees.
Flexibility: Handles both periodic and aperiodic tasks, and supports dynamic task creation without
disrupting tasks already running.
Disadvantages of EDF
Transient Overload Problem – if the system briefly gets overloaded with more work than it can handle,
EDF's guarantees can break down unpredictably.
Resource Sharing Problem – coordinating shared resources between tasks under EDF adds complexity.
Efficient Implementation Problem – achieving an efficient real-world implementation of EDF is non-
trivial.
Each task's priority is based on its period: shorter period → higher priority, longer period → lower
priority.
A task's period (and therefore its priority) does not change over time — this is what makes RM a static
priority scheme, unlike EDF's dynamic priorities.
RM is a preemptive algorithm: if a task with a shorter period becomes ready during execution, it gains
higher priority and can preempt (block) whatever lower-priority task is currently running.
In short: priority is inversely proportional to the time period — smallest period = highest priority.
Worked Example
Task Release Time (rᵢ) Execution Time (Cᵢ) Deadline (Dᵢ) Period (Tᵢ)
T1 0 0.5 3 3
T2 0 1 4 4
T3 0 2 6 6
Since utilization (0.75) is less than 1 (100%), the task set is schedulable under Rate Monotonic scheduling.
Execution Walkthrough:
At t = 0, all three tasks are released. T1 has the highest priority, so it runs first, until t = 0.5.
5/7
Module6_RTOS_Notes.md 2026-07-26
At t = 0.5, T2 has higher priority than T3, so T2 runs next, until t = 1.5. After that, only T3 remains, so it
starts running, continuing to t = 3.
At t = 3, T1 is released again; since it has higher priority than T3, it preempts T3 and runs until t = 3.5
— then T3 resumes its remaining work.
At t = 4, T2 is released again and completes its execution immediately since nothing else is running at
that moment.
At t = 6, both T1 and T3 are released simultaneously; T1 (shorter period) preempts T3 and runs until t =
6.5, after which T3 resumes and runs until t = 8.
At t = 8, T2 (higher priority than T3) is released, preempting T3 and starting its execution.
At t = 9, T1 is released again, preempts T3, executes first, and then at t = 9.5, T3 executes its remaining
part.
This cyclic preemption pattern continues indefinitely, following the same priority rules.
Advantages of RM
Easy to implement.
Optimal among static priority algorithms — if any static-priority assignment can meet all deadlines
for a task set, RM can meet them too.
Uses a properly calculated allocation of time periods, unlike simpler time-sharing algorithms (like
Round Robin) which ignore each process's actual scheduling needs.
Disadvantages of RM
Very difficult to support aperiodic and sporadic tasks (tasks that don't arrive on a strict, predictable
schedule).
Not optimal when a task's period and deadline differ — RM's guarantees assume deadline = period,
and performance suffers when that assumption breaks.
6/7
Module6_RTOS_Notes.md 2026-07-26
Note: Your syllabus for this module also lists Linux OS and Mobile OS as topics, but the uploaded slide deck
doesn't cover them — happy to put together notes on those (e.g., via GeeksforGeeks, like the earlier modules)
if you'd like them added.
Source basis: content extracted from the uploaded [Link], reorganized and simplified for study purposes.
7/7