How to enable zRAM in Rocky Linux 9

Share on Social Media

Discover how to enable zRAM in Rocky Linux 9 with our step-by-step guide. Optimize your system’s performance and memory management by leveraging this compressed RAM feature for efficient resource utilization. #centlinux #linux #linuxswap

What is zRAM?:

zRAM, formerly called compcache, is a Linux kernel module for creating a compressed block device in RAM, i.e. a RAM disk with on-the-fly disk compression. The block device created with zRAM can then be used for swap (named as zswap) or as general-purpose RAM disk.

The zram module creates RAM-based block devices named /dev/zram<id> (<id> = 0, 1, …). Pages written to these disks are compressed and stored in memory itself. These disks allow very fast I/O and compression provides good amounts of memory savings. Some of the use cases include /tmp storage, use as swap disks, various caches under /var and maybe many more.

Statistics for individual zram devices are exported through sysfs nodes at /sys/block/zram<id>/

Does zRAM improve performance?

Yes, enabling zRAM can improve performance in certain scenarios, particularly on systems with limited physical memory (RAM) or systems that frequently encounter memory pressure. zRAM, also known as compressed RAM or virtual memory compression, works by compressing data stored in RAM, allowing more data to fit into memory and reducing the need for swapping data between RAM and disk storage (swap space).

Here are some ways in which zRAM can improve performance:

  1. Increased Effective Memory Capacity: By compressing data stored in RAM, zRAM effectively increases the amount of data that can be stored in memory. This can help mitigate the effects of running out of physical memory (RAM), reducing the likelihood of system slowdowns or crashes due to memory exhaustion.
  2. Reduced Swap Activity: zRAM can reduce the need for swapping data between RAM and disk storage (swap space). Swapping data to disk is much slower than accessing data in RAM, so reducing swap activity can lead to improved overall system responsiveness and reduced latency.
  3. Improved System Responsiveness: With less swapping to disk and more data fitting into memory, systems with zRAM enabled may experience improved responsiveness, particularly during periods of heavy memory usage or multitasking.
  4. Better Performance on Low-Memory Systems: On systems with limited physical memory, such as embedded devices or systems with small amounts of RAM, enabling zRAM can significantly improve performance by effectively expanding available memory capacity.
  5. Lower Disk I/O: Since zRAM reduces the need for swapping data to disk, it can lead to lower disk I/O (input/output) activity, which can reduce wear and tear on storage devices and improve overall system longevity.

It’s important to note that while zRAM can improve performance in many scenarios, the benefits may vary depending on the specific workload and system configuration. Additionally, enabling zRAM may consume some CPU resources for compression and decompression operations, so there may be a trade-off between CPU usage and memory utilization. Overall, zRAM can be a valuable tool for optimizing memory usage and improving system performance, particularly on systems with constrained memory resources.

zRAM vs zSwap

Zram and zswap are both technologies used in Linux systems to improve memory management by compressing memory pages. However, they serve slightly different purposes:

  1. Zram: Zram, also known as “compressed RAM,” creates a compressed block device in RAM. It takes a portion of your RAM and uses it as a compressed block device where pages that would normally be written to disk are stored in compressed form in RAM instead. This can be particularly useful in systems with limited RAM because it effectively increases the amount of available RAM by compressing data.
  2. Zswap: Zswap, on the other hand, is a lightweight compressed cache for swap pages. It doesn’t use a separate block device like Zram does. Instead, it sits between the swap subsystem and the CPU’s memory controller, compressing and caching swap pages in RAM before they’re written to disk. This can improve performance by reducing the amount of I/O operations to disk, especially in systems where disk I/O is a bottleneck.

In summary, while both Zram and Zswap involve compressing memory pages to improve memory management, Zram creates a compressed block device in RAM, while Zswap acts as a compressed cache for swap pages. The choice between them depends on factors such as system resources, workload, and specific performance requirements.

Recommended Online Training: Learn Bash Shell in Linux for Beginners

745772 0021show?id=oLRJ54lcVEg&offerid=1074652.745772&bids=1074652

Environment Specification

We are using a minimal Rocky Linux 9 virtual machine with following specifications.

  • CPU – 3.4 Ghz (2 cores)
  • Memory – 2 GB
  • Storage – 20 GB
  • Operating SystemRocky Linux release 9.1 (Blue Onyx)
  • Hostname – rocky9.centlinux.com
  • IP Address – 192.168.116.131/24

Enable zRAM Linux Kernel Module

By using a ssh client, login to your Linux server as root user.

Create a file with following content, to enable zRAM module during loading of your Linux Kernel.

# cat > /etc/modules-load.d/zram.conf << EOF
> zram
> EOF

Create configuration file for zRAM Kernel Module.

In this configuration file, you can set the number of zRAM block devices (num_devices=x) for your Linux server.

# cat > /etc/modprobe.d/zram.conf << EOF
> options zram num_devices=1
> EOF

Create a udev rule and specify the size of your zRAM device therein.

# cat > /etc/udev/rules.d/99-zram.rules << EOF
> KERNEL=="zram0", ATTR{disksize}="2G",TAG+="systemd"
> EOF

Open /etc/fstab file by using vim text editor.

# vi /etc/fstab

Find and comment the following line to disable automount of default swap partition. If you have more than one swap partitions then disable all of them.

#/dev/mapper/rl-swap     none                    swap    defaults        0 0

Create a systemd unit for zRAM to enable zswap partition on your Rocky Linux server.

By using vim text editor create a systemd unit.

# vi /etc/systemd/system/zram.service

Add following directives in this file.

[Unit]
Description=Swap with zram
After=multi-user.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStartPre=/sbin/mkswap /dev/zram0
ExecStart=/sbin/swapon /dev/zram0
ExecStop=/sbin/swapoff /dev/zram0

[Install]
WantedBy=multi-user.target

Enable zram.service by executing following command.

# systemctl enable zram.service
Created symlink /etc/systemd/system/multi-user.target.wants/zram.service → /etc/systemd/system/zram.service.

Reboot your Linux server to let it start with the new zswap partition.

# reboot

Create and Enable zSwap Memory

After reboot, check the status of your zram block devices by executing zramctl command.

# zramctl
NAME       ALGORITHM DISKSIZE DATA COMPR TOTAL STREAMS MOUNTPOINT
/dev/zram0 lzo-rle         2G   4K   74B   12K       1 [SWAP]

Check the status of zswap memory by using free command at Linux bash prompt.

# free -m
               total        used        free      shared  buff/cache   available
Mem:            1743         392        1323           5         174        1351
Swap:           2047           0        2047

Currently, the zswap memory is not in used, because we are using a test machine with almost zero load on it. The output may vary on a producion grade server.

You need to write a C language program, to create some imaginery load on your Rocky Linux server.

You can use vim text editor to write your C language program.

# vi ~/memeater.c

Add following lines of code in this file.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char** argv) {
    int max = -1;
    int mb = 0;
    int multiplier = 100; // allocate 1 MB every time unit. Increase this to e.g.100 to allocate 100 MB every time unit.
    char* buffer;

    if(argc > 1)
        max = atoi(argv[1]);

    while((buffer=malloc(multiplier * 1024*1024)) != NULL && mb != max) {
        memset(buffer, 1, multiplier * 1024*1024);
        mb++;
        printf("Allocated %d MBn", multiplier * mb);
        sleep(1); // time unit: 1 second
    }
    return 0;
}

You may need to install C language compiler to compile your program.

Use dnf command to install gcc package.

# dnf install -y gcc

Now, use gcc command to compile your C language program.

# gcc ~/memeater.c -o ~/memeater

Adjust the swappiness of your Linux server to 100% for immediate result.

# sysctl vm.swappiness=100

Now execute memeater command.

# ~/memeater

Open another ssh session and check the usage of zswap partition.

# free -m
               total        used        free      shared  buff/cache   available
Mem:            1743        1713          30           13        473          30
Swap:           2047         834        1213

Our zswap partition is in use now.

Reboot your Linux server now.

# reboot

Video Tutorial: How to enable zRAM in Linux

YouTube player

Final Thoughts

Unlock the potential for enhanced system performance and memory management with our guide to enable zRAM in Rocky Linux 9. By implementing this compressed RAM feature, you’ll optimize resource utilization and elevate your computing experience to new heights. Let this tutorial be your key to unleashing the full capabilities of your system.

Leave a Comment