Kernel same-page merging (KSM) is a Linux kernel feature that scans memory for identical pages and merges them into a single copy-on-write page shared by several processes. In virtualization on Linux, KSM is used mainly with KVM and QEMU to deduplicate guest memory, so that many virtual machines running the same operating system consume noticeably less physical RAM than their combined configured size.
KSM entered the mainline kernel in version 2.6.32 and works on anonymous memory only. It does not require cooperation from guests: from the host’s point of view, each virtual machine is simply a large QEMU process whose memory regions have been registered as mergeable.
How kernel same-page merging finds and shares pages
KSM runs as a kernel thread called ksmd, which periodically walks memory regions that applications have marked with madvise(MADV_MERGEABLE). QEMU marks guest RAM this way by default, and recent kernels also allow process-wide opt-in through prctl so that whole workloads can participate.
The scanner uses two red-black trees to find duplicates efficiently. The stable tree holds pages that are already merged and write-protected. The unstable tree holds candidate pages that have not changed between two scans, ordered by content. When a scanned page matches a page in either tree byte for byte, KSM maps both virtual addresses to one physical page, marks it read-only and frees the duplicate.
If any process later writes to a merged page, the hardware raises a fault and the kernel performs copy-on-write: it allocates a private copy for the writer. This break of sharing is transparent to the application but costs time and memory, which is why KSM favors pages that rarely change.
Key KSM parameters and statistics
KSM is controlled through files in /sys/kernel/mm/ksm/. The scan rate is the main lever: it sets how much CPU the ksmd thread spends and how quickly savings appear.
| Parameter | Meaning | Typical effect of raising it |
|---|---|---|
run | 0 stops, 1 runs, 2 unmerges all pages | Not applicable (mode switch) |
pages_to_scan | Pages scanned per wake-up | Faster merging, more CPU use |
sleep_millisecs | Pause between scan batches | Lower CPU use, slower merging |
max_page_sharing | Maximum sharers of one stable page | Higher density, longer chains to manage |
merge_across_nodes | Allows merging across NUMA nodes | More savings, possible remote access penalty |
use_zero_pages | Merges empty pages with the zero page | Cheaper handling of zeroed memory |
The effect of KSM is visible in counters in the same directory. Reading them together shows whether merging pays off or only burns CPU cycles.
| Counter | What it counts | Interpretation |
|---|---|---|
pages_shared | Physical pages in use after merging | Memory actually kept |
pages_sharing | Additional mappings saved | Roughly the pages saved |
pages_unshared | Pages scanned but unique | High value means wasted scanning |
pages_volatile | Pages changing too fast to merge | Poor candidates for KSM |
full_scans | Completed passes over all regions | Shows scanner progress |
A high ratio of `pages_sharing` to `pages_shared` indicates good deduplication. A large pages_unshared value combined with modest savings suggests that the workload is a poor fit, and the scan rate should be reduced or KSM disabled.
KSM compared with other memory-saving techniques
KSM is one of several ways to fit more virtual machines into host memory, and it is often combined with the others. Each technique has a different cost and trigger.
| Technique | How it saves memory | Guest cooperation | Main cost |
|---|---|---|---|
| KSM | Shares identical pages across processes | Not required | Host CPU time for scanning |
| Memory ballooning | Guest driver returns unused pages | Required (virtio-balloon) | Guest may run short of memory |
| Free page reporting | Guest reports freed pages to the host | Required | Small signaling overhead |
| Host swap or zswap | Moves cold pages to disk or compressed RAM | Not required | Latency on page access |
| Transparent huge pages | Uses 2 MiB pages for efficiency | Not required | Conflicts with fine-grained merging |
The conflict with huge pages deserves attention. KSM merges 4 KiB pages, so a huge page must first be split before its contents can be shared. Hosts that rely on huge pages for performance, for example with GPU passthrough or latency-sensitive guests, often gain little from KSM.
When to enable KSM
KSM is most useful on hosts that run many similar guests, such as virtual desktop farms, test labs and dense clusters built on Proxmox VE or libvirt. Savings of tens of percent of guest memory are realistic when guests share an operating system image, while heterogeneous workloads may save only a few percent.
- Enable it for dense deployments of identical or similar guests where memory is the limiting resource.
- Tune it adaptively with tools such as ksmtuned, which raise the scan rate only when free memory falls.
- Disable it for performance-critical hosts with few large guests, NUMA-sensitive workloads or heavy huge page usage.
- Avoid it where tenants do not trust each other, unless the side-channel risk has been assessed.
Security risks and limitations of KSM
The main risk of KSM is a timing side channel. Writing to a merged page takes measurably longer because of copy-on-write, so an attacker in one virtual machine can detect whether a page with known content exists in another guest. Research attacks have used this to identify software versions, recover information about address-space layouts and support Rowhammer-based attacks on shared pages.
For this reason, many public cloud providers disable cross-tenant merging. Other limitations include unpredictable memory demand when shared pages are suddenly unmerged, which can trigger out-of-memory conditions if the host was overcommitted on the assumption of stable savings, and the steady CPU cost of scanning large memory regions.
In everyday language
Imagine a library where ten readers each bring the same textbook. Instead of keeping ten copies on the shelf, the librarian keeps one shared copy and lets everyone read it. If one reader wants to write notes in the margin, that reader gets a personal photocopy.
KSM does the same with computer memory. When several virtual machines hold identical data, the system keeps only one copy and hands out private copies only when something changes. The result is that one server can run more machines with the same amount of memory.
Seen in the real world
A university IT department runs a training lab on one KVM host with 256 GiB of RAM. For each course, it starts 40 identical Linux guests with 8 GiB each, which adds up to 320 GiB of configured memory, more than the host physically has.
With KSM enabled and ksmtuned adjusting the scan rate, the counters show about 9 million pages saved after twenty minutes, which corresponds to roughly 34 GiB of memory. Combined with ballooning, the host runs the full class without swapping. Because all guests belong to the same department, the side-channel risk is acceptable, and the lab avoids buying a second server. The outcome is higher guest density at modest CPU cost, about one core spent on scanning during startup.