logo

What's the purpose of swap and zRAM on Android?


The core operating system in Android is Linux kernel. All the apps we use run as native Linux processes. Executable code is saved as a file (a compiled binary or library or virtual machine code) on storage like eMMC, SD card, SSD, hard disk etc. When a process starts, its code is loaded to RAM so that CPU can perform operations on it. Then process keeps on allocating more RAM as it needs and freeing when not needed. But what if there are too many processes running and RAM becomes completely filled?

RAM is broken up into pages; typically 4KB each. So Linux kernel starts freeing up RAM by removing pages which are not shared by other processes and are not dirty (i.e. not been modified by any process). But what if the process has made some changes to the pages e.g. when you edit or create a file in a text editor app?

In this case Linux kernel looks for the pages which have not been touched (changed or used) in last few seconds or minutes. So these pages are temporarily moved to a portion on storage called swap. This portion can be a partition or a file. And as soon as the process needs one of such pages, they are swapped back to RAM.

Linux swap

Credit: Understanding Swap Space

But there are two problems with this approach as discussed here:

So Android uses a compressed portion of RAM called zRAM for swapping. It solves both of the above problems.

Android zRAM

Credit: Android Memory Allocation

Pages are compressed when swapped out, and then decompressed when swapped in. So zRAM keeps on growing and shrinking in size. WhatsRunning shows the current state of zRAM and swap on device:

Android swap usage total

224 MB (196 + 28) of zRAM is holding 698 MB (334 + 91 + 273) of swapped out pages with an almost 3 times compression.

What if swapping is not enough and the device is still short on RAM? Android's Low Memory Killer starts killing cached apps. Still short on RAM? See How to free RAM on Android?


Related:

Comments