Vault Notes

Operating Systems

Subject 2 of 10 Β· from what an OS does to how disks are scheduled, with the formulas and algorithms that show up on exams.

1. OS Basics

Functions of an operating system

CPU utilization under multiprogrammingCPU utilization = 1 βˆ’ Pn
P = probability a process waits on I/O, n = degree of multiprogramming

Example: each process spends 80% of its time waiting on I/O (P = 0.8) with 3 processes in memory: utilization = 1 βˆ’ 0.8Β³ = 1 βˆ’ 0.512 β‰ˆ 49%. Add more processes and utilization climbs β€” until thrashing (chapter 7) ruins it.

Security goals: the CIA triad

GoalMeaning
ConfidentialityOnly authorized users can read the data
IntegrityData can't be modified by unauthorized users
AvailabilityThe system stays up for legitimate users

Authentication verifies who you are (passwords, biometrics). Authorization decides what you're allowed to do once inside.

Classic security threats

ThreatWhat it is
Trojan HorseLooks like useful software, hides a malicious payload
Trapdoor / BackdoorSecret entry point that bypasses authentication
Logic BombMalicious code that triggers on a specific date or condition
VirusNeeds a host program; replicates when the host runs
WormStandalone; self-replicates across networks without a host

2. Processes & Threads

Program vs process

A program is a passive entity on disk. A process is a program in execution β€” an active entity with its own address space and system state.

Process memory layout

SectionHolds
TextThe program's code (read-only)
DataGlobal and static variables
HeapDynamically allocated memory (grows upward)
StackFunction calls, local variables (grows downward)

Process Control Block (PCB)

The OS's file on every process: process ID (PID), parent PID, current state, program counter, CPU register snapshot, scheduling info (priority), accounting info (CPU time used), memory-management info, I/O status, and the list of open files.

Process states

New β†’ Ready β†’ Running β†’ Terminated, with a detour: a running process that waits on I/O goes to Waiting, then back to Ready when the I/O completes. Suspended variants (suspend-ready, suspend-waiting) exist when the OS swaps processes out to disk.

Context switching

Switching the CPU from one process to another: save the old process's registers and program counter into its PCB, load the next process's state. It's pure overhead β€” the CPU does no useful work during the switch β€” which is why dispatch latency matters.

Threads

A thread is a lightweight process: it shares the address space, code, data, and open files with its sibling threads, carrying only its own stack, registers, and program counter. Benefits of multithreading: responsiveness (UI stays alive during long work), resource sharing, economy (creating a thread is far cheaper than a process), and scalability across cores.

AspectUser-level threadsKernel-level threads
Managed byThread library in user spaceThe OS kernel
Context switchFast β€” no kernel trapSlower β€” kernel involved
BlockingOne thread blocks, all blockOne thread blocks, rest continue

Multithreading models

ModelMappingTrade-off
Many-to-OneMany user β†’ one kernel threadEfficient, but one blocking call stalls everything
One-to-OneEach user β†’ its own kernel threadTrue concurrency, but creating threads costs more
Many-to-ManyMultiplexedBest of both; the OS can run the right number of kernel threads

Inter-Process Communication (IPC)

3. CPU Scheduling

The short-term scheduler picks which ready process gets the CPU next. The dispatcher performs the actual handoff; dispatch latency is the time a switch takes.

Scheduling criteria

CriterionGoal
CPU utilizationKeep the CPU as busy as possible
ThroughputMaximize processes completed per unit time
Turnaround timeMinimize submission β†’ completion
Waiting timeMinimize time spent in the ready queue
Response timeMinimize submission β†’ first response (interactive systems)

The algorithms

AlgorithmPreemptive?How it picks
FCFSNoFirst come, first served β€” simple, but convoy effect
SJFNoShortest burst first β€” optimal avg waiting time, can starve long jobs
SRTFYesPreemptive SJF β€” picks shortest remaining time
PriorityBothHighest priority first β€” starvation fixed with aging
Round RobinYesFixed time quantum per process, cyclically β€” the time-sharing workhorse
Multilevel QueueYesSeparate queues per class (foreground/background), fixed priority between queues
Multilevel Feedback QueueYesProcesses move between queues based on behavior β€” the most general scheme
Round Robin tuning

Quantum too large β†’ degenerates to FCFS. Too small β†’ context-switch overhead eats the CPU. A common rule of thumb: quantum long enough that 80% of bursts finish within one slice.

Queues and schedulers

4. Process Synchronization

When processes share data, the critical section β€” the code touching shared state β€” needs guarding. Any correct solution must provide:

Peterson's solution (two processes)

A pure-software solution using a flag[2] array (who wants in) and a turn variable (whose turn it is). It satisfies all three requirements but only works for two processes and assumes atomic loads/stores.

// process i (j is the other)
flag[i] = true;
turn = j;
while (flag[j] && turn == j) ;  // busy wait
// --- critical section ---
flag[i] = false;
// --- remainder ---

Hardware support: Test-and-Set

boolean TestAndSet(boolean *lock) {
    boolean old = *lock;
    *lock = true;      // executed atomically
    return old;
}
// usage: while (TestAndSet(&lock)) ; // critical section; lock = false;

Semaphores

An integer variable touched only through two atomic operations: wait() (P β€” decrement, block if zero) and signal() (V β€” increment, wake a waiter).

Mutex locks vs spinlocks

A mutex is acquire/release around the critical section. A spinlock is a mutex that busy-waits instead of sleeping β€” wasteful on single-core, but the fastest option for very short critical sections on multicore.

Monitors

A high-level construct: only one process may be active inside a monitor at a time, enforced by the compiler/runtime. Condition variables (wait/signal) let processes sleep inside until some condition holds β€” the classic bounded-buffer implementation.

Classic synchronization problems

ProblemSetupKey idea
Producer–ConsumerBounded buffer between producer and consumerSemaphores empty, full, and mutex
Readers–WritersMany readers OK together; writers need exclusivityFirst reader locks out writers; variants favor readers or writers
Dining Philosophers5 philosophers, 5 chopsticks, one between each pairNaive pickup deadlocks β€” fix with ordering or an asymmetric pickup rule

5. Deadlocks

A deadlock is a standstill: each process in a set waits for a resource held by another process in the set, and nobody can move. All four conditions must hold simultaneously:

#ConditionMeaning
1Mutual exclusionAt least one resource is non-sharable
2Hold and waitA process holds resources while waiting for more
3No preemptionResources can't be forcibly taken away
4Circular waitP1 waits on P2, P2 waits on P3, …, Pn waits on P1

Resource Allocation Graph (RAG)

Processes are circles, resource types are squares. A request edge P→R means "waiting for"; an assignment edge R→P means "holding". With single-instance resources, a cycle in the graph is a deadlock; with multiple instances, a cycle only means deadlock might exist.

Handling strategies

Exam favorite

Prevention negates a condition statically. Avoidance dynamically checks each allocation. Detection does nothing until a deadlock actually forms.

6. Memory Management

The CPU generates logical addresses; RAM speaks physical addresses. The MMU translates between them at runtime, which is what lets every process believe it owns contiguous memory starting at zero.

Contiguous allocation

Each process gets one unbroken block of memory. Simple, but suffers external fragmentation β€” free memory scattered in holes too small to use. Classic placement policies:

PolicyChoosesTrade-off
First FitThe first hole big enoughFast; litters small holes at the front
Best FitThe smallest hole big enoughLeast waste per pick, but slowest search
Worst FitThe largest holeLeaves big leftovers; rarely the winner

Partitioning

Internal vs external fragmentation

Internal = wasted space inside an allocated block (you got more than you asked for). External = wasted space between blocks (enough total free memory, but no single hole fits).

Paging

Memory is chopped into fixed-size frames; each process is chopped into same-size pages. Pages land in any free frames β€” no contiguity needed, so external fragmentation disappears. A page table maps page β†’ frame per process.

Segmentation

Memory is divided by logical meaning β€” code, data, stack segments of variable size β€” matching how programmers think. Each segment gets a base + limit in a segment table.

PagingSegmentation
DivisionFixed-size, physicalVariable-size, logical
FragmentationInternal (last page)External (variable holes)
Programmer visibilityInvisibleVisible β€” matches program structure

7. Virtual Memory

Virtual memory lets processes use more memory than physically exists: only the pages actually needed live in RAM, the rest wait on disk. Benefits: larger effective address spaces, higher multiprogramming, less I/O per process.

Demand paging

Pages are loaded only on first use β€” a page fault triggers the load. A valid/invalid bit in the page table marks which pages are resident. Pure demand paging starts with nothing loaded; locality keeps fault rates low after warmup.

Page replacement

When RAM is full and a fault needs a frame, pick a victim page:

AlgorithmVictim =Notes
FIFOOldest loaded pageSimple; can suffer Belady's anomaly (more frames β†’ more faults!)
OptimalPage used farthest in the futureTheoretical lower bound β€” impossible in practice, used as benchmark
LRULeast recently usedExcellent approximation of Optimal; needs timestamp or stack hardware
Clock / Second-chanceFIFO with a reference bitCheap LRU approximation used in real systems
LFU / MFULeast / most frequently usedCounting-based; rarely used alone
Effective Access Time with a TLBEAT = hit Γ— (TLB + mem) + miss Γ— (TLB + 2 Γ— mem)
A TLB miss costs an extra memory lookup for the page table itself.

Thrashing

When the degree of multiprogramming is too high, processes spend all their time page-faulting instead of executing β€” CPU utilization collapses even though everyone is "busy". Fixes: reduce multiprogramming, give processes bigger working sets, add RAM. The working-set model tracks each process's current locality to size allocations correctly.

8. File Systems

File concepts and attributes

A file is a named collection of related data on secondary storage. Its metadata: name, type, size, location on disk, protection/permissions, owner, and timestamps.

Allocation methods

MethodHow it storesStrengths / weaknesses
ContiguousOne unbroken run of blocksFast sequential + direct access; external fragmentation
LinkedBlocks chained with pointersNo fragmentation; terrible random access
IndexedAn index block lists all data blocksDirect access without fragmentation; index overhead

Free-space management

9. Disk Scheduling

Disk access timeAccess time = seek time + rotational delay + transfer time
Avg rotational delay = half a revolution (e.g. 7200 RPM β†’ 8.33 ms/rev β†’ 4.17 ms avg)

Seek time dominates for random access; rotational delay matters most for sequential access. Example: seek 6 ms + rotational 4.17 ms + transfer 0.5 ms = 10.67 ms per access.

The algorithms

AlgorithmHead behaviorNotes
FCFSServices in arrival orderFair; wild seeks, no optimization
SSTFNearest request firstGood throughput; edge requests can starve
SCAN (elevator)Sweeps to the disk end, then reversesNo starvation; fairer than SSTF
C-SCANSweeps one direction only, jumps backUniform wait times; the return trip is pure overhead
LOOKLike SCAN, but reverses at the last requestSkips pointless travel to empty disk edges

Worked example β€” requests at tracks 98, 183, 37, 122, 14, 124, 65, 67, head at 53 moving outward: SCAN services 65 β†’ 67 β†’ 98 β†’ 122 β†’ 124 β†’ 183, then reverses to 37 β†’ 14. C-SCAN instead jumps straight back to 0 after 183 and continues 14 β†’ 37. LOOK would reverse at 183 without ever visiting the disk edge.

← Back to all subjects