What is Linux Swap And Zram-Free Embedded Linux Course

PREV_LEC NEXT_LEC
Linux Swap And Zram
Part of the free Linux kernel development course — Managing Memory chapter
Chapter 11
Lecture 5
Embedded Focus

Linux Swap And Zram Explained

If you are following our free linux kernel development course, you already know that RAM on an embedded board is almost always the tightest resource on the system. Swap is the kernel’s oldest trick for stretching that RAM, and zram is the modern, flash-friendly way embedded engineers actually use it. This lecture explains both from first principles, then walks through configuring, enabling, and measuring zram-backed swap on a real board running a current mainline kernel.

swap zram CONFIG_ZRAM memory reclaim free linux device drivers course

What You Will Learn

  • Why the kernel swaps pages out at all, and what it actually gains you
  • Why disk-backed swap is a poor fit for embedded flash storage
  • How zram works internally and why it is the preferred swap device on low-memory boards
  • How to build, enable, and size a zram swap device on the latest stable kernel
  • How to watch swap activity and decide whether zram is helping or hurting your board

Prerequisites

You should already be comfortable with basic kernel configuration (menuconfig/defconfig), rebuilding and flashing a kernel image, and reading /proc and /sys files from a shell. If you have not been through the earlier lectures in this free embedded linux course on virtual memory and process memory maps, it is worth skimming those first — this lecture builds directly on the idea of a page as the unit of memory management.

Why Swap Exists

Every page of memory a process touches has to live somewhere physical. When the system runs low on free pages, the kernel has two choices for a page that is not backed by a file: throw it away, which loses data, or copy it out to some other storage and reclaim the physical page. Swap is that “somewhere else.” A swap device is nothing more than a block device (or a file) that the kernel treats as an extension of RAM for anonymous pages — the stack, the heap, and other memory that has no file behind it.

Swap is never a substitute for enough RAM. Copying a page out and later copying it back in costs real time, and if the working set of your processes genuinely does not fit in RAM, the kernel ends up copying pages back and forth constantly instead of doing useful work. That state has a name: thrashing. The system looks “busy” but almost none of the CPU time is going toward your application.

Why Traditional Swap Struggles On Embedded Boards

Desktop and server systems have historically swapped to a spinning disk or an SSD with wear-leveling and a generous write budget. Most embedded boards have neither. They boot from raw NAND, eMMC, or a small SPI NOR chip, and flash cells wear out after a bounded number of program/erase cycles. A swap partition that is written to constantly under memory pressure is exactly the kind of workload that shortens the life of that storage — and unlike a laptop SSD, an embedded board’s storage often cannot be swapped out in the field. This is the main reason classic disk-backed swap is rare on embedded Linux, and why the kernel’s compressed-RAM alternative matters so much for this audience.

How Zram Actually Works

zram is a block device driver that lives entirely inside RAM. Instead of writing a swapped-out page to flash, the kernel compresses the page in memory and stores the compressed bytes inside a zram device such as /dev/zram0. When the page is needed again, the kernel decompresses it back into a normal page. No flash write ever happens.

The trade is CPU time and a second copy of the data (compressed) for extra effective RAM. Typical text and heap pages on embedded workloads compress to somewhere between roughly a third and half of their original size, so a board that dedicates, say, 128 MiB of RAM to a zram device can often absorb noticeably more than 128 MiB worth of swapped-out pages — at the cost of the compression/decompression CPU cycles and a small increase in power draw. On a board that is occasionally memory-starved but has CPU headroom, that is usually a good trade. On a board that is already CPU-bound, it usually is not.

Anonymous Page Under Memory Pressure
Process heap page (anonymous, dirty) | v Kernel reclaim picks the page | v +——————–+ +———————–+ | Compress in memory |——->| Store in /dev/zram0 | | (LZO / LZ4 / zstd) | | (RAM-backed block dev) | +——————–+ +———————–+ | v Physical page freed and reused | v Page fault later -> decompress -> page restored to process

Configuring Zram On A Current Kernel

On mainline kernels today, zram lives under drivers/block/zram and is enabled with a small, focused set of options — the old-style memory-controller option names some books still list have long since been folded into the unified memory controller. Enable at least:

CONFIG_SWAP=y
CONFIG_ZRAM=y
CONFIG_ZRAM_DEF_COMP_LZORLE=y   # or LZ4 / ZSTD, pick one default
CONFIG_MEMCG=y
CONFIG_MEMCG_SWAP=y

Pick a compression algorithm based on your board: LZO is the lightest on CPU, zstd compresses noticeably tighter but costs more cycles per page. If your kernel has multiple compressors built in, you can even choose per-device at runtime through /sys/block/zram0/comp_algorithm.

Creating And Enabling A Zram Swap Device

Once the kernel boots with zram support, loading the module (or, if built-in, just seeing the device appear) gives you /dev/zram0. Rather than the old fstab-with-a-fixed-size approach, the current, cleaner way is to size the device through sysfs and then hand it to mkswap/swapon like any other swap device:

# modprobe zram num_devices=1
# echo lz4 > /sys/block/zram0/comp_algorithm
# echo 128M > /sys/block/zram0/disksize
# mkswap /dev/zram0
# swapon -p 100 /dev/zram0

The -p 100 gives zram swap a high priority so the kernel prefers it over any slower disk-backed swap that might also be configured. To make this persistent across boots, most current distributions and Yocto/Buildroot setups use a small init script or a systemd unit that runs the same three commands early in boot rather than a static /etc/fstab entry, because the disk size has to be set through sysfs before swapon will succeed.

Turning it off is the same as any swap device:

# swapoff /dev/zram0
# echo 1 > /sys/block/zram0/reset

Watching Zram Do Its Job

Two tools tell you whether zram is actually earning its keep. swapon --show gives you swap usage per device, and the per-device sysfs stats give you the compression ratio directly:

$ swapon --show
NAME       TYPE      SIZE   USED PRIO
/dev/zram0 partition 128M   34M  100

$ cat /sys/block/zram0/mm_stat
   orig_data_size   compr_data_size  mem_used_total ...
      71303168          24117248         24444928 ...

orig_data_size is how much data is logically stored, compr_data_size is how much RAM that actually costs after compression — the ratio between the two is your real-world compression ratio on this board’s workload, which is far more useful than any number quoted in a book.

Swap Device Comparison

Backing storeFlash wearExtra CPU costTypical embedded use
eMMC / NAND partitionHigh under pressureLowRare — avoided on production boards
zram (compressed RAM)NoneModerate (compress/decompress)Common on low-memory boards with CPU headroom
zswap (compressed cache + disk backend)Some — only on cache overflowModerateSystems with both limited RAM and a real disk

Real-World Use Case

A good example is a low-memory Android or embedded Linux media device with, say, 512 MiB of RAM. The UI stack, browser, and background services can spike memory usage well past what fits comfortably, but the storage is eMMC with a limited write budget. Dedicating a modest slice of RAM as a zram swap device lets the kernel absorb those spikes by compressing cold pages instead of killing processes outright, without ever touching the flash. This is exactly the pattern Android has shipped by default on low-RAM devices for years.

Common Mistakes And Troubleshooting

  • Sizing zram too large. The disksize is a logical limit, not reserved RAM, but if the data does not compress well, a large zram device can itself consume most of physical RAM and make things worse. Start conservative (10–25% of RAM) and measure.
  • Forgetting the sysfs disksize step. mkswap silently fails or produces a zero-size device if you try to run it before setting disksize.
  • Using zram on a CPU-starved board. If your CPU is already the bottleneck, adding compression work will make latency worse, not better — check CPU headroom first.
  • No priority set. If you have both zram and a disk-backed swap file, forgetting swapon -p can leave the kernel preferring the slower device.

Best Practices

  • Prefer zram over any flash-backed swap on embedded boards unless you have a specific reason not to.
  • Pick the compression algorithm based on measured CPU headroom, not habit — benchmark LZO against zstd on your actual board.
  • Size the device from real memory-pressure measurements (see the previous lecture on measuring kernel memory usage), not a guess.
  • Always give zram a swap priority above any other configured swap device.

Performance And Security Considerations

Performance-wise, zram trades CPU cycles and a little latency for effective RAM — always validate on target hardware, since ARM cores with dedicated crypto/compression acceleration behave very differently from a plain Cortex-A core running software LZ4. From a security angle, remember that a zram device holds decompressed application memory in compressed form but not encrypted form; if your threat model includes physical access to a running device, zram alone does nothing to protect that data, and you would need dm-crypt or a similar layer underneath.

Summary And Key Takeaways

  • Swap extends usable memory by moving anonymous pages out of RAM under pressure.
  • Disk-backed swap wears out embedded flash and is generally avoided.
  • zram compresses pages into a RAM-backed block device, giving you extra effective memory with no flash writes, at the cost of CPU cycles.
  • Current kernels configure zram through CONFIG_ZRAM plus the unified memory controller options, and size it through /sys/block/zram0/disksize.
  • swapon --show and /sys/block/zram0/mm_stat tell you exactly how much zram is buying you.

Conclusion

Swap is a simple idea — spill memory somewhere else when RAM runs short — but the “somewhere else” matters enormously on embedded hardware. zram turns that somewhere-else into RAM itself, compressed, so your board gains breathing room without wearing out flash it may never get replaced. Understanding when zram helps, and measuring rather than guessing its effect, is a core skill for anyone doing serious embedded Linux memory tuning, and it rounds out this chapter’s look at how the kernel manages memory under real-world constraints.

Frequently Asked Questions

Is zram the same thing as a RAM disk?

No. A RAM disk stores files directly and uncompressed; zram is specifically a swap/block device that compresses the anonymous pages the kernel writes to it, and it disappears (along with its contents) once you reset or remove the device.

Should every embedded board enable zram?

No — boards with comfortable RAM headroom gain nothing and just add unnecessary code paths. zram earns its place specifically on boards that are occasionally memory-constrained but have spare CPU cycles.

What compression algorithm should I pick for zram?

LZO/LZO-RLE is the lightest on CPU and a safe default for weaker cores; zstd compresses better but costs more cycles. Benchmark both on your actual target before deciding.

Can zram and a real swap partition run together?

Yes. The kernel supports multiple swap devices simultaneously, each with its own priority via swapon -p, so you can let zram absorb the common case and fall back to a slower device only if needed.

How do I know if zram is actually helping my board?

Compare orig_data_size and compr_data_size in /sys/block/zram0/mm_stat before and after enabling zram, and watch overall CPU utilization — if latency-sensitive tasks start missing deadlines, the CPU cost is outweighing the memory benefit.

Does zram wear out flash storage?

No — that is the whole point of zram. The compressed pages live entirely in RAM and are never written to the underlying flash device.

What happens to zram contents on a reboot?

They are lost, exactly like any other RAM contents. zram is not persistent storage and should never be treated as one.

JSON-LD FAQ Schema

{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {"@type": "Question", "name": "Is zram the same thing as a RAM disk?",
     "acceptedAnswer": {"@type": "Answer", "text": "No. A RAM disk stores files directly and uncompressed; zram compresses the anonymous pages the kernel swaps to it and loses its contents when reset or removed."}},
    {"@type": "Question", "name": "Should every embedded board enable zram?",
     "acceptedAnswer": {"@type": "Answer", "text": "No, only boards that are occasionally memory-constrained but have spare CPU cycles benefit meaningfully."}},
    {"@type": "Question", "name": "What compression algorithm should I pick for zram?",
     "acceptedAnswer": {"@type": "Answer", "text": "LZO/LZO-RLE is lighter on CPU; zstd compresses tighter but costs more cycles. Benchmark on the real target."}},
    {"@type": "Question", "name": "Can zram and a real swap partition run together?",
     "acceptedAnswer": {"@type": "Answer", "text": "Yes, the kernel supports multiple prioritized swap devices at once."}},
    {"@type": "Question", "name": "How do I know if zram is actually helping my board?",
     "acceptedAnswer": {"@type": "Answer", "text": "Compare orig_data_size and compr_data_size in /sys/block/zram0/mm_stat and watch CPU utilization impact."}},
    {"@type": "Question", "name": "Does zram wear out flash storage?",
     "acceptedAnswer": {"@type": "Answer", "text": "No, zram is entirely RAM-backed and never writes to flash."}},
    {"@type": "Question", "name": "What happens to zram contents on a reboot?",
     "acceptedAnswer": {"@type": "Answer", "text": "They are lost, the same as any other RAM contents."}}
  ]
}

Continue The Free Linux Kernel Development Course

More hands-on Linux kernel, device driver, and embedded Linux lectures are on the way — all free, all on EmbeddedPathashala.

Browse The Full Course Next Lecture
PREV_LEC NEXT_LEC

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *