Based on the book by Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau
Table of Contents
Introduction
Part 1: Virtualization
1. The von Neumann Model
A running program:
- Fetches instruction from memory
- Decodes it
- Executes it
This is the von Neumann model of computing - the fundamental model for how computers execute programs.
2. OS Overview
The operating system makes it easy to run programs by:
- Allowing programs to share memory
- Enabling programs to interact with devices
Virtualization
Virtualization: The primary technique the OS uses to manage resources. The OS takes a physical resource and transforms it into a more general, powerful, and easy-to-use virtual form of itself.
Virtual Machine (VM): We often refer to the OS as a VM because of its virtualization capabilities.
System Calls and APIs
- The OS provides APIs you can call through system calls
- A typical OS has a few hundred system calls available to applications
- These are accessed through the standard library (STL)
Resource Management
The OS is sometimes known as the resource manager.
Resources: CPU, Memory, Disk
Virtualizing the CPU: The OS uses a large number of virtual CPUs to create an illusion that there are infinitely many CPUs available.
Virtualizing Memory: Each process accesses its own private virtual address space, which the OS maps onto the physical memory of the machine.
Concurrency
Concurrency: Doing multiple things at once.
Thread: A function running within the same memory space as other functions, with more than one of them active at a time.
Multi-threaded programs create threads using pthread_create() in C.
Challenge: How can we build a correctly working concurrent application? Because instructions are not atomic (don’t happen all at once), we have concurrency issues.
Persistence
Persistence: The ability to store files persistently on disk, surviving across reboots and power failures.
3. OS Design Goals
- Abstraction: Makes system resources easy to use
- High Performance: Optimize resource usage and minimize overhead
- Isolation: Isolate processes from one another for security and stability
- Reliability: Must run non-stop without crashing
- Other Goals: Energy efficiency, security, mobility
4. UNIX History
Created by Ken Thompson and Dennis Ritchie at Bell Labs.
Evolution:
- Libraries
- Filesystem
- Minicomputer
- PC (Personal Computer)
Note: MacOS (v8) and MS-DOS had issues with memory protection and concurrency support.
5. The Abstraction: The Process
Process: A running program - the fundamental abstraction that the OS provides for executing programs.
Time-Sharing of the CPU
The OS provides the illusion of many CPUs through time-sharing - rapidly switching between processes to give each one time on the CPU.
Mechanisms vs. Policies
Mechanisms: Low-level protocols or methods required to implement a piece of functionality.
Example: Context switch - gives the OS the ability to stop running one program and start running another on a given CPU.
Policies: Algorithms for making decisions within the OS.
Example: Scheduling policy - determines which program to run given multiple ready processes.
What Makes Up a Process?
A process comprises:
- Machine State: What a program can read or update when running
- Address Space: Memory the process can address
- Registers: CPU registers for fast data access
- Program Counter (PC): Points to which instruction is currently being executed
- Stack Pointer: Points to the stack for function calls
- Frame Pointer: Manages parameters, local variables, and return addresses
Resource Sharing
- CPU: Time shared across processes
- Disk: Space shared across files and processes
Process API
The OS provides these operations for processes:
- Create: Create a new process
- Destroy: Forcefully terminate a process
- Wait: Wait for a process to stop executing
- Misc Control: Suspend, resume, and other control operations
- Status: Get information about process state and runtime
How Programs Become Processes
Step 1: Loading Code and Data
The OS loads code and static data (variables, constants) from disk into memory.
- Early OS: Eager loading (entire program loaded at once)
- Modern OS: Lazy loading (load pieces as needed during execution)
Step 2: Memory Allocation
Runtime Stack:
Memory allocated for the program’s stack:
- Used for local variables, function parameters, return addresses
- OS initializes stack with arguments (
argcandargvformain())
Heap:
Memory allocated for dynamic data structures:
- Allocated with
malloc()in C - Freed with
free()in C - Needed for linked lists, hash tables, trees, etc.
- Starts small and grows as needed
File Descriptors:
In Unix systems, each process has three open file descriptors by default:
- Standard input (stdin)
- Standard output (stdout)
- Standard error (stderr)
Step 3: Program Execution
The entry point is the main() function. By jumping to main(), the OS transfers control of the CPU to the process, and the program begins execution.
Process States
A process can be in one of three states:
- Running: Actively executing instructions on the CPU
- Ready: Ready to run but OS has chosen not to run it at this moment
- Blocked: Not ready to run until some event occurs (e.g., I/O completion)
Process State Diagram
Data Structures
The OS maintains several data structures for process management:
- Process List: Tracks all processes in the system
- Register Context: Stores saved register values for each process
- Context Switch: Mechanism for saving and restoring process state
6. Process API
Process creation in UNIX systems uses three key system calls:
fork()- Create new processexec()- Execute new programwait()- Wait for child process
The fork() System Call
fork() creates a new process by duplicating the calling process.
PID: Process Identifier - unique ID for each process
Key Points:
- Creates an (almost) exact copy of the parent process
- Child process continues as if it had called
fork()itself - Child doesn’t start at
main()- starts wherefork()was called - Child receives return code of 0; parent receives child’s PID
- This allows different behavior in parent vs. child
- Fork creation is non-deterministic with one CPU
- CPU scheduler determines execution order - no strong guarantees
The wait() System Call
wait() allows a parent to wait for a child process to finish.
System Calls:
wait()- Wait for any childwaitpid()- Wait for specific child
Using wait() makes execution deterministic by ensuring the parent waits for the child to complete before continuing.
The exec() System Call
exec() runs a different program within the current process (unlike fork() which only makes a copy).
Variants:
execl(),execlp(),execle()execv(),execvp(),execvpe()
How exec() Works:
- Takes executable name and arguments
- Loads new code and static data
- Overwrites current code segment
- Reinitializes heap and stack
- Does not create a new process
- Transforms current program into a completely different program
Important: The separation of fork() and exec() is essential for building shells - it allows code to run between the fork and exec calls (e.g., for I/O redirection).
Shell Implementation
How shells work:
- Display prompt to user
- User enters command
- Shell calls
fork()to create child process - Child calls
exec()to run the command - Parent calls
wait()to wait for child to complete - Returns to prompt when child finishes
Popular Shells: bash, zsh, tcsh
I/O Redirection Example:
prompt> wc p3.c > newfile.txt
Implementation:
- Shell closes stdout in child process
- Opens
newfile.txtinstead - Output goes to file instead of terminal
Unix Pipes
Pipes: Implemented with the pipe() system call.
- Output of one process connects to an in-kernel pipe (a queue)
- Input of another process connects to the same pipe
- Allows chaining commands with
|operator
Example:
ps aux | grep python | wc -l
Signal System Calls
kill() System Call:
Sends signals to processes (pause, terminate, etc.)
Common Signals:
Ctrl-CsendsSIGINT(interrupt) - normally terminates processCtrl-ZsendsSIGTSTP(stop) - pauses process mid-execution
signal() System Call:
Allows processes to catch and handle signals sent to them.
Useful Commands
Process Viewing:
ps- View running processestop- View processes with live resource usage
Privileges:
- Superuser (root): Special user with abilities to kill any process and shut down the system
7. Limited Direct Execution
Direct Execution: Running a program directly on the CPU for maximum performance.
Direct Execution Protocol
| OS | Program |
|---|---|
| 1) Create entry for process list | |
| 2) Allocate memory for program | |
| 3) Load program into memory | |
| 4) Set up stack with argc/argv | |
| 5) Clear registers | |
| 6) Execute call main() | |
| 7) Run main() | |
| 8) Execute return from main() | |
| 9) Free memory of process | |
| 10) Remove from process list |
Problems with Direct Execution
Problem #1: How do we ensure a program doesn’t do something we don’t want it to do?
Problem #2: How do we switch between programs to accomplish time-sharing?
Restricted Operations
What if a program needs to perform restricted operations like I/O requests or accessing more memory?
User Mode vs. Kernel Mode
User Mode:
- Code is restricted in what it can do
- Cannot issue I/O requests directly
- Attempting restricted operations causes an exception that kills the process
Kernel Mode:
- Code can perform any operation
- Can execute privileged operations like I/O calls
- OS runs in this mode
System Calls
User processes perform restricted operations through system calls - a controlled way to request OS services.
Most OSes provide hundreds of system calls.
System Call Process:
- Program executes a trap instruction
- Privilege level changes from user mode to kernel mode
- OS performs the requested operation
- OS calls return-from-trap
- Execution returns to user mode
Important: Hardware saves caller’s registers to restore the process correctly after return-from-trap. On x86, this uses a per-process kernel stack.
Trap Table
How does the trap know which OS code to run?
The trap table solves this:
- Set up at boot time (machine in kernel mode)
- OS informs hardware of trap handler locations
- Hardware remembers these until next reboot
- When system call occurs, hardware knows where to jump
| OS @ Boot | Hardware |
|---|---|
| Initialize trap table | Remember system call handler addresses |
System-Call Number:
Each system call has a number placed in a register or on the stack, which the OS checks to determine which operation to perform.
Kernel Stack:
Each process has a kernel stack where registers are saved during transitions between user and kernel mode.
Switching Between Processes
If a process runs on the CPU, the OS is not running. How does the OS regain control?
Approach I: Cooperative Approach
The OS trusts processes to behave reasonably and periodically give up the CPU.
How Processes Transfer Control:
- System calls - Regular operations transfer control
- yield() system call - Explicitly gives up CPU
- Illegal operations - Divide by zero, access restricted memory, etc.
Problem: What if a malicious or buggy program never gives back control? Without hardware help, the only solution is to reboot the machine.
Approach II: Non-Cooperative Approach
The OS takes control with hardware assistance.
Timer Interrupt: A timer device raises an interrupt every few milliseconds.
Process:
- Timer triggers
- Current process halted
- Pre-configured interrupt handler runs in OS
- OS can now start a new process or continue the current one
Setup:
- At boot time, OS informs hardware which code to run on timer interrupt
- OS starts the timer
Context Switching
The OS regains control through:
- System call
- Illegal operation
- Timer interrupt
Decision Point: Should the OS continue the current process or switch to a different one?
This decision is made by the scheduler - a key OS component that implements scheduling policies.
Context Switch: Low-level code that switches between processes.
Process:
- Save register values for currently running process onto its kernel stack
- Restore register values for the to-be-run process from its kernel stack
8. Scheduling: Introduction
How do we develop an effective scheduling policy?
Workload Assumptions
Workload: The set of processes running in a system.
We start with simplified assumptions about jobs (processes):
- Each job runs for the same amount of time
- All jobs arrive at the same time
- Once started, each job runs to completion
- All jobs only use the CPU (no I/O)
- The runtime of each job is known
We’ll relax these assumptions as we develop more sophisticated schedulers.
Scheduling Metrics
Turnaround Time
Tturnaround = Tcompletion - Tarrival
For now, Tarrival = 0 (assumption 2), so:
Tturnaround = Tcompletion
This is a performance metric that measures how long jobs take to complete.
FIFO (First In, First Out)
Also known as First Come, First Served (FCFS).
Algorithm: Run jobs in the order they arrive.
Average Turnaround Time:
Average = $\sum_{i=1}^{k} \frac{T_{completion,i} - T_{arrival,i}}{k}$
where k = number of processes
The Convoy Effect
Problem: Jobs of different lengths cause trouble for FIFO.
Example:
- Job A = 100 seconds
- Jobs B and C = 10 seconds each
If A runs first:
- Average turnaround = (100 + 110 + 120) / 3 = 110 seconds
Convoy Effect: Short jobs get queued behind a heavyweight job, significantly increasing average turnaround time.
Limitation: FIFO fails when assumption 1 (all jobs run for same time) doesn’t hold.
Shortest Job First (SJF)
Algorithm: Run the shortest job first, then the next shortest, and so on.
Example: Same jobs A, B, C but run B and C first:
- Average turnaround = (10 + 20 + 120) / 3 = 50 seconds
This is much better than FIFO’s 110 seconds!
Important: When all jobs arrive at the same time, SJF is provably optimal.
Limitation
SJF fails when assumption 2 (all jobs arrive at same time) doesn’t hold.
If a long job arrives first and short jobs arrive later, we’re back to the convoy effect.
Note: SJF is a non-preemptive scheduler - once a job starts, it runs to completion.
Shortest Time-to-Completion First (STCF)
Also called Preemptive Shortest Job First (PSJF).
Preemptive Scheduler: Can stop a running job to start or resume another job using context switches.
To fix SJF’s limitation, we relax assumption 3 (jobs run to completion). With timer interrupts and context switches, the scheduler can:
- Preempt the current job
- Run a different job
- Resume the original job later
STCF Algorithm:
- When a new job arrives
- Determine which remaining job has the least time left
- Schedule that job
Example: Long job A arrives first, then short jobs B and C arrive:
- Average turnaround = ((120-0) + (20-10) + (30-10)) / 3 = 50 seconds
Important: STCF is provably optimal for minimizing turnaround time.
Response Time Metric
Response Time: Time from when a job arrives to when it first runs.
Tresponse = Tfirstrun - Tarrival
Problem: SJF and STCF are poor for response time. A short job arriving after a long job has started might wait a long time before first running.
Question: How can we build a scheduler that’s responsive for interactive systems?
Round Robin (RR)
Also called time-slicing.
Algorithm:
- Run a job for a time-slice (or scheduling quantum)
- Switch to the next job
- Repeat until all jobs finish
Time Slice Considerations
Length Requirements:
- Must be a multiple of the timer interrupt period
Trade-offs:
- Shorter time slices → better response time
- Too short → context switch overhead dominates performance
- Need to amortize (spread out) the cost of context switches
Performance Characteristics
Response Time: Excellent - all jobs get CPU time quickly
Turnaround Time: Poor - jobs take longer to complete because of frequent switching
Important Trade-off: Fair policies (distributing CPU on a small time scale) perform poorly on turnaround time.
This is a fundamental trade-off in systems design.
Summary: We now have two classes of schedulers:
- Optimizes turnaround time: SJF, STCF
- Optimizes response time: Round Robin
Incorporating I/O
When a job performs I/O, it doesn’t use the CPU - it’s blocked waiting for I/O completion.
STCF Approach: Treat each CPU burst (time between I/O operations) as a separate job. While one job waits for I/O, another job can use the CPU.
This overlap of CPU and I/O operations improves system utilization.