Based on the book by Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau

Table of Contents

Introduction

  1. The von Neumann Model
  2. OS Overview
  3. OS Design Goals
  4. UNIX History

Part 1: Virtualization

  1. The Abstraction: The Process
  2. Process API
  3. Limited Direct Execution
  4. Scheduling: Introduction

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:

  1. Machine State: What a program can read or update when running
  2. Address Space: Memory the process can address
  3. Registers: CPU registers for fast data access
  4. Program Counter (PC): Points to which instruction is currently being executed
  5. Stack Pointer: Points to the stack for function calls
  6. 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:

  1. Create: Create a new process
  2. Destroy: Forcefully terminate a process
  3. Wait: Wait for a process to stop executing
  4. Misc Control: Suspend, resume, and other control operations
  5. 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 (argc and argv for main())

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:

  1. Running: Actively executing instructions on the CPU
  2. Ready: Ready to run but OS has chosen not to run it at this moment
  3. Blocked: Not ready to run until some event occurs (e.g., I/O completion)

Process State Diagram

stateDiagram-v2 Ready --> Running: schedule Running --> Ready: deschedule Running --> Blocked: I/O started Blocked --> Ready: I/O done

Data Structures

The OS maintains several data structures for process management:

  1. Process List: Tracks all processes in the system
  2. Register Context: Stores saved register values for each process
  3. 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 process
  • exec() - Execute new program
  • wait() - 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:

  1. Creates an (almost) exact copy of the parent process
  2. Child process continues as if it had called fork() itself
  3. Child doesn’t start at main() - starts where fork() was called
  4. Child receives return code of 0; parent receives child’s PID
    • This allows different behavior in parent vs. child
  5. Fork creation is non-deterministic with one CPU
  6. 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 child
  • waitpid() - 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:

  1. Takes executable name and arguments
  2. Loads new code and static data
  3. Overwrites current code segment
  4. Reinitializes heap and stack
  5. Does not create a new process
  6. 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:

  1. Display prompt to user
  2. User enters command
  3. Shell calls fork() to create child process
  4. Child calls exec() to run the command
  5. Parent calls wait() to wait for child to complete
  6. Returns to prompt when child finishes

Popular Shells: bash, zsh, tcsh

I/O Redirection Example:

prompt> wc p3.c > newfile.txt

Implementation:

  1. Shell closes stdout in child process
  2. Opens newfile.txt instead
  3. 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-C sends SIGINT (interrupt) - normally terminates process
  • Ctrl-Z sends SIGTSTP (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 processes
  • top - 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

OSProgram
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:

  1. Program executes a trap instruction
  2. Privilege level changes from user mode to kernel mode
  3. OS performs the requested operation
  4. OS calls return-from-trap
  5. 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:

  1. Set up at boot time (machine in kernel mode)
  2. OS informs hardware of trap handler locations
  3. Hardware remembers these until next reboot
  4. When system call occurs, hardware knows where to jump
OS @ BootHardware
Initialize trap tableRemember 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:

  1. System calls - Regular operations transfer control
  2. yield() system call - Explicitly gives up CPU
  3. 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:

  1. Timer triggers
  2. Current process halted
  3. Pre-configured interrupt handler runs in OS
  4. 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:

  1. System call
  2. Illegal operation
  3. 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:

  1. Save register values for currently running process onto its kernel stack
  2. 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):

  1. Each job runs for the same amount of time
  2. All jobs arrive at the same time
  3. Once started, each job runs to completion
  4. All jobs only use the CPU (no I/O)
  5. 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:

  1. When a new job arrives
  2. Determine which remaining job has the least time left
  3. 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:

  1. Run a job for a time-slice (or scheduling quantum)
  2. Switch to the next job
  3. 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:

  1. Optimizes turnaround time: SJF, STCF
  2. 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.