Swapping in OS
Swapping moves an entire process out of main memory to a backing store on disk, and later back in, so that more processes can be active than memory can hold at once.
Moving a Whole Process Out and Back
- Select a victim – choose a process to remove, typically blocked or low priority.
- Swap out – copy the process's memory image to the backing store and free its memory.
- Mark it swapped – its PCB records that it is ready but not resident.
- Swap in – when it is needed and memory is free, copy the image back and resume it.
Swapping is a memory management technique in which a process is temporarily moved out of main memory to a backing store, usually a fast disk, and brought back into memory later to continue execution. Moving a process out is called swap out or roll out; bringing it back is swap in or roll in.
Swapping lets the total memory of all active processes exceed the physical memory of the machine, which raises the degree of multiprogramming. The medium-term scheduler makes the choice: it removes processes when memory is short and brings them back when there is room and they are needed.
- Backing store: disk space large enough for copies of all swapped processes
- A swapped-out process still exists; it is just not in memory
- A running process is never the victim; blocked or low-priority ready ones are
When a Process Can Be Swapped
When the scheduler picks a process that is not in memory, the dispatcher checks whether there is room. If not, it swaps out a resident process and swaps in the one it wants, then reloads the registers and transfers control. In a priority system this is called roll out, roll in: a higher-priority process arrives, a lower-priority one is rolled out to make room, and it is rolled back in when the higher-priority work is done.
Two conditions make swapping safe. First, the process must be able to run at a different address when it comes back, which needs execution-time address binding with a relocation (base) register; with compile-time or load-time binding it must return to exactly the same location. Second, a process must not be swapped out while a device is writing into its memory by DMA, or the data would land in whichever process took its place. The tracer shows the scheduler skipping such a process.
- Pending I/O: either never swap such a process, or do all I/O through kernel buffers so no device writes into user memory
- Contiguous space: the whole process needs one hole big enough, so free memory split into small holes may force compaction first
- Many systems swap only when free memory drops below a threshold and stop once it recovers
Swap Time Calculation
The cost of swapping is dominated by the transfer time, which is proportional to the amount of memory moved. For one direction, swap time = disk latency + process size ÷ transfer rate. A full swap, one process out and another in, pays it twice.
Take a 100 MB process, a backing store that transfers 50 MB per second, and an average latency of 8 ms. The transfer takes 100 ÷ 50 = 2 s = 2000 ms, so one direction costs 2008 ms, and swapping this process out and another of the same size in costs 4016 ms. Next to a scheduling quantum of a few milliseconds that is enormous, which is why a swapped-in process should run for a long time before it is swapped again.
- Swap only the memory a process actually uses, not its maximum size
- Doubling the process size roughly doubles the swap time; latency is a small fixed part
- A process that is swapped out and in every quantum spends almost all its time on disk I/O
Terms, operations, and practical uses
Core vocabulary
- SwappingMoving a whole process between main memory and the backing store.
- Backing storeDisk space that holds the images of swapped-out processes.
- Roll out, roll inSwapping a low-priority process out so a high-priority one can run.
- Medium-term schedulerDecides which processes are swapped out and back in.
Formulas and rules
- Swap timelatency + size ÷ transfer rate, for each direction
- Full swapswap out + swap in: twice the one-way time for equal sizes
- Relocationexecution-time binding lets a process return to a new address
- Pending I/Onever swap out a process a device is writing into
Related lessons
- Types of SchedulersThe medium-term scheduler that swaps processes.
- Virtual MemoryPaging, the modern replacement for whole-process swapping.
- Disk ManagementWhere swap space lives on the disk and how it is managed.
- External FragmentationThe holes that swapping whole processes creates.
Roll out, roll in, and compaction
from dataclasses import dataclass
MEMORY_MB = 12 # user memory, after the kernel
LATENCY_MS = 8 # disk latency per transfer
RATE_MB_PER_S = 100 # disk transfer rate
@dataclass
class Proc:
size: int # MB
priority: int # higher runs first
state: str # running, ready, blocked or swapped
base: int | None # start address in MB, None when on disk
io_pending: bool = False
procs = {
"P1": Proc(4, 2, "running", 0),
"P2": Proc(3, 2, "blocked", 4, io_pending=True),
"P3": Proc(5, 1, "ready", 7),
"P4": Proc(4, 3, "swapped", None),
}
swap_ms = 0
def resident():
return sorted((p.base, name) for name, p in procs.items() if p.base is not None)
def holes():
found, at = [], 0
for base, name in resident():
if base > at:
found.append((at, base - at))
at = base + procs[name].size
if at < MEMORY_MB:
found.append((at, MEMORY_MB - at))
return found
def memory_map():
cells, at = [], 0
for base, name in resident():
if base > at:
cells.append(f"[{at}-{base} free]")
at = base + procs[name].size
cells.append(f"[{base}-{at} {name}]")
if at < MEMORY_MB:
cells.append(f"[{at}-{MEMORY_MB} free]")
return " ".join(cells)
def transfer(name, direction):
global swap_ms
ms = LATENCY_MS + procs[name].size * 1000 // RATE_MB_PER_S
swap_ms += ms
print(f" swap {direction} {name} ({procs[name].size} MB): {ms} ms")
def swap_in(name):
size = procs[name].size
fit = next((base for base, free in holes() if free >= size), None) # first fit
if fit is None:
total = sum(free for _, free in holes())
print(f" {name} needs {size} MB: {total} MB free in total, no single hole fits it")
return False
transfer(name, "in")
procs[name].state, procs[name].base = "ready", fit
return True
def swap_out_victim():
# Blocked processes first (they cannot run anyway), then the lowest priority.
candidates = [n for _, n in resident() if procs[n].state != "running"]
candidates.sort(key=lambda n: (procs[n].state != "blocked", procs[n].priority))
for name in candidates:
if procs[name].io_pending:
# A device is writing into this memory; moving the process would
# let the transfer land in someone else's space.
print(f" skip {name}: blocked, but its I/O is still in flight")
continue
transfer(name, "out")
procs[name].state, procs[name].base = "swapped", None
return name
return None
def compact():
at = 0
for _, name in resident():
procs[name].base = at
at += procs[name].size
print(" compaction: processes slid together, relocated by the base register")
print("start: ", memory_map())
print("P4 (priority 3) is ready but swapped out")
if not swap_in("P4"):
swap_out_victim()
swap_in("P4")
print("after roll-in:", memory_map())
procs["P2"].state, procs["P2"].io_pending = "ready", False
del procs["P1"]
print("P2's I/O completes; P1 terminates")
print("now: ", memory_map())
if not swap_in("P3"):
compact()
swap_in("P3")
print("after P3 in: ", memory_map())
print(f"total swap time: {swap_ms} ms")#include <algorithm>
#include <cstdio>
#include <map>
#include <optional>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const int MEMORY_MB = 12; // user memory, after the kernel
const int LATENCY_MS = 8; // disk latency per transfer
const int RATE_MB_PER_S = 100; // disk transfer rate
struct Proc {
int size; // MB
int priority; // higher runs first
string state; // running, ready, blocked or swapped
optional<int> base; // start address in MB, empty when on disk
bool ioPending = false;
};
map<string, Proc> procs = {
{"P1", {4, 2, "running", 0}},
{"P2", {3, 2, "blocked", 4, true}},
{"P3", {5, 1, "ready", 7}},
{"P4", {4, 3, "swapped", nullopt}},
};
int swapMs = 0;
vector<pair<int, string>> resident() {
vector<pair<int, string>> r;
for (const auto& [name, p] : procs) {
if (p.base) r.push_back({*p.base, name});
}
sort(r.begin(), r.end());
return r;
}
vector<pair<int, int>> holes() {
vector<pair<int, int>> found;
int at = 0;
for (const auto& [base, name] : resident()) {
if (base > at) found.push_back({at, base - at});
at = base + procs[name].size;
}
if (at < MEMORY_MB) found.push_back({at, MEMORY_MB - at});
return found;
}
string memoryMap() {
string out;
int at = 0;
auto cell = [&](int from, int to, const string& what) {
out += (out.empty() ? "" : " ") + ("[" + to_string(from) + "-" + to_string(to) + " " + what + "]");
};
for (const auto& [base, name] : resident()) {
if (base > at) cell(at, base, "free");
at = base + procs[name].size;
cell(base, at, name);
}
if (at < MEMORY_MB) cell(at, MEMORY_MB, "free");
return out;
}
void transfer(const string& name, const char* direction) {
int ms = LATENCY_MS + procs[name].size * 1000 / RATE_MB_PER_S;
swapMs += ms;
printf(" swap %s %s (%d MB): %d ms\n", direction, name.c_str(), procs[name].size, ms);
}
bool swapIn(const string& name) {
int size = procs[name].size;
for (const auto& [base, free] : holes()) { // first fit
if (free >= size) {
transfer(name, "in");
procs[name].state = "ready";
procs[name].base = base;
return true;
}
}
int total = 0;
for (const auto& h : holes()) total += h.second;
printf(" %s needs %d MB: %d MB free in total, no single hole fits it\n", name.c_str(), size, total);
return false;
}
void swapOutVictim() {
// Blocked processes first (they cannot run anyway), then the lowest priority.
vector<string> candidates;
for (const auto& [base, name] : resident()) {
if (procs[name].state != "running") candidates.push_back(name);
}
stable_sort(candidates.begin(), candidates.end(), [](const string& a, const string& b) {
return make_pair(procs[a].state != "blocked", procs[a].priority) <
make_pair(procs[b].state != "blocked", procs[b].priority);
});
for (const string& name : candidates) {
if (procs[name].ioPending) {
// A device is writing into this memory; moving the process would
// let the transfer land in someone else's space.
printf(" skip %s: blocked, but its I/O is still in flight\n", name.c_str());
continue;
}
transfer(name, "out");
procs[name].state = "swapped";
procs[name].base.reset();
return;
}
}
void compact() {
int at = 0;
for (const auto& [base, name] : resident()) {
procs[name].base = at;
at += procs[name].size;
}
printf(" compaction: processes slid together, relocated by the base register\n");
}
int main() {
printf("start: %s\n", memoryMap().c_str());
printf("P4 (priority 3) is ready but swapped out\n");
if (!swapIn("P4")) {
swapOutVictim();
swapIn("P4");
}
printf("after roll-in: %s\n", memoryMap().c_str());
procs["P2"].state = "ready";
procs["P2"].ioPending = false;
procs.erase("P1");
printf("P2's I/O completes; P1 terminates\n");
printf("now: %s\n", memoryMap().c_str());
if (!swapIn("P3")) {
compact();
swapIn("P3");
}
printf("after P3 in: %s\n", memoryMap().c_str());
printf("total swap time: %d ms\n", swapMs);
return 0;
}import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
static final int MEMORY_MB = 12; // user memory, after the kernel
static final int LATENCY_MS = 8; // disk latency per transfer
static final int RATE_MB_PER_S = 100; // disk transfer rate
static class Proc {
final int size; // MB
final int priority; // higher runs first
String state; // running, ready, blocked or swapped
Integer base; // start address in MB, null when on disk
boolean ioPending;
Proc(int size, int priority, String state, Integer base, boolean ioPending) {
this.size = size;
this.priority = priority;
this.state = state;
this.base = base;
this.ioPending = ioPending;
}
}
static final Map<String, Proc> procs = new TreeMap<>();
static int swapMs = 0;
static List<String> resident() {
List<String> r = new ArrayList<>();
procs.forEach((name, p) -> {
if (p.base != null) r.add(name);
});
r.sort(Comparator.comparingInt(n -> procs.get(n).base));
return r;
}
static List<int[]> holes() {
List<int[]> found = new ArrayList<>();
int at = 0;
for (String name : resident()) {
int base = procs.get(name).base;
if (base > at) found.add(new int[] {at, base - at});
at = base + procs.get(name).size;
}
if (at < MEMORY_MB) found.add(new int[] {at, MEMORY_MB - at});
return found;
}
static String memoryMap() {
List<String> cells = new ArrayList<>();
int at = 0;
for (String name : resident()) {
int base = procs.get(name).base;
if (base > at) cells.add(String.format("[%d-%d free]", at, base));
at = base + procs.get(name).size;
cells.add(String.format("[%d-%d %s]", base, at, name));
}
if (at < MEMORY_MB) cells.add(String.format("[%d-%d free]", at, MEMORY_MB));
return String.join(" ", cells);
}
static void transfer(String name, String direction) {
int ms = LATENCY_MS + procs.get(name).size * 1000 / RATE_MB_PER_S;
swapMs += ms;
System.out.printf(" swap %s %s (%d MB): %d ms%n", direction, name, procs.get(name).size, ms);
}
static boolean swapIn(String name) {
Proc p = procs.get(name);
for (int[] hole : holes()) { // first fit
if (hole[1] >= p.size) {
transfer(name, "in");
p.state = "ready";
p.base = hole[0];
return true;
}
}
int total = holes().stream().mapToInt(h -> h[1]).sum();
System.out.printf(" %s needs %d MB: %d MB free in total, no single hole fits it%n", name, p.size, total);
return false;
}
static void swapOutVictim() {
// Blocked processes first (they cannot run anyway), then the lowest priority.
List<String> candidates = new ArrayList<>();
for (String name : resident()) {
if (!procs.get(name).state.equals("running")) candidates.add(name);
}
candidates.sort(Comparator.<String, Boolean>comparing(n -> !procs.get(n).state.equals("blocked"))
.thenComparingInt(n -> procs.get(n).priority));
for (String name : candidates) {
Proc p = procs.get(name);
if (p.ioPending) {
// A device is writing into this memory; moving the process would
// let the transfer land in someone else's space.
System.out.printf(" skip %s: blocked, but its I/O is still in flight%n", name);
continue;
}
transfer(name, "out");
p.state = "swapped";
p.base = null;
return;
}
}
static void compact() {
int at = 0;
for (String name : resident()) {
procs.get(name).base = at;
at += procs.get(name).size;
}
System.out.println(" compaction: processes slid together, relocated by the base register");
}
public static void main(String[] args) {
procs.put("P1", new Proc(4, 2, "running", 0, false));
procs.put("P2", new Proc(3, 2, "blocked", 4, true));
procs.put("P3", new Proc(5, 1, "ready", 7, false));
procs.put("P4", new Proc(4, 3, "swapped", null, false));
System.out.println("start: " + memoryMap());
System.out.println("P4 (priority 3) is ready but swapped out");
if (!swapIn("P4")) {
swapOutVictim();
swapIn("P4");
}
System.out.println("after roll-in: " + memoryMap());
procs.get("P2").state = "ready";
procs.get("P2").ioPending = false;
procs.remove("P1");
System.out.println("P2's I/O completes; P1 terminates");
System.out.println("now: " + memoryMap());
if (!swapIn("P3")) {
compact();
swapIn("P3");
}
System.out.println("after P3 in: " + memoryMap());
System.out.printf("total swap time: %d ms%n", swapMs);
}
}Step through it
Running on 12 MB memory; P1 4 MB running, P2 3 MB blocked on I/O, P3 5 MB ready, P4 4 MB on disk (priority 3); disk 8 ms + 100 MB/s
Swapping with Paging
Standard swapping, moving entire processes, is rarely used by modern operating systems: it takes too long and leaves external fragmentation. Instead, systems with virtual memory swap pages. A page out writes one page to the swap space and a page in reads it back, so only the parts of a process that are not being used leave memory. This is demand paging, and the word swapping is now used loosely for it.
Linux keeps swapped pages in a swap partition or swap file and tunes how eagerly it uses them with vm.swappiness. Windows uses a pagefile. Phones have traditionally avoided swapping to flash, which wears out and is small: iOS compresses memory, Android uses zram (compressed swap kept in RAM), and both kill background apps when memory runs out. Whole-process swapping survives only as a last resort under severe memory pressure.
- Page out / page in: move individual pages, not whole processes
- Swap space: a partition or file reserved on disk for swapped pages
- Too much paging activity becomes thrashing
Swapping vs Paging
The two are often confused because modern systems implement swapping with paging. The difference is the unit that moves and whether it must be contiguous.
| Aspect | Swapping | Paging |
|---|---|---|
| Unit moved | an entire process | a fixed-size page |
| Memory needed | one contiguous region per process | any free frames, anywhere |
| Fragmentation | external | internal (within the last page) |
| Transfer size | large: the whole image | small: 4 KB pages, on demand |
| Decided by | the medium-term scheduler | the page replacement algorithm |
| Used today | rarely, under extreme memory pressure | by every general-purpose OS |
- Swapping is coarse and simple; paging is fine-grained but needs hardware support (an MMU and page tables)
- See Segmentation and Paging for how pages are mapped
When Swapping Pays Off
Swapping trades disk time for memory. It pays off when some processes sit idle for long periods, and it fails when every process needs the CPU often, because then the CPU waits on the disk instead of running anything.
- Gain: more processes than physical memory can hold, so higher CPU utilization
- Gain: a high-priority process can run at once by rolling out a low-priority one
- Gain: works on simple hardware with only a base and limit register
- Cost: every move copies a whole process, taking seconds for large ones
- Cost: external fragmentation, so compaction may be needed before a roll in
- Related: Memory Management and Types of Schedulers