Enable zram on Android

1 minute read

What is zram

Kernel Documentation says it is Compressed RAM based block devices.

How to enable zram on Android devices

Enable kernel options

CONFIG_SWAP
CONFIG_CGROUP_MEM_RES_CTLR
CONFIG_CGROUP_MEM_RES_CTLR_SWAP
CONFIG_ZRAM

init.rc

# ZRAM setup
    write /sys/block/zram0/comp_algorithm lz4
    write /proc/sys/vm/page-cluster 0

add above to init.rc on init section.

zram mount

mount zram in fstab:

/dev/block/zram0      none       swap    defaults     zramsize=536870912,max_comp_streams=4

sepolicy

file_contexts

/dev/block/zram0 u:object_r:swap_block_device:s0

swapon_all /fstab.x

zram config (not used any more)

#!/system/bin/sh

# load dependency modules
NRDEVICES=$(grep -c ^processor /proc/cpuinfo | sed 's/^0$/1/')
if modinfo /system/lib/modules/zram.ko | grep -q ' zram_num_devices:' 2>/dev/null; then
  MODPROBE_ARGS="zram_num_devices=${NRDEVICES}"
elif modinfo /system/lib/modules/zram.ko | grep -q ' num_devices:' 2>/dev/null; then
  MODPROBE_ARGS="num_devices=${NRDEVICES}"
else
  exit 1
fi
insmod /system/lib/modules/zram.ko $MODPROBE_ARGS

# Calculate memory to use for zram (1/4 of ram)
totalmem=`LC_ALL=C free | grep -e "^Mem:" | sed -e 's/^Mem: *//' -e 's/  *.*//'`
mem=$((totalmem / 4 / ${NRDEVICES}))

# initialize the devices
for i in $(seq ${NRDEVICES}); do
    DEVNUM=$((i - 1))
    echo $mem > /sys/block/zram${DEVNUM}/disksize
    mkswap /dev/block/zram${DEVNUM}
    swapon -p 5 /dev/block/zram${DEVNUM}
done

After android bootup, swap partition can be viewed through procfs:

rpi3:/mnt/media_rw # cat /proc/swaps
Filename				Type		Size	Used	Priority
/dev/block/zram0                        partition	47656	0	5
/dev/block/zram1                        partition	47656	0	5
/dev/block/zram2                        partition	47656	0	5
/dev/block/zram3                        partition	47656	0	5

In case zram was built into kernel pass zram parameter from bootargs:

zram.num_devices=4

Resources

Performance

zram-perf can be used for read/write speed test.