UNIT 4: Operating Systems Short Notes
I. Introduction to Operating Systems
Evolution of Operating Systems
-
Batch Systems: Jobs submitted on punch cards, no interaction, sequential processing.
-
Multiprogramming: Multiple jobs in memory, CPU switches when one waits (e.g., I/O), improves utilization.
-
Time-Sharing: Multiple users interact via terminals, CPU time sliced (quantum), illusion of dedicated system.
-
Personal OS: Single-user, GUI-based (e.g., early Windows, MacOS).
-
Network OS: Provides file/print sharing over LAN, client-server model.
-
Distributed OS: Multiple autonomous computers appear as single system, resources shared via network.
Functions and Services Provided by OS
| Category | Services |
|---|---|
| Process Management | Create/terminate processes, scheduling, synchronization, deadlock handling |
| Memory Management | Allocation/deallocation, protection, sharing, virtual memory |
| File Management | Create/delete files/directories, mapping to storage, access control |
| I/O Management | Device drivers, buffering, caching, device independence |
| Protection & Security | Access control, authentication, encryption |
| Other Services | System calls interface, error detection, accounting, command interpretation |
Characteristics of Operating Systems
-
Convenience: Makes system easier to use.
-
Efficiency: Optimizes resource use (CPU, memory, I/O).
-
Ability to Evolve: Supports new hardware/software.
-
Managed Resource Allocation: Fair sharing among processes/users.
-
Easy to Use: Abstraction, user-friendly interfaces.
OS Structures
-
Layered Approach: OS divided into layers (hardware at bottom, UI at top). Each layer uses only lower layers. Simple but inefficient.
-
Microkernel: Minimal kernel (memory management, process scheduling, IPC). Other services (file systems, drivers) run in user space. More secure, modular, but performance overhead due to IPC.
-
Modular (Loadable Modules): Kernel composed of modules loaded dynamically. Linux uses this.
-
Process-Based Kernel: Kernel as set of processes, some run in kernel mode for protection.
System Calls
Interface between user programs and OS kernel. Types:
-
Process Control:
fork(),exec(),exit(),wait(),getpid(). -
File Management:
open(),close(),read(),write(),lseek(). -
Device Management:
ioctl(),read(),write()(device files). -
Information Maintenance:
time(),stat(),getrusage(). -
Communication:
pipe(),shmget(),msgget()(IPC). -
Protection:
chmod(),chown(),umask().
Utility Programs
-
Loaders: Load executable into memory.
-
Linkers: Combine object files into executable (resolve symbols).
-
Debuggers: Test and debug programs (e.g.,
gdb). -
System Monitors: Performance monitoring (CPU, memory usage).
II. Process Management
Process Concept and PCB
-
Process: Program in execution; an active entity.
-
Process Control Block (PCB): OS data structure storing process information.
- Fields: Process state, program counter, CPU registers, memory management info (page tables), I/O status, accounting info, scheduling info (priority, pointers to queues).
Process States and Transition Diagram
-
New: Process being created.
-
Ready: Waiting for CPU.
-
Running: Executing on CPU.
-
Waiting/Blocked: Waiting for I/O or event.
-
Terminated: Process completed.
New → Ready → Running → Waiting → Ready → Terminated
↑ ↓
└─────────┘ (context switch)
Scheduling Queues and Schedulers
-
Job Queue: All processes in system.
-
Ready Queue: Processes ready to run.
-
Device Queues: Processes waiting for I/O.
-
Schedulers:
-
Long-term (Job Scheduler): Selects processes from job queue to admit to ready queue (controls degree of multiprogramming).
-
Short-term (CPU Scheduler): Selects process from ready queue to run on CPU (frequent, fast).
-
Medium-term (Swapper): Removes processes from memory to reduce multiprogramming (swapping).
-
System Calls for Process Management
-
fork(): Creates child process (duplicate of parent). -
exec(): Replaces process memory space with new program. -
wait(): Parent waits for child termination. -
exit(): Terminates process. -
getpid(): Returns process ID. -
nice(): Adjusts priority.
Threads
-
Thread: Basic unit of CPU utilization; lightweight process within same address space.
-
Benefits: Responsiveness, resource sharing, economy (less overhead than process creation), scalability (parallelism on multiprocessors).
User-Level Threads
-
Implementation: Managed by user-space thread library; kernel unaware.
-
Advantages: Fast creation/switch (no kernel mode), portable.
-
Disadvantages: One blocking thread blocks all (no true parallelism), kernel schedules entire process.
Kernel-Level Threads
-
Implementation: Managed by OS kernel; each thread has kernel data structure.
-
Advantages: True parallelism on multiprocessors, one thread block doesn’t block others.
-
Disadvantages: Slower creation/switch (kernel mode), overhead.
Comparison: User vs Kernel Threads
| Aspect | User-Level | Kernel-Level |
|---|---|---|
| Management | User-space library | OS kernel |
| Creation/Switch | Fast (no syscall) | Slow (syscall) |
| Blocking | Entire process blocks | Individual thread blocks |
| Parallelism | No (on multiprocessor) | Yes |
| Scheduling | User-controlled | Kernel-controlled |
| Examples | POSIX Pthreads (user), Java threads | Windows, Linux |
Concurrency: Real vs Virtual
-
Real Concurrency: Multiple processors/cores executing simultaneously (true parallelism).
-
Virtual Concurrency: Single processor time-slicing, giving illusion of concurrency.
III. CPU Scheduling
Scheduling Criteria
-
CPU Utilization: % time CPU busy (aim for 40-90%).
-
Throughput: # processes completed per unit time.
-
Turnaround Time: Completion time – arrival time.
-
Waiting Time: Total time spent in ready queue (turnaround – burst time).
-
Response Time: First response – arrival time (for time-sharing).
Scheduling Algorithms
First-Come-First-Served (FCFS)
-
Non-preemptive; processes run to completion.
-
Gantt Chart: Order of arrival.
-
Disadvantage: Convoy effect (long job delays short ones).
-
Example:
Processes: P1(10), P2(1), P3(2) all at 0.
Gantt: P1(0-10), P2(10-11), P3(11-13).
Avg Waiting = (0 + 10 + 11)/3 = 7 units.
Shortest Job First (SJF) / Shortest Remaining Time First (SRTF)
-
SJF: Non-preemptive; select process with shortest burst.
-
SRTF: Preemptive; select process with shortest remaining time.
-
Optimal for average waiting time.
-
Disadvantage: Starvation for long jobs.
-
Example (SJF):
P1(10,0), P2(1,1), P3(2,2).
At t=0, P1 runs. At t=1, P2 arrives (burst 1 < remaining 9), so P1 preempted? For non-preemptive SJF, P1 continues. For SRTF, P2 runs at t=1.
SRTF Gantt: P1(0-1), P2(1-2), P3(2-4), P1(4-14).
Avg Waiting = (0 + 0 + 0 + 3)/3? Wait, processes: P1 wait= (2-1)+(4-14?) Actually recalc properly.
Priority Scheduling
-
Each process has priority; higher priority runs first.
-
Preemptive: New higher priority preempts current.
-
Non-preemptive: Run to completion.
-
Disadvantage: Starvation of low-priority; solution: aging (increase priority over time).
-
Example (Nov 2023):
P1(10,3), P2(1,1), P3(2,3), P4(1,4), P5(5,2) all at 0.
Non-preemptive: Order by priority: P2(1), P5(5), P1(10) and P3(2) same priority? Assume lower number = higher priority.
Priority: P2(1), P5(2), P1(3), P3(3), P4(4).
Gantt: P2(0-1), P5(1-6), P1(6-16), P3(16-18), P4(18-19).
Turnaround: P1=16, P2=1, P3=16, P4=18, P5=6. Avg = (16+1+16+18+6)/5 = 11.4.
Round Robin (RR)
-
Preemptive; each process gets time quantum (q).
-
Ready queue circular; if burst > q, requeued.
-
Gantt Chart: Cyclic with q intervals.
-
Trade-off: q large → FCFS; q small → more context switches.
-
Example (Jun 2022):
Processes: P1(10), P2(29), P3(3), P4(7), q=10.
Gantt: P1(0-10), P2(10-20), P3(20-23), P4(23-30), P2(30-40), P1(40-50? P1 done), P2(50-60), P4? Actually P4 done at 30, so next P2(30-40), then P2 remaining 9? P2 burst 29, after 20, remaining 9, so at 30-39, then P2 done? Let's compute properly.
Gantt Charts and Metrics
-
Turnaround Time = Completion Time – Arrival Time.
-
Waiting Time = Turnaround Time – Burst Time.
-
Response Time = First CPU allocation – Arrival Time.
IV. Synchronization
Critical Section Problem
-
Critical Section: Code segment accessing shared resource.
-
Requirements:
-
Mutual Exclusion: Only one process in CS at a time.
-
Progress: If no process in CS and others want to enter, decision in finite time.
-
Bounded Wait: Limit on number of times other processes enter after request.
-
Software Solution: Peterson’s Algorithm
For two processes (P0, P1):
int turn = 0; // shared
bool flag[2] = {false, false};
// P0:
flag[0] = true;
turn = 1;
while (flag[1] && turn == 1) ; // wait
// critical section
flag[0] = false;
// P1:
flag[1] = true;
turn = 0;
while (flag[0] && turn == 0) ; // wait
// critical section
flag[1] = false;
Note: Works only for two processes; assumes sequential consistency.
Hardware Support
-
Test-and-Set: Atomic; returns old value and sets to true.
bool test_and_set(bool *lock) { bool old = *lock; *lock = true; return old; } -
Compare-and-Swap (CAS): Atomic; compare memory with expected, swap if equal.
int compare_and_swap(int *value, int expected, int new) { int temp = *value; if (*value == expected) *value = new; return temp; }
Semaphores
-
Integer variable accessed atomically via
wait()(P) andsignal()(V). -
Binary Semaphore: 0 or 1; for mutual exclusion.
-
Counting Semaphore: ≥0; for resource counting.
-
Operations:
-
wait(S): while S ≤ 0; S--. -
signal(S): S++.
-
-
Implementation: Must be atomic; disable interrupts or use hardware instructions.
Monitors
-
High-level synchronization construct; combines mutual exclusion and condition variables.
-
Condition Variables:
wait()(releases monitor lock and blocks),signal()(wakes one waiting process). -
Usage: Only one process active in monitor at a time.
-
Dining Philosophers with Monitor:
monitor DiningPhilosophers { enum {THINKING, HUNGRY, EATING} state[5]; condition self[5]; void pickup(int i) { state[i] = HUNGRY; test(i); if (state[i] != EATING) self[i].wait(); } void putdown(int i) { state[i] = THINKING; test((i+4)%5); test((i+1)%5); } void test(int i) { if (state[(i+4)%5] != EATING && state[i]==HUNGRY && state[(i+1)%5]!=EATING) { state[i] = EATING; self[i].signal(); } } initialization() { for i=0 to 4: state[i]=THINKING; } }
Classic Synchronization Problems
Producer-Consumer Problem
-
With Semaphores:
semaphore empty = N, full = 0, mutex = 1; // Producer: while (true) { produce_item(); wait(empty); wait(mutex); add_to_buffer(); signal(mutex); signal(full); } // Consumer: while (true) { wait(full); wait(mutex); remove_from_buffer(); signal(mutex); signal(empty); consume_item(); } -
With Monitors: Use condition variables
notFull,notEmpty.
Reader-Writer Problem
-
Readers Priority:
int readcount = 0; semaphore mutex = 1, wrt = 1; // Reader: wait(mutex); readcount++; if (readcount == 1) wait(wrt); signal(mutex); // read wait(mutex); readcount--; if (readcount == 0) signal(wrt); signal(mutex); // Writer: wait(wrt); // write signal(wrt); -
Writers Priority: Add turnstile to prevent writer starvation.
Dining Philosophers Problem
-
With Semaphores:
semaphore chopstick[5] = {1,1,1,1,1}; // Philosopher i: while (true) { think(); wait(chopstick[i]); wait(chopstick[(i+1)%5]); eat(); signal(chopstick[i]); signal(chopstick[(i+1)%5]); }Deadlock possible if all pick left simultaneously. Solution: limit to 4 philosophers, or pick both only if both available (using
mutex).
V. Deadlocks
Definition and System Model
-
Deadlock: Set of processes blocked; each waiting for resource held by another in set.
-
System Model: Processes request/release resources; resources have instances.
Necessary Conditions (Coffman Conditions)
-
Mutual Exclusion: Only one process uses resource at a time.
-
Hold and Wait: Process holds resources while waiting for others.
-
No Preemption: Resources cannot be forcibly taken.
-
Circular Wait: Circular chain of processes waiting for each other’s resources.
Deadlock Handling Methods
Prevention
Break one condition:
-
Mutual Exclusion: Not always possible (printers).
-
Hold and Wait: Require all resources at start, or release held before requesting new.
-
No Preemption: Preempt resources if request denied (only if state can be saved/restored).
-
Circular Wait: Impose total ordering on resources; request in increasing order.
Avoidance
-
Banker’s Algorithm: Ensure system never enters unsafe state.
-
Need Matrix = Max – Allocation.
-
Safe State Check: Find sequence where each process’s need ≤ available; if found, safe.
-
Request Granting: If request ≤ need and ≤ available, pretend allocate and check safe.
-
-
Resource Allocation Graph (RAG): For single instance; cycle → deadlock.
Detection and Recovery
-
Detection:
-
RAG for multiple instances: Look for cycles? Not sufficient; use algorithm similar to Banker’s (find deadlocked processes).
-
Algorithm: Find process whose request ≤ work; if none, deadlocked set.
-
-
Recovery:
-
Process Termination: Terminate all deadlocked processes or one by one.
-
Resource Preemption: Select victim process, rollback to safe state (checkpointing).
-
Banker’s Algorithm Example (Jun 2022)
Given:
| Process | Allocation (A B C D) | Max (A B C D) | Available (A B C D) |
|---|---|---|---|
| P0 | 0 0 1 2 | 0 0 1 2 | 1 5 2 0 |
| P1 | 1 0 0 1 | 7 5 0 0 | |
| P2 | 1 3 5 4 | 2 3 5 6 | |
| P3 | 0 6 3 2 | 0 6 5 2 | |
| P4 | 0 0 1 4 | 0 6 5 6 |
-
Need Matrix:
-
P0: (0-0, 0-0, 1-1, 2-2) = (0,0,0,0)
-
P1: (7-1,5-0,0-0,0-1) = (6,5,0,1)
-
P2: (2-1,3-3,5-5,6-4) = (1,0,0,2)
-
P3: (0-0,6-6,5-3,2-2) = (0,0,2,0)
-
P4: (0-0,6-0,5-1,6-4) = (0,6,4,2)
-
-
Safe State Check:
-
Work = Available = (1,5,2,0)
-
Find process with Need ≤ Work: P0 (0,0,0,0) ≤ (1,5,2,0) → Yes. Work += Allocation(P0) = (1,5,2,0)+(0,0,1,2)=(1,5,3,2). Safe sequence: P0.
-
Next: P2 (1,0,0,2) ≤ (1,5,3,2) → Yes. Work = (1,5,3,2)+(1,3,5,4)=(2,8,8,6). Sequence: P0,P2.
-
Next: P1 (6,5,0,1) ≤ (2,8,8,6)? No. P3 (0,0,2,0) ≤ Yes. Work = (2,8,8,6)+(0,6,3,2)=(2,14,11,8). Sequence: P0,P2,P3.
-
Next: P1 (6,5,0,1) ≤ (2,14,11,8)? No. P4 (0,6,4,2) ≤ Yes. Work = (2,14,11,8)+(0,0,1,4)=(2,14,12,12). Sequence: P0,P2,P3,P4.
-
Next: P1 (6,5,0,1) ≤ (2,14,12,12)? No. But all others done? P1 not finished. Actually after P4, work=(2,14,12,12). P1 need=(6,5,0,1) not ≤ work because 6>2. So not safe? Wait recalc: after P3, work=(2,14,11,8). P4 need=(0,6,4,2) ≤ yes, so work becomes (2,14,12,12). Then P1 need=(6,5,0,1) ≤ (2,14,12,12)? 6>2 false. So no safe sequence? But in problem, likely safe. Check P2 allocation: (1,3,5,4) so work after P2: initial (1,5,2,0) + (1,3,5,4) = (2,8,7,4)? I miscalculated: Allocation P0=(0,0,1,2), so after P0: work=(1,5,2,0)+(0,0,1,2)=(1,5,3,2). After P2: work=(1,5,3,2)+(1,3,5,4)=(2,8,8,6). After P3: work=(2,8,8,6)+(0,6,3,2)=(2,14,11,8). After P4: work=(2,14,11,8)+(0,0,1,4)=(2,14,12,12). Then P1 need=(6,5,0,1) not ≤ (2,14,12,12). So not safe? But maybe order different. Try P0, P3, P2, P4, P1? After P0: (1,5,3,2). P3 need=(0,0,2,0) ≤ yes → work=(1,5,3,2)+(0,6,3,2)=(1,11,6,4). Then P2 need=(1,0,0,2) ≤ (1,11,6,4) yes → work=(1,11,6,4)+(1,3,5,4)=(2,14,11,8). Then P4 need=(0,6,4,2) ≤ yes → work=(2,14,12,12). Then P1 need=(6,5,0,1) not ≤. Still not. Maybe P0, P2, P4, P3, P1? After P0: (1,5,3,2). P2: (2,8,8,6). P4: (2,8,8,6)+(0,0,1,4)=(2,8,9,10). P3: need=(0,0,2,0) ≤ (2,8,9,10) yes → work=(2,8,9,10)+(0,6,3,2)=(2,14,12,12). Then P1 no. So not safe? But in exam question, likely safe. Check P1 max: (7,5,0,0), allocation (1,0,0,1), so need (6,5,0,1). Available (1,5,2,0). So P1 cannot finish because need 6A but only 1A available. So system not safe. For Nov 2023 question, they asked if safe? Answer: No.
-
-
Request from P1 for (0,4,2,0):
- Request ≤ Need? (0,4,2,0) ≤ (6,5,0,1)? 2>0 false → cannot grant.
VI. Memory Management
Memory Management Requirements
-
Relocation: Process can move in memory (dynamic relocation via base/limit or paging).
-
Protection: Prevent process from accessing others’ memory.
-
Sharing: Allow multiple processes to access same memory (code, data).
-
Logical vs Physical Organization: Programs use logical addresses; OS maps to physical.
Contiguous Memory Allocation
-
Single Partition: Base and limit registers; OS in low memory.
-
Multiple Partition:
-
Fixed Partitioning: Equal or unequal sizes; internal fragmentation.
-
Variable Partitioning: Allocate exact size; external fragmentation.
-
-
Allocation Algorithms:
| Algorithm | Method | Advantage | Disadvantage | |---------------|-------------|---------------|------------------| | First Fit | First block ≥ size | Fast | External fragmentation | | Best Fit | Smallest block ≥ size | Less waste | Slow, more fragmentation | | Worst Fit | Largest block | More leftover for others | High fragmentation |
-
Fragmentation:
-
Internal: Unused space within allocated block (fixed partitions).
-
External: Small holes between allocated blocks (variable partitions).
-
Paging
-
Basic Concept: Divide memory into fixed-size frames (physical) and pages (logical). Page table maps page → frame.
-
Address Translation: Logical address = page number + offset. Physical = frame number + offset.
-
Page Table Structure: One entry per page; contains frame number, valid/invalid bit, protection bits.
-
Translation Lookaside Buffer (TLB): Cache of recent page translations; speeds up translation (hit ratio important).
-
Protection and Sharing: Valid-invalid bit; share pages by mapping same frame in multiple page tables.
-
Hierarchical Paging: Multi-level page tables (e.g., two-level: outer page table points to inner page tables). Reduces memory for large address spaces.
-
Hashed Page Tables: For >32-bit addresses; hash page number to bucket, chain of entries.
-
Inverted Page Table: One entry per physical frame; stores (process ID, logical page). Saves memory but slower lookup (search entire table).
Segmentation
-
Basic Concept: Memory divided into variable-size segments (logical units: code, data, stack). Each segment has segment number and offset.
-
Segment Table: Entry contains base physical address, limit (segment length), protection bits.
-
Hardware Support: Segment number from logical address; offset checked against limit.
-
Segmentation with Paging (Paged Segmentation): Each segment paged; combines benefits. Segment table points to page tables.
-
Comparison with Paging:
| Aspect | Paging | Segmentation | |------------|------------|------------------| | View | Physical (user unaware) | Logical (user visible) | | Size | Fixed | Variable | | Fragmentation | Internal | External | | Sharing | Page-level | Segment-level (natural) | | Protection | Page-level | Segment-level (more meaningful) |
Virtual Memory and Demand Paging
-
Concept: Only needed pages in memory; rest on disk. Allows larger address spaces.
-
Page Fault: Access to page not in memory; OS loads from disk.
-
Thrashing: High page fault rate; CPU spends more time paging than executing. Caused by under-allocation of frames or high locality.
-
Working Set: Set of pages recently used by process. If working set > allocated frames → thrashing.
-
Demand Paging Implementation:
-
Valid-invalid bit in page table: valid = in memory, invalid = not.
-
Page Fault Handling:
-
Trap to OS.
-
Check page table entry; if invalid, locate page on disk.
-
Find free frame (if none, use replacement algorithm).
-
Read page from disk to frame (scheduling I/O).
-
Update page table and TLB.
-
Restart instruction.
-
-
Page Replacement Algorithms
-
FIFO (First-In-First-Out):
-
Replace oldest page.
-
Belady’s Anomaly: More frames → more page faults for some reference strings.
-
Example: Reference string 1,2,3,4,1,2,5,1,2,3,4,5 with 3 frames vs 4 frames.
-
-
LRU (Least Recently Used):
-
Replace page not used for longest time.
-
Implemented with counter or stack; approximations: reference bits, second chance.
-
-
OPT (Optimal):
-
Replace page not used for longest time in future.
-
Not implementable (requires future knowledge); used for comparison.
-
Frame Allocation
-
Fixed Allocation: Equal frames per process (unfair) or proportional to size.
-
Variable Allocation: Adjust frames based on behavior (working set model).
Memory Management in UNIX and Windows
| Aspect | UNIX | Windows |
|---|---|---|
| Memory Organization | Paging with demand paging, swap space | Paging with demand paging, working set model |
| Page Table | Multi-level (e.g., 3-level on 64-bit) | Hierarchical (page directory, page tables) |
| Replacement | LRU approximation (clock algorithm) | Working set algorithm (per-process working set) |
| Shared Memory | Shared pages via same physical frame | Memory-mapped files, shared sections |
| Thrashing Control | Swap daemon adjusts allocation | Working set trimming |
VII. File Systems
File Concept
-
Attributes: Name, Identifier (inode number in UNIX), Type, Location, Size, Protection, Time (create, modify, access).
-
Operations: Create, Delete, Open, Close, Read, Write, Seek, Append, Truncate.
-
Types:
-
Regular: User data.
-
Directory: Mapping names to files.
-
Special/Device: Device files (character/block).
-
Access Methods
-
Sequential: Read sequentially from beginning.
-
Direct (Random): Access by record number (e.g.,
lseek). -
Indexed: Index block contains pointers to data blocks.
Directory Structure
| Structure | Description | Advantages | Disadvantages |
|---|---|---|---|
| Single-Level | All files in one directory | Simple | Name collisions, no grouping |
| Two-Level | User directories + master directory | No name collisions across users | No subdirectories |
| Tree-Structured | Hierarchical, paths | Flexible, no cycles | No file sharing |
| Acyclic-Graph | Shared files via links (hard/soft) | Sharing, no cycles | Hard links: same inode; soft links: separate file |
| General Graph | Cycles allowed with reference counts | Flexible sharing | Complex, garbage collection needed |
File System Structure and Modules
-
Virtual File System (VFS): Interface layer supporting multiple file systems (e.g., ext4, NTFS). Uses vnodes (inode-like).
-
Directory Management Module: Path resolution, directory operations.
-
Allocation and Free Space Management Module: Allocation methods (contiguous, linked, indexed), free space tracking.
-
I/O Control Module: Device drivers, buffering, caching.
File Allocation Methods
-
Contiguous Allocation:
-
Files stored in contiguous blocks.
-
Advantages: Fast sequential/direct access, simple.
-
Disadvantages: External fragmentation, file growth difficult.
-
-
Linked Allocation:
-
Each block points to next.
-
FAT (File Allocation Table): Table in memory stores next pointers; fast traversal but table size limits disk size.
-
Advantages: No external fragmentation, files can grow.
-
Disadvantages: Slow direct access, space for pointers, reliability (lost pointer → lost file).
-
-
Indexed Allocation:
-
Index block contains pointers to data blocks.
-
Single Indexing: Small files (direct pointers).
-
Multi-level Indexing: Larger files (indirect blocks). UNIX inode: 12 direct, 1 single indirect, 1 double indirect, 1 triple indirect.
-
Linked Indexing: Index blocks linked (e.g., FAT).
-
Advantages: No external fragmentation, fast direct access (if index in memory).
-
Disadvantages: Overhead for index blocks; large files need multi-level.
-
Free Space Management
-
Bit Vector (Bitmap): One bit per block; 1=free, 0=allocated. Compact, easy to find contiguous blocks.
-
Linked List: Free blocks linked together; each block stores list of free blocks. Wastes space.
-
Grouping: First free block stores addresses of many free blocks.
-
Counting: Store ranges of contiguous blocks (like FAT for free space).
File Protection
-
Access Control Lists (ACL): Per file, list of users/groups with permissions (rwx).
-
Capabilities: Token-based; process holds list of accessible objects with rights.
-
Encryption: File contents encrypted; key management.
File Systems in UNIX and Windows
| Aspect | UNIX (ext4) | Windows (NTFS) |
|---|---|---|
| Structure | Inode-based; inode stores metadata and block pointers | MFT (Master File Table) entries; similar to inode |
| Metadata | Inode: mode, links, owner, timestamps, block pointers | MFT: attributes (standard, filename, security descriptor) |
| Allocation | Extents (contiguous blocks) + indirect blocks | Clusters (contiguous), B+ trees for directories |
| Journaling | Optional (ext3/4 have journaling) | Mandatory (NTFS journaling) |
| Security | Permission bits (user/group/other), ACLs | ACLs, security descriptors, encryption (EFS) |
| Performance | Fast for small files, efficient disk use | Better for large files, robust recovery |
VIII. Disk Management
Disk Structure
-
Platter: Circular disk, two surfaces.
-
Track: concentric circle on surface.
-
Sector: Smallest addressable unit (typically 512B-4KB).
-
Cylinder: Set of tracks at same radius across platters.
-
Head: Read/write device per surface.
Disk Performance Parameters
-
Seek Time ($$\displaystyle T_s $$): Time to move head to target track. Depends on distance; average seek time given.
-
Rotational Latency ($$\displaystyle T_r $$): Time for sector to rotate under head. Average = $$\displaystyle \frac{1}{2} \times \text{rotation time} $$.
-
Transfer Time ($$\displaystyle T_t $$): Time to read/write sector. $$\displaystyle T_t = \frac{\text{sector size}}{\text{transfer rate}} $$.
-
Disk Bandwidth: Total bytes transferred per unit time (including overhead).
Disk Scheduling Algorithms
Goal: Minimize seek time.
| Algorithm | Description | Advantages | Disadvantages |
|---|---|---|---|
| FCFS | First request in queue | Fair, simple | High seek time |
| SSTF | Shortest seek time first | Reduces seek | Starvation, not optimal |
| SCAN (Elevator) | Head moves in one direction until end, then reverse | Fair, moderate seek | Long wait for requests behind |
| C-SCAN (Circular SCAN) | Head moves in one direction, then jumps to beginning | More uniform wait time | Ignores requests in reverse direction |
| LOOK | Like SCAN but only to last request (not end) | Saves seek | Similar to SCAN |
| C-LOOK | Like C-SCAN but only to last request | Saves seek | Similar to C-SCAN |
Example (Nov 2023):
Head at 143, previous 125, queue: 86,147,91,177,94,150,102,175,130.
FCFS: 143→86 (57), 86→147 (61), 147→91 (56), 91→177 (86), 177→94 (83), 94→150 (56), 150→102 (48), 102→175 (73), 175→130 (45). Total = 57+61+56+86+83+56+48+73+45 = 565 tracks.
Disk Management
-
Disk Formatting:
-
Physical Formatting (Low-level): Divide into sectors/tracks, mark bad sectors.
-
Logical Formatting (High-level): Create file system structures (boot block, superblock, inodes, data blocks).
-
-
Disk Mounting: Attach file system to directory tree (mount point). Unmounting detaches.
-
Swap Space Management: Reserved area for virtual memory; can be partition or file.
Disk Space Allocation
Linked to file allocation methods: contiguous, linked, indexed.
IX. I/O Systems
I/O Hardware
-
Devices: Input (keyboard, mouse), output (printer, display), storage (disk, tape).
-
Controllers: Interface between device and bus; has registers for commands/data.
-
Buses: Communication pathway (e.g., PCI, USB).
-
Ports: Connection points (I/O ports, memory-mapped I/O).
I/O Methods
-
Programmed I/O: CPU executes instructions for each byte/word transfer. Simple but CPU busy.
-
Interrupt-Driven I/O: CPU issues command, continues; device interrupts when ready. Better CPU utilization.
-
Direct Memory Access (DMA): DMA controller transfers data between device and memory without CPU; interrupt on completion. Best for large transfers.
I/O Software Layers
-
Interrupt Handlers: Service device interrupts; save context, handle, restore.
-
Device Drivers: Kernel modules specific to device; provide uniform interface.
-
Device-Independent I/O Software: Common functions (buffering, caching, error handling, allocation).
-
User-Space I/O Libraries: Standard I/O library (e.g.,
stdio.h), system call wrappers.
Kernel I/O Subsystem
-
I/O Scheduling: Order requests (similar to disk scheduling).
-
Buffering: Store data in memory to cope with speed mismatch.
-
Single Buffer: One buffer; CPU and I/O alternate.
-
Double Buffer: Two buffers; overlap I/O and CPU (e.g., input to buffer A while CPU processes buffer B).
-
Circular Buffer: Multiple buffers in ring; for streaming.
-
-
Caching: Keep copies of data in faster memory (e.g., disk cache).
-
Spooling: Hold output for slow devices (e.g., printer spooler).
-
Device Reservation: Exclusive access (e.g., tape drives).
-
Error Handling: Retry, fail, correct.
I/O Buffering Strategies
-
Input Buffering: Read ahead, store in buffer; process consumes.
-
Output Buffering: Accumulate output, write in chunks.
-
Double Buffering: Overlap I/O and computation.
Asynchronous vs Synchronous I/O
-
Synchronous I/O: Process blocks until I/O completes (e.g.,
read()returns when data in buffer). -
Asynchronous I/O: Process continues; notified via signal/callback when complete (e.g.,
aio_read()). -
Comparison:
| Aspect | Synchronous | Asynchronous | |------------|-----------------|------------------| | Blocking | Yes | No | | Complexity | Simple | Complex (callbacks, state) | | Concurrency | Low | High | | Use Case | Simple apps, sequential | High-performance servers |
I/O Management in UNIX and Windows
| Aspect | UNIX | Windows |
|---|---|---|
| Device Access | Device files in /dev (read/write/open) |
Device objects, handles, Win32 API |
| System Calls | read(), write(), ioctl() |
ReadFile(), WriteFile(), DeviceIoControl() |
| Drivers | Kernel modules, uniform interface | WDM (Windows Driver Model), layered drivers |
| Buffering | Kernel buffer cache, stdio library | System cache, I/O manager |
| Asynchronous I/O | aio_* calls, signals |
Overlapped I/O, I/O completion ports |
System Calls for File Management
-
open(path, flags, mode): Open file, return descriptor. -
close(fd): Close descriptor. -
read(fd, buf, count): Read bytes. -
write(fd, buf, count): Write bytes. -
lseek(fd, offset, whence): Move file offset. -
ioctl(fd, request, argp): Device-specific operations. -
stat(path, buf): Get file status. -
fstat(fd, buf): Get status via descriptor. -
chmod(path, mode): Change permissions. -
unlink(path): Delete file.
X. Protection and Security
Goals of Protection
-
Integrity: Data not modified improperly.
-
Confidentiality: Data not disclosed improperly.
-
Availability: Resources accessible when needed.
Protection Principles
-
Domain of Protection: Set of objects a process can access. Process executes in domain.
-
Access Control:
-
Access Matrix: Rows = domains, columns = objects, entries = rights (rwx). Sparse; implemented as ACLs or capabilities.
-
Access Control Lists (ACL): Per object, list of (user, rights). E.g., UNIX permission bits.
-
Capabilities: Per domain, list of (object, rights). Token-based; harder to revoke.
-
Security
-
Authentication: Verify identity.
- Passwords, biometrics (fingerprint), tokens (smart card).
-
Common Threats:
-
Viruses: Attach to programs, spread.
-
Worms: Network self-replicating.
-
Trojan Horses: Disguised malicious code.
-
Logic Bombs: Triggered by condition.
-
-
Attack Types:
- Intrusion (unauthorized access), DoS (denial-of-service), Masquerading (spoofing identity).
Security Mechanisms
-
Encryption:
-
Symmetric: Same key (AES, DES).
-
Asymmetric: Public/private keys (RSA).
-
-
Intrusion Detection Systems (IDS): Monitor for attacks (signature-based, anomaly-based).
-
Firewalls: Filter network traffic (packet filtering, application gateway).
-
Secure OS Design Principles:
- Least privilege, economy of mechanism, complete mediation, fail-safe defaults, separation of privilege, least common mechanism, etc.
XI. Advanced and Special Topics
Overlays
-
Concept: Load only required parts of program into memory; rest on disk. Overlay manager loads on demand.
-
Use: Execute programs larger than available memory. Manual or automatic (by compiler/loader).
-
Example: Program with modules A, B, C; A calls B, B calls C; but A and C never together. Load A, then B, then C over B when needed.
Dynamic Linking and Loading
-
Static Linking: Library code copied into executable at link time.
-
Dynamic Linking:
-
Load-time: Shared library loaded when executable starts.
-
Run-time: Library loaded on first function call (e.g.,
dlopen()).
-
-
Shared Libraries: Single copy in memory, multiple processes share (e.g.,
.so,.dll). -
Advantages: Saves memory, easier updates.
Distributed vs Multiprocessor OS
| Aspect | Distributed OS | Multiprocessor OS |
|---|---|---|
| Architecture | Network of independent computers | Multiple CPUs sharing memory/bus |
| Communication | Message passing (network) | Shared memory, buses |
| Fault Tolerance | High (fault isolation) | Low (single point of failure) |
| Scalability | High (add nodes) | Limited (bus/memory bandwidth) |
| Examples | Amoeba, Mach (cluster) | SMP Linux, Windows SMP |
Network Operating Systems (NOS)
-
Characteristics: File/print sharing, user/group management, communication services.
-
Services: SMB/CIFS (Windows), NFS (UNIX), directory services (LDAP).
Tape Organization
-
Sequential Access: Must wind through tape to reach data.
-
Structure: Tracks (parallel), blocks (records), gaps (between blocks).
-
Access Methods: Sequential read/write; indexing for faster access (tape directories).
Real and Virtual Concurrency
-
Real Concurrency: Multiple processors executing simultaneously (e.g., multi-core).
-
Virtual Concurrency: Single processor time-slicing; processes appear concurrent.
Virtual File Systems (VFS)
-
Interface: Abstract layer between kernel and concrete file systems.
-
Implementation: VFS inode (generic), file operations table (
read,write, etc.), superblock. -
Benefits: Supports multiple file systems uniformly; transparent to users.
Interrupt-Driven I/O
-
Operation:
-
CPU issues read/write command to device controller.
-
CPU continues other work.
-
Device completes operation, raises interrupt.
-
CPU saves context, jumps to interrupt handler.
-
Handler services interrupt (read data from controller, signal process).
-
CPU resumes.
-
-
Advantages: CPU not idle during I/O; better utilization than programmed I/O.
-
Disadvantages: Overhead of context switch per interrupt; mitigated with DMA.