Per-process ZRAM writeback

In Android 17 QPR2 and higher, per-process ZRAM writeback includes static resource overlay configurations (config.xml or runtime resource overlays (RROs)) for device manufacturers. This memory optimization feature writes ZRAM memory pages of eligible cached background apps directly out to backing flash storage. By reducing the physical DRAM footprint of idle cached apps, per-process ZRAM writeback lets the system retain more cached apps in memory, preserving app state and avoiding disruptive process terminations.

Overview and system benefits

Traditional ZRAM compresses anonymous memory pages and stores them in a dynamic swap pool in physical DRAM. While this provides a 2:1 to 3:1 compression ratio, the compressed pages still occupy physical RAM. Under system memory pressure, the low-memory killer daemon (lmkd) is forced to terminate background cached processes to satisfy foreground memory allocations. When a user returns to a terminated app, the system must launch the process through a cold start, losing transient in-app state (such as user input, navigation stack, and scroll position).

Traditional idle page writeback in ZRAM operates globally and periodically during scheduled maintenance sweeps (managed by the Memory management daemon (mmd)), scanning memory pages after long idle windows (for example, 20 or more hours). However, global idle writeback lacks process-level context and can't proactively prioritize user-facing apps when they enter the background.

Per-process ZRAM writeback bridges this gap by letting system_server use CachedAppOptimizer to target eligible cached apps shortly after freezing. Whereas generic swap-to-flash or file-backed RAM-extension schemes decompress pages or route swap I/O through a mounted file system, per-process ZRAM writeback coordinates four platform behaviors:

  • Direct compressed block writeback: When kernel compressed writeback is enabled with compressed_writeback set to 1, mmd writes compressed ZRAM objects directly to an encrypted raw Device Mapper block partition backed by dm-default-key without CPU decompression or loopback file system layers.
  • Activity-only eligibility: CachedAppOptimizer admits only frozen cached processes that host UI activities with hasActivities set to true. Headless cached processes such as CACHED_EMPTY processes, stopped services, and broadcast receivers stay in compressed DRAM so lmkd terminates them first under memory pressure instead of spending flash write quota on processes with no UI state to restore.
  • Eviction-priority protection: After writeback succeeds, OomAdjuster sends an oom_score_adj ceiling of 249 to lmkd, keeping the written-back process alive ahead of cached processes in the 900 to 999 range.
  • Activity-triggered read-ahead: When a written-back process unfreezes for an activity launch, CachedAppOptimizer restores its compressed pages into ZRAM without blocking on backing storage reads, whereas non-activity unfreezes clear the writeback state without prefetching.

Per-process ZRAM writeback provides the following system benefits:

  • Preserving app state (positive user experience): By keeping cached processes alive rather than terminating them under memory pressure, the system preserves in-app state (such as navigation history, unsaved form inputs, and scroll positions). When the user returns, the app resumes directly where they left off instead of restarting from scratch.
  • Physical RAM savings: Reclaims nearly 100% of an app's anonymous and swap memory, reducing its physical DRAM footprint to negligible kernel metadata.
  • Keeping cached apps alive: Reduces memory pressure across the system, preventing lmkd from terminating background cached processes.

Architecture and mechanism

Per-process ZRAM writeback spans Android framework components, the user-space memory management daemon (mmd), and Linux kernel ZRAM drivers.

Platform and kernel prerequisites

Per-process ZRAM writeback requires the following system components:

  • Cached apps freezer: The Android framework cached apps freezer (CachedAppOptimizer and kernel CONFIG_CACHED_APPS_FREEZER) is a hard prerequisite. OEM power management customizations must not disable or delay the freezer. If a process executes code while compacted or during writeback, severe page-fault thrashing and race conditions occur.
  • Kernel and GKI ZRAM ioctls: The kernel ZRAM driver must enable CONFIG_ZRAM_ANDROID_IOCTL to expose ZRAM_ANDROID_IOC_PROCESS_RANGE_WRITEBACK, legacy ZRAM_ANDROID_IOC_PROCESS_WRITEBACK, and ZRAM_ANDROID_IOC_PROCESS_PREFETCH. These operations are available in the Android Common Kernel and standard Android Generic Kernel Images. If the underlying kernel lacks these ioctls, mmd rejects writeback operations and logs SKIPPED_UNSUPPORTED_BY_MMD.
  • Dedicated backing block storage (DM-based): A dedicated raw block partition (such as userdata_exp.zram) mapped through Device Mapper (dm-default-key) is strongly recommended for production devices. Using a file-backed loopback device introduces additional file system overhead, lock contention, and scheduling latency that can degrade system responsiveness.

Backing storage architecture

The design of the backing storage interface critically determines system responsiveness and memory compaction performance during ZRAM writeback.

Partition-based backing device (recommended for production)

In a partition-based architecture:

  • Dedicated flash partition: A dedicated flash partition (typically 2 GB to 4 GB, such as userdata_exp.zram) is carved out in the GPT or dynamic partition metadata.
  • Encrypted partition initialization: When mmd.zram.writeback.partition_name is set, vold maps the target partition with an ephemeral per-boot dm-default-key key to create /dev/block/mapper/zram_wb. On boot completion, mmd_setup sets /sys/block/zram0/compressed_writeback to 1 in both partition and loopback modes so compressed ZRAM objects write to the backing device configured in /sys/block/zram0/backing_dev without CPU decompression and recompression.
  • Direct block I/O and lower latency: Block I/O requests are submitted directly to the block device without file system layer overhead or loopback worker indirection, minimizing latency and improving throughput.

Loopback device backing file (not recommended for production)

Although a /dev/block/loop<N> loopback device can attach to a temporary file under /data/per_boot/zram, loopback backing is strongly discouraged for production devices:

  • Silent boot fallback: If mmd.zram.writeback.partition_name is set and /dev/block/mapper/zram_wb is missing or unreadable at boot, mmd_setup falls back to a loopback device and logs WritebackSetupSuccessLoopbackFallback instead of disabling writeback. When mmd.zram.writeback.partition_name is unset, mmd_setup attaches a loopback file under /data/per_boot/zram and logs WritebackSetupSuccess. Verify /sys/block/zram0/backing_dev on production builds to confirm partition mode is active.
  • File system and I/O serialization overhead: Routing block I/O through a loopback worker adds scheduler indirection and file system lock contention. On zoned file systems where unpinned /data files can't use direct I/O through O_DIRECT, buffered writeback serializes at queue depth 1 and stalls synchronous 4 KB foreground swap-in page faults, causing severe launch latency spikes and Application Not Responding timeouts.

For these reasons, don't use loopback device backing files in production. Use them only for testing, experimentation, or development environments.

End-to-end execution pipeline

The per-process ZRAM writeback workflow follows these steps:

  1. Process frozen: The user navigates away from an app, placing it in the CACHED_ACTIVITY state. The cached apps freezer freezes the process, halting all CPU execution and preventing asynchronous state changes.
  2. Process compaction: CachedAppOptimizer initiates COMPACT_PROFILE_FULL full compaction on the frozen process. The kernel swaps the process's anonymous pages into the ZRAM compressed memory pool.
  3. Cooldown delay: After compaction finishes, CachedAppOptimizer posts ZRAM_WRITEBACK_MSG on mCompactionHandler with the cooldown delay from config_zramWritebackWaitSeconds, which defaults to 600 seconds, before running policy checks.
  4. Eligibility evaluation: When the 600-second handler delay expires, maybeWritebackZram calls checkZramWritebackPolicy to confirm that the total post-compaction ZRAM swap footprint sits under the threshold, the process hosts UI activities, unswappable graphics allocations stay within limits, and mmd supports per-process ZRAM operations. Eligible processes log STARTED to ZramWritebackEvent.
  5. IPC dispatch to mmd: CachedAppOptimizer opens a secure pidfd process file descriptor and invokes IMmd.asyncWritebackProcessZramMemory(pfd, callback) over Binder to mmd.
  6. Page writeback to backing storage: mmd coordinates with the kernel to write the target pages to the backing block device.
  7. Completion callback and OOM score ceiling: mmd reports status and written byte count through IMmdProcessWritebackCallback. If writeback succeeds, ActivityManager sets isZramWrittenBack to true and OomAdjuster sends an oom_score_adj ceiling of 249 to lmkd with for_lmkd_only set to 1. That flag updates internal lmkd eviction priority and curAdj in ActivityManager without rewriting /proc/<pid>/oom_score_adj.
  8. Read-ahead on resume: When the user launches an activity and unfreezes the process with UNFREEZE_REASON_ACTIVITY, CachedAppOptimizer clears isZramWrittenBack and calls IMmd.asyncPrefetchProcessZramMemory with the process pidfd. The kernel handles ZRAM_ANDROID_IOC_PROCESS_PREFETCH and restores written-back compressed objects asynchronously into the ZRAM zsmalloc RAM pool through zram_populate_table so later page faults hit compressed RAM instead of blocking on flash I/O.

Handle unfreeze cancellation and read-ahead

CachedAppOptimizer coordinates cooldown delay handling and activity-triggered read-ahead across process freezes and wakes:

  • Cooldown timer dispatch: CachedAppOptimizer posts ZRAM_WRITEBACK_MSG on mCompactionHandler with a 600-second delay. When that delay expires, maybeWritebackZram calls checkZramWritebackPolicy and dispatches writeback if eligible.
  • Activity-triggered read-ahead: When a written-back process unfreezes with UNFREEZE_REASON_ACTIVITY, CachedAppOptimizer clears isZramWrittenBack and calls IMmd.asyncPrefetchProcessZramMemory to prefetch pages into ZRAM, logging PREFETCHED.
  • Background wake without activity resume: If a written-back process unfreezes for a non-activity reason such as a service or broadcast, CachedAppOptimizer clears isZramWrittenBack and resets its lmkd eviction priority without issuing prefetch.

Memory management interaction

Per-process ZRAM writeback coordinates with other platform memory subsystems:

CachedAppOptimizer
Coordinates the process lifecycle, compaction scheduling, cooldown timers, and eligibility evaluation in system_server.
Memory management daemon (mmd)
Manages backing block device lifecycle, enforces global daily flash write budgets, and acts as the privileged user-space daemon managing ZRAM writeback operations.

Process eligibility and policy

Writing to flash storage incurs an endurance and I/O cost. To maximize physical memory return on investment (ROI) while protecting flash longevity and user responsiveness, CachedAppOptimizer enforces strict eligibility policies before initiating writeback.

Process cached, frozen, and compacted
         │
         ▼
Has 600 s mCompactionHandler delay elapsed?
         │ Yes
         ▼
Is swap footprint < threshold? (zramUsedDeltaKb < threshold)
         │ Yes
         ▼
Does process host UI activities? (hasActivities == true)
         │ Yes
         ▼
Is GPU memory <= threshold? (gpuMemory <= gpuThreshold)
         │ Yes
         ▼
Is DMA-BUF memory <= threshold? (dmabufMemory <= dmabufThreshold)
         │ Yes
         ▼
Dispatch writeback to mmd ──► Write to storage ──► Cap OOM Adj at 249

Eligibility conditions

A process must satisfy all of the following conditions to be eligible for per-process ZRAM writeback:

  • Cooldown delay: After compaction, CachedAppOptimizer schedules ZRAM_WRITEBACK_MSG on mCompactionHandler with the delay from config_zramWritebackWaitSeconds, which defaults to 600 seconds. When that delay expires, maybeWritebackZram runs checkZramWritebackPolicy.
  • Swap footprint under config_zramWritebackThresholdKb: CachedAppOptimizer passes the process's total post-compaction ZRAM swap footprint from rssAfter[RSS_SWAP_INDEX] as zramUsedDeltaKb and requires that footprint to sit strictly under config_zramWritebackThresholdKb, which defaults to 300 MB. Processes at or above the threshold are rejected with SKIPPED_RSS_SWAP_TOO_HIGH, preventing oversized apps from dominating the daily flash write budget.
  • Hosting an activity: CachedAppOptimizer admits only processes with hasActivities set to true. Headless cached processes such as CACHED_EMPTY processes, stopped services, and broadcast receivers stay in compressed DRAM so lmkd terminates them under memory pressure instead of consuming flash write endurance and process slots on work with no UI state to resume. Platform policy enforces this filter with SKIPPED_NO_ACTIVITY rather than exposing a config.xml resource overlay.
  • GPU memory within config_zramWritebackGpuMemThresholdKb: Unswappable GPU graphics memory can't exceed config_zramWritebackGpuMemThresholdKb, which defaults to 60 KB. If an app holds large unreleased graphics textures or surfaces, those allocations remain pinned in physical DRAM, negating the benefit of writing out its CPU pages.
  • DMA-BUF memory within config_zramWritebackDmabufMemThresholdKb: Unswappable DMA-BUF memory can't exceed config_zramWritebackDmabufMemThresholdKb, which defaults to 0 KB. Pinned DMA-BUF allocations can't be written back to ZRAM storage. For example, camera and media apps hold pinned DMA-BUFs for image streams. This gate protects camera processes and maintains instant camera launch latency without requiring manual package allowlists or blocklists.

Live debugging process eligibility

To determine whether an app is eligible on a live device, inspect its state using the following diagnostic commands:

# 1. Verify that process hosts activities and is in CACHED_ACTIVITY state
adb shell dumpsys activity processes | grep -A 5 "com.example.app"

# 2. Check current freeze status in CachedAppOptimizer
adb shell dumpsys activity cao | grep -i "frozen"

# 3. Check swapped memory (compare to config_zramWritebackThresholdKb)
adb shell dumpsys meminfo com.example.app | grep "Swap:"

# 4. Check GPU memory (compare to config_zramWritebackGpuMemThresholdKb)
adb shell dumpsys meminfo com.example.app | grep "Graphics:"

# 5. Check DMA-BUF usage (compare to config_zramWritebackDmabufMemThresholdKb)
PID=$(adb shell pidof com.example.app)
adb shell dumpsys dmabuf $PID

Inspect writeback decisions using Statsd

CachedAppOptimizer logs a ZramWritebackEvent atom (atom ID 1202) to statsd whenever writeback is evaluated, admitted, rejected, or completed. To inspect real-time writeback decisions on an attached device or emulator:

# 1. Enable statsd pushed atom logging
adb root
adb shell cmd stats print-logs 1

# 2. Stream and format ZramWritebackEvent atoms in real time
adb shell logcat -s statsd:I | grep --line-buffered "(1202)" | awk '
BEGIN {
  e[0]="UNKNOWN"; e[1]="SKIPPED_NO_ACTIVITY"; e[2]="SKIPPED_RSS_SWAP_TOO_HIGH";
  e[3]="SKIPPED_MMD_SERVICE_UNAVAILABLE"; e[4]="SKIPPED_UNSUPPORTED_BY_MMD";
  e[5]="SKIPPED_OTHER_REASONS"; e[8]="DISABLED_BY_FLAG"; e[9]="STARTED";
  e[10]="SUCCEEDED"; e[11]="FAILED_DEVICE_FULL"; e[12]="FAILED_UNSUPPORTED";
  e[13]="FAILED_OTHER"; e[14]="PREFETCHED";
  e[15]="SKIPPED_GPU_MEMORY_TOO_HIGH"; e[16]="SKIPPED_DMA_BUF_TOO_HIGH";
}
function val(prefix, s,    p, sub_str) {
  p = index(s, prefix);
  if (p == 0) return "-";
  sub_str = substr(s, p + length(prefix));
  sub(/\[.*/, "", sub_str);
  return sub_str;
}
{
  ev = int(val("0x10000->", $0));
  status = (ev in e) ? e[ev] : ("EVENT_" ev);
  uid = val("0x20000->", $0);
  swap = val("0x50000->", $0);
  written = val("0x60000->", $0);
  dmabuf = val("0x90000->", $0);
  gpu = val("0xa0000->", $0);
  pid = val("0xc0000->", $0);
  printf "[%s %s] PID %s (UID %s)\n", $1, $2, pid, uid;
  printf "  Event: %s | Swap: %s KB | GPU: %s KB | DMA: %s KB\n", \
    status, swap, gpu, dmabuf;
  fflush();
}'

This formats raw statsd atom lines into a readable livestream:

[08-31 15:18:21.662] PID 4643 (UID 1000)
  Event: DISABLED_BY_FLAG | Swap: 0 KB | GPU: -1 KB | DMA: -1 KB
[08-31 15:25:10.120] PID 5120 (UID 10142)
  Event: SUCCEEDED | Swap: 24150 KB | GPU: 0 KB | DMA: 0 KB
[08-31 15:28:44.890] PID 5340 (UID 10189)
  Event: SKIPPED_DMA_BUF_TOO_HIGH | Swap: 15200 KB | DMA: 4096 KB

Key atom fields include:

  • 0x10000-><event_type>[I]: The event type enum describing admission, rejection, or execution status
  • 0x20000-><uid>[I][UID]: Process UID
  • 0x30000-><name>[S]: Process name (empty if identical to package name)
  • 0x40000-><0|1>[I]: Whether the process hosts activities (hasActivities)
  • 0x50000-><kb>[L]: Post-compaction ZRAM swap footprint (rss_swap_kb)
  • 0x60000-><bytes>[L]: Bytes written to backing store (zram_bytes_written)
  • 0x90000-><kb>[L]: Pinned DMA-BUF size (dma_buf_size_kb)
  • 0xa0000-><kb>[L]: Unswappable GPU memory size (gpu_memory_size_kb)
  • 0xc0000-><pid>[I]: Process ID (pid)

The event_type field indicates why a process was admitted or rejected:

SKIPPED_NO_ACTIVITY
Event 1: Process doesn't host UI activities, so hasActivities is false.
SKIPPED_RSS_SWAP_TOO_HIGH
Event 2: Post-compaction ZRAM swap footprint met or exceeded config_zramWritebackThresholdKb.
SKIPPED_MMD_SERVICE_UNAVAILABLE
Event 3: The mmd daemon Binder service is unavailable.
SKIPPED_UNSUPPORTED_BY_MMD
Event 4: Kernel lacks required ioctl support, including ZRAM_ANDROID_IOC_PROCESS_WRITEBACK.
DISABLED_BY_FLAG
Event 8: Per-process writeback is disabled by resource overlay or DeviceConfig.
STARTED
Event 9: Cooldown elapsed and eligibility checks passed, dispatching writeback to mmd.
SUCCEEDED
Event 10: Kernel writeback completed successfully.
FAILED_DEVICE_FULL
Event 11: Backing storage or /data partition free space margin is exhausted with ENOSPC.
FAILED_UNSUPPORTED
Event 12: mmd reported unsupported per-process ZRAM writeback at execution time.
FAILED_OTHER
Event 13: Unexpected I/O failure, stale pidfd, or Binder IPC exception.
PREFETCHED
Event 14: Unfreeze-path prefetch triggered on UNFREEZE_REASON_ACTIVITY.
SKIPPED_GPU_MEMORY_TOO_HIGH
Event 15: Unswappable GPU memory exceeds config_zramWritebackGpuMemThresholdKb.
SKIPPED_DMA_BUF_TOO_HIGH
Event 16: Pinned DMA-BUF memory exceeds config_zramWritebackDmabufMemThresholdKb.

Post-writeback OOM score adjustment

When writeback succeeds while the process remains frozen on the active session, ActivityManager sets isZramWrittenBack to true. On any unfreeze, CachedAppOptimizer immediately clears isZramWrittenBack to false. During OOM evaluation while frozen and written back, OomAdjuster clamps the effective OOM score:

if (app.isZramWrittenBack()) {
    app.setCurAdj(Math.min(adj, config_zramWritebackOomAdj));
}

Standard cached processes carry OOM scores in the 900 to 999 range, making them the primary targets for eviction by lmkd during memory pressure. Because a written-back process retains minimal physical DRAM overhead, capping its score at config_zramWritebackOomAdj, which defaults to 249, ranks it after PERCEPTIBLE_LOW_APP_ADJ at 250 and before PERCEPTIBLE_MEDIUM_APP_ADJ at 225 in lmkd eviction ordering.

For single-process priority updates through LMK_PROCPRIO, OomAdjuster sends the clamped score to lmkd with for_lmkd_only set to 1. Setting for_lmkd_only updates internal lmkd ranking and curAdj in ActivityManager while leaving /proc/<pid>/oom_score_adj untouched in the cached range. Batched LMK_PROCS_PRIO updates don't set for_lmkd_only.

Configuration and resource overlays

Device manufacturers configure per-process ZRAM writeback using standard Android RROs in frameworks/base/core/res/res/values/config.xml.

Resource overlay reference

The following table details all configuration overlays available for per-process ZRAM writeback:

Resource overlay name Type Default Description
config_zramWritebackPerProcessForceEnabled boolean false Force enables the per-process ZRAM writeback feature on the device. Set to true to activate per-process writeback.
config_zramWritebackWaitSeconds integer 600 (10 min) Cooldown duration in seconds that a process must remain continuously cached and frozen before writeback is initiated. If the process is unfrozen before this timer expires, writeback is canceled.
config_zramWritebackOomAdj integer 249 Target OOM adjustment score ceiling applied to cached processes after successful writeback. OomAdjuster clamps the effective OOM score using Math.min(adj, config_zramWritebackOomAdj), protecting the process from low-memory killer daemon (lmkd) eviction while its physical DRAM footprint is reclaimed.
config_zramWritebackThresholdKb integer 307200 (300 MB) Maximum compressed ZRAM memory footprint in kilobytes for a process to be eligible for writeback. A 300 MB threshold provides a recommended starting point, while 600 MB can be evaluated for higher memory savings if the device can handle the I/O load.
config_zramWritebackGpuMemThresholdKb integer 60 KB Maximum unswappable GPU memory usage in kilobytes for a process to be eligible for writeback. Processes exceeding this limit are skipped because pinned graphics memory remains in physical DRAM.
config_zramWritebackDmabufMemThresholdKb integer 0 KB Maximum unswappable DMA-BUF memory usage in kilobytes for a process to be eligible for writeback. Set to 0 to require zero unswappable DMA-BUF allocations.

Sample resource overlay snippet

To configure per-process ZRAM writeback for a device target, create or modify the resource overlay file in device/<oem>/<device>/overlay/frameworks/base/core/res/res/values/config.xml in your device tree:

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2026 The Android Open Source Project

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <!-- Force enable per-process ZRAM writeback -->
    <bool name="config_zramWritebackPerProcessForceEnabled">true</bool>

    <!-- Cooldown delay in seconds before writeback (600s = 10 minutes) -->
    <integer name="config_zramWritebackWaitSeconds">600</integer>

    <!-- Target OOM score adj cap for written-back cached processes -->
    <integer name="config_zramWritebackOomAdj">249</integer>

    <!-- Maximum swap footprint in KB eligible for writeback (300 MB) -->
    <integer name="config_zramWritebackThresholdKb">307200</integer>

    <!-- Maximum allowed unswappable GPU memory in KB (60 KB) -->
    <integer name="config_zramWritebackGpuMemThresholdKb">60</integer>

    <!-- Maximum allowed unswappable DMA-BUF memory in KB (0 KB) -->
    <integer name="config_zramWritebackDmabufMemThresholdKb">0</integer>
</resources>

OEM tuning guidelines and trade-off analysis

Tuning per-process ZRAM writeback requires balancing physical DRAM reclamation, flash memory endurance (TBW), and app relaunch responsiveness.

Process swap threshold versus daily write quota

The default value of config_zramWritebackThresholdKb is 300 MB (307200 KB). A 300 MB threshold serves as a solid baseline starting point for most devices. We also recommend evaluating a 600 MB (614400 KB) threshold to assess whether the device's storage subsystem and memory pipeline can handle the additional I/O load. If the device can sustain the higher load without latency degradation, a 600 MB threshold yields higher physical memory savings by admitting larger cached apps into writeback.

The goal when configuring config_zramWritebackThresholdKb is to pick a value that admits as many eligible writebacks as possible to maximize physical DRAM savings and app retention, without prematurely exhausting the daily flash writeback quota or inducing I/O contention.

Consider the following trade-offs when tuning this threshold:

  • Setting the threshold too low: Causes excessive policy skips on otherwise healthy candidates, resulting in missed DRAM savings and higher LMK kill rates for cached processes.
  • Setting the threshold too high: Admits unusually large apps (for example, heavy gaming apps or browsers consuming several hundred megabytes of swap) that can consume large portions of the daily write budget in a single operation, potentially exhausting the quota and preventing subsequent smaller writebacks from proceeding.

Device manufacturers should choose a threshold that maximizes admission rates across typical daily user workflows while comfortably remaining within the device's rolling daily write budget and I/O performance targets.

Unswappable memory risks (GPU and DMA-BUF)

When an app is cached, its anonymous memory can be compressed and written back. However, GPU textures, render buffers, and DMA-BUF allocations can't be swapped to ZRAM; they remain pinned in physical DRAM.

If an app holds 250 MB of GPU memory and 40 MB of CPU memory, writing back the 40 MB of CPU memory to flash still leaves 250 MB of unswappable memory in physical RAM. Gating writeback using config_zramWritebackGpuMemThresholdKb and config_zramWritebackDmabufMemThresholdKb ensures that flash write wear is only incurred when the app's overall physical DRAM footprint can be reclaimed.

These thresholds should be set to zero (0 KB) to ensure only processes with completely reclaimable memory are written back. However, depending on the device's graphics driver architecture, some GPU drivers might not fully release all small buffer allocations or context metadata when an app moves to the background. In such cases, setting config_zramWritebackGpuMemThresholdKb or config_zramWritebackDmabufMemThresholdKb to a small non-zero value (for example, 60 KB to 120 KB) is reasonable to avoid skipping otherwise eligible writebacks due to residual driver buffers.

Cooldown period versus freeze churn

The cooldown period balances prompt physical DRAM reclamation against the risk of writing back processes that the user quickly resumes during multitasking.

  • Short cooldown (< 180 seconds): Reclaims DRAM faster, but risks writing pages to flash for apps the user might return to soon after switching, incurring unnecessary flash write wear and relaunch page faults.
  • Recommended cooldown (600 seconds or 10 minutes): Lets transient app switches remain in fast ZRAM compressed RAM, initiating writeback only for processes that demonstrate stable background idle residency.
  • Long cooldown (> 1,800 seconds or 30 minutes): Minimizes flash writes, but delays memory reclamation during sustained memory pressure.

OOM adjustment 249 protection rationale

When a cached app's pages are written to flash, its physical RAM consumption is reduced. Setting config_zramWritebackOomAdj to 249 clamps the process's effective OOM score (Math.min(adj, 249)).

In Android's OOM adjustment hierarchy, 250 is PERCEPTIBLE_LOW_APP_ADJ. Setting config_zramWritebackOomAdj to 249 ranks written-back processes such that they're killed after PERCEPTIBLE_LOW_APP_ADJ (250), and before PERCEPTIBLE_MEDIUM_APP_ADJ (225). When lmkd seeks memory to reclaim, it targets standard cached apps (900+) and background services (500) that still consume physical DRAM, while preserving written-back apps in the process table with minimal physical memory overhead.

Flash endurance and daily write budget

Flash storage endurance is measured in Terabytes Written (TBW). To ensure device longevity over a three-to-five-year lifespan:

  • eMMC storage: Disable per-process ZRAM writeback (config_zramWritebackPerProcessForceEnabled = false) on devices with eMMC storage. Due to lower write endurance (fewer program or erase cycles) and half-duplex I/O constraints, background writeback on eMMC can accelerate flash degradation and introduce foreground I/O latency spikes.
  • UFS storage: On devices equipped with UFS storage (such as UFS 2.2, 3.1, or 4.0), per-process ZRAM writeback operates safely under the global daily writeback limit enforced by mmd (mmd.zram.writeback.max_bytes_per_day, default is 24 GiB per day).
  • Backing partition configuration: When using partition-based writeback, specify the target dynamic partition name using the system property mmd.zram.writeback.partition_name in device.mk or vendor.prop (for example, mmd.zram.writeback.partition_name=userdata_exp.zram). mmd communicates with vold to map this partition using dm-default-key on boot.
  • Disk storage capacity protection: mmd continuously coordinates with the /data user storage partition, monitoring remaining free disk space against mmd.zram.writeback.min_free_space_mib (default is 1.5 GiB headroom). If available user storage falls short of this safety margin, mmd rejects writebacks (FAILED_DEVICE_FULL or ENOSPC), preventing writeback from exhausting disk space or contributing to storage pressure.
  • Daily write quota: If the daily write quota is reached, mmd rejects further writeback requests (WritebackDailyLimitExceeded) until the rolling 24-hour quota advances.

The following table provides the recommended baseline configuration settings for devices supporting per-process ZRAM writeback:

Configuration item Recommended value Description and rationale
Backing storage architecture Dedicated partition (DM-based)
(loopback devices not recommended)
Allocate a dedicated dynamic partition (for example, userdata_exp.zram) mapped using dm-default-key. Loopback devices aren't recommended for production due to additional file system overhead and contention.
mmd.zram.writeback.partition_name userdata_exp.zram (or custom partition name) System property instructing mmd to use the named raw block partition for encrypted Device Mapper writeback.
config_zramWritebackPerProcessForceEnabled true (UFS)
false (eMMC)
Enable on all devices equipped with UFS storage (for example, UFS 2.2, 3.1, or 4.0) regardless of RAM capacity. Disable on devices equipped with eMMC flash storage to prevent accelerated flash wear and I/O bus contention.
config_zramWritebackWaitSeconds 600 (10 minutes) Ensures transient app switches remain in fast compressed ZRAM while initiating writeback only for stable background idle processes.
config_zramWritebackOomAdj 249 Clamps the effective OOM score of written-back processes, protecting them from lmkd termination ahead of non-written-back cached processes.
config_zramWritebackThresholdKb 307200 (300 MB baseline)
(or evaluate 614400 (600 MB))
The default 300 MB threshold provides a recommended baseline starting point. Evaluating a 600 MB threshold is recommended to determine whether the device can handle the additional I/O load, which yields higher memory savings.
config_zramWritebackGpuMemThresholdKb 60 (60 KB) Permits writeback for apps with minimal residual GPU memory while tolerating driver-level background buffer metadata.
config_zramWritebackDmabufMemThresholdKb 0 (0 KB) Requires zero unswappable DMA-BUF allocations to ensure writeback achieves maximum physical DRAM reclamation.

Verification and diagnostics

Use the following commands and telemetry tools to verify and troubleshoot per-process ZRAM writeback on test devices.

Inspect runtime configuration

To inspect active CachedAppOptimizer settings:

adb shell "dumpsys activity cao | grep -iE 'zram_?writeback'"

Expected output reflects the active configuration. zram_writeback_enabled reports the runtime DeviceConfig value and defaults to false when unset, whereas config_zramWritebackPerProcessForceEnabled=true enables writeback from the config.xml resource overlay:

  zram_writeback_enabled=false
  zram_writeback_wait_seconds=600
  zram_writeback_oom_adj=249
  zram_writeback_threshold_kb=307200
  zram_writeback_gpu_mem_threshold_kb=60
  zram_writeback_dmabuf_mem_threshold_kb=0
  config_zramWritebackPerProcessForceEnabled=true

Because OomAdjuster sets for_lmkd_only to 1 on single-process updates, /proc/<pid>/oom_score_adj keeps the process's cached 900 to 999 score. Verify the clamped cur score in ActivityManager and confirm the active backing block device:

adb shell "dumpsys activity processes com.example.app | grep 'oom adj:'"
adb shell "cat /sys/block/zram0/backing_dev"
adb shell "ls -l /dev/block/mapper/zram_wb"

Expected output for a written-back, frozen process includes cur=249, such as oom adj: max=1001 curRaw=900 setRaw=900 cur=249 set=249. Kernel backing_dev prints /dev/block/dm-<N> matching the /dev/block/mapper/zram_wb symlink in partition mode, or /dev/block/loop<N> if mmd_setup fell back to loopback.

Perfetto tracing

Per-process writeback operations emit asynchronous trace slices and instant events on the ZramWriteback track, defined by ATRACE_ZRAM_WRITEBACK_TRACK. When writeback completes, an instant trace event is emitted: ZramWriteback: writeback completed for <process_name>:<pid> status: <status>.

To capture a trace containing writeback activity:

adb shell perfetto \
  -c - --txt -o /data/misc/perfetto-traces/trace.perfetto-trace <<EOF
buffers: {
    size_kb: 65536
    fill_policy: RING_BUFFER
}
data_sources: {
    config {
        name: "linux.ftrace"
        ftrace_config {
            ftrace_events: "am/*"
            atrace_categories: "am"
            atrace_apps: "system_server"
        }
    }
}
duration_ms: 30000
EOF

Open the trace in the Perfetto UI and search for the ZramWriteback track to observe asyncWritebackProcessZramMemory duration, pidfd handover, and completion events.

To query writeback duration and events using PerfettoSQL:

SELECT
  slice.ts,
  slice.dur,
  slice.name,
  track.name AS track_name
FROM slice
JOIN track ON slice.track_id = track.id
WHERE track.name = 'ZramWriteback'
ORDER BY slice.ts ASC;

Kernel sysfs monitoring

Inspect backing block device and writeback statistics in sysfs:

# Check resolved backing block device (/dev/block/dm-<N> in partition mode)
adb shell cat /sys/block/zram0/backing_dev

# Check backing device page count, 4KB page reads, and 4KB page writes
adb shell cat /sys/block/zram0/bd_stat

# Check per-process ZRAM writeback execution statistics
adb shell cat /sys/block/zram0/proc_wb_stat

# Check overall ZRAM memory compression statistics
adb shell cat /sys/block/zram0/mm_stat

Statsd telemetry metrics

system_server logs writeback telemetry events to FrameworkStatsLog.ZRAM_WRITEBACK_EVENT (ZRAM_WRITEBACK_EVENT atom). The following table maps event types to their diagnostic meanings:

Event type Status Diagnostic explanation
STARTED Normal Cooldown elapsed and eligibility checks passed, opening a pidfd and dispatching writeback to mmd.
SUCCEEDED Normal Kernel successfully wrote compressed pages to backing storage.
PREFETCHED Normal Unfreeze-path prefetch triggered on UNFREEZE_REASON_ACTIVITY.
DISABLED_BY_FLAG Policy skip Per-process writeback is disabled by resource overlay or DeviceConfig.
SKIPPED_NO_ACTIVITY Policy skip Process doesn't host a UI activity (hasActivities == false).
SKIPPED_RSS_SWAP_TOO_HIGH Policy skip Post-compaction ZRAM swap footprint met or exceeded config_zramWritebackThresholdKb.
SKIPPED_GPU_MEMORY_TOO_HIGH Policy skip GPU memory exceeded config_zramWritebackGpuMemThresholdKb.
SKIPPED_DMA_BUF_TOO_HIGH Policy skip DMA-BUF memory exceeded config_zramWritebackDmabufMemThresholdKb.
SKIPPED_MMD_SERVICE_UNAVAILABLE System error system_server couldn't connect to the mmd service.
SKIPPED_UNSUPPORTED_BY_MMD System error Kernel ZRAM driver lacks per-process writeback support.
FAILED_DEVICE_FULL I/O failure Backing storage is full (ENOSPC).
FAILED_UNSUPPORTED System error mmd reported unsupported per-process ZRAM writeback at execution time.
FAILED_OTHER Error Unexpected I/O failure, stale pidfd, or IPC exception.