요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
Attributes and statistics
zram.rst:197-316Device attribute와 io_stat·mm_stat·bd_stat field, deactivate·reset 절차를 정리합니다.
Optional memory features
zram.rst:317-569Idle tracking, backing-device writeback와 budget, secondary recompression, debug memory tracking을 다룹니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
========================================
zram: Compressed RAM-based block devices
========================================
Introduction
============
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>/
Usage
=====
There are several ways to configure and manage zram device(-s):
a) using zram and zram_control sysfs attributes
b) using zramctl utility, provided by util-linux ([email protected]).
In this document we will describe only 'manual' zram configuration steps,
IOW, zram and zram_control sysfs attributes.
In order to get a better idea about zramctl please consult util-linux
documentation, zramctl man-page or `zramctl --help`. Please be informed
that zram maintainers do not develop/maintain util-linux or zramctl, should
you have any questions please contact [email protected]
Following shows a typical sequence of steps for using zram.
WARNING
=======
For the sake of simplicity we skip error checking parts in most of the
examples below. However, it is your sole responsibility to handle errors.
zram sysfs attributes always return negative values in case of errors.
The list of possible return codes:
======== =============================================================
-EBUSY an attempt to modify an attribute that cannot be changed once
the device has been initialised. Please reset device first.
-ENOMEM zram was not able to allocate enough memory to fulfil your
needs.
-EINVAL invalid input has been provided.
-EAGAIN re-try operation later (e.g. when attempting to run recompress
and writeback simultaneously).
======== =============================================================
If you use 'echo', the returned value is set by the 'echo' utility,
and, in general case, something like::
echo foo > /sys/block/zram0/comp_algorithm
if [ $? -ne 0 ]; then
handle_error
fi
should suffice.
1) Load Module
==============
::
modprobe zram num_devices=4
This creates 4 devices: /dev/zram{0,1,2,3}
num_devices parameter is optional and tells zram how many devices should be
pre-created. Default: 1.
2) Select compression algorithm
===============================
Using comp_algorithm device attribute one can see available and
currently selected (shown in square brackets) compression algorithms,
or change the selected compression algorithm (once the device is initialised
there is no way to change compression algorithm).
Examples::
#show supported compression algorithms
cat /sys/block/zram0/comp_algorithm
lzo [lz4]
#select lzo compression algorithm
echo lzo > /sys/block/zram0/comp_algorithm
For the time being, the `comp_algorithm` content shows only compression
algorithms that are supported by zram.
3) Set compression algorithm parameters: Optional
=================================================
Compression algorithms may support specific parameters which can be
tweaked for particular dataset. ZRAM has an `algorithm_params` device
attribute which provides a per-algorithm params configuration.
For example, several compression algorithms support `level` parameter.
In addition, certain compression algorithms support pre-trained dictionaries,
which significantly change algorithms' characteristics. In order to configure
compression algorithm to use external pre-trained dictionary, pass full
path to the `dict` along with other parameters::
#pass path to pre-trained zstd dictionary
echo "algo=zstd dict=/etc/dictionary" > /sys/block/zram0/algorithm_params
#same, but using algorithm priority
echo "priority=1 dict=/etc/dictionary" > \
/sys/block/zram0/algorithm_params
#pass path to pre-trained zstd dictionary and compression level
echo "algo=zstd level=8 dict=/etc/dictionary" > \
/sys/block/zram0/algorithm_params
Parameters are algorithm specific: not all algorithms support pre-trained
dictionaries, not all algorithms support `level`. Furthermore, for certain
algorithms `level` controls the compression level (the higher the value the
better the compression ratio, it even can take negatives values for some
algorithms), for other algorithms `level` is acceleration level (the higher
the value the lower the compression ratio).
4) Set Disksize
===============
Set disk size by writing the value to sysfs node 'disksize'.
The value can be either in bytes or you can use mem suffixes.
Examples::
# Initialize /dev/zram0 with 50MB disksize
echo $((50*1024*1024)) > /sys/block/zram0/disksize
# Using mem suffixes
echo 256K > /sys/block/zram0/disksize
echo 512M > /sys/block/zram0/disksize
echo 1G > /sys/block/zram0/disksize
Note:
There is little point creating a zram of greater than twice the size of memory
since we expect a 2:1 compression ratio. Note that zram uses about 0.1% of the
size of the disk when not in use so a huge zram is wasteful.
5) Set memory limit: Optional
=============================
Set memory limit by writing the value to sysfs node 'mem_limit'.
The value can be either in bytes or you can use mem suffixes.
In addition, you could change the value in runtime.
Examples::
# limit /dev/zram0 with 50MB memory
echo $((50*1024*1024)) > /sys/block/zram0/mem_limit
# Using mem suffixes
echo 256K > /sys/block/zram0/mem_limit
echo 512M > /sys/block/zram0/mem_limit
echo 1G > /sys/block/zram0/mem_limit
# To disable memory limit
echo 0 > /sys/block/zram0/mem_limit
6) Activate
===========
::
mkswap /dev/zram0
swapon /dev/zram0
mkfs.ext4 /dev/zram1
mount /dev/zram1 /tmp
7) Add/remove zram devices
==========================
zram provides a control interface, which enables dynamic (on-demand) device
addition and removal.
In order to add a new /dev/zramX device, perform a read operation on the hot_add
attribute. This will return either the new device's device id (meaning that you
can use /dev/zram<id>) or an error code.
Example::
cat /sys/class/zram-control/hot_add
1
To remove the existing /dev/zramX device (where X is a device id)
execute::
echo X > /sys/class/zram-control/hot_remove
8) Stats
========
Per-device statistics are exported as various nodes under /sys/block/zram<id>/
A brief description of exported device attributes follows. For more details
please read Documentation/ABI/testing/sysfs-block-zram.
====================== ====== ===============================================
Name access description
====================== ====== ===============================================
disksize RW show and set the device's disk size
initstate RO shows the initialization state of the device
reset WO trigger device reset
mem_used_max WO reset the `mem_used_max` counter (see later)
mem_limit WO specifies the maximum amount of memory ZRAM can
use to store the compressed data
writeback_limit WO specifies the maximum amount of write IO zram
can write out to backing device as 4KB unit
writeback_limit_enable RW show and set writeback_limit feature
comp_algorithm RW show and change the compression algorithm
algorithm_params WO setup compression algorithm parameters
compact WO trigger memory compaction
debug_stat RO this file is used for zram debugging purposes
backing_dev RW set up backend storage for zram to write out
idle WO mark allocated slot as idle
====================== ====== ===============================================
User space is advised to use the following files to read the device statistics.
File /sys/block/zram<id>/stat
Represents block layer statistics. Read Documentation/block/stat.rst for
details.
File /sys/block/zram<id>/io_stat
The stat file represents device's I/O statistics not accounted by block
layer and, thus, not available in zram<id>/stat file. It consists of a
single line of text and contains the following stats separated by
whitespace:
============= =============================================================
failed_reads The number of failed reads
failed_writes The number of failed writes
invalid_io The number of non-page-size-aligned I/O requests
notify_free Depending on device usage scenario it may account
a) the number of pages freed because of swap slot free
notifications
b) the number of pages freed because of
REQ_OP_DISCARD requests sent by bio. The former ones are
sent to a swap block device when a swap slot is freed,
which implies that this disk is being used as a swap disk.
The latter ones are sent by filesystem mounted with
discard option, whenever some data blocks are getting
discarded.
============= =============================================================
File /sys/block/zram<id>/mm_stat
The mm_stat file represents the device's mm statistics. It consists of a single
line of text and contains the following stats separated by whitespace:
================ =============================================================
orig_data_size uncompressed size of data stored in this disk.
Unit: bytes
compr_data_size compressed size of data stored in this disk
mem_used_total the amount of memory allocated for this disk. This
includes allocator fragmentation and metadata overhead,
allocated for this disk. So, allocator space efficiency
can be calculated using compr_data_size and this statistic.
Unit: bytes
mem_limit the maximum amount of memory ZRAM can use to store
the compressed data
mem_used_max the maximum amount of memory zram has consumed to
store the data
same_pages the number of same element filled pages written to this disk.
No memory is allocated for such pages.
pages_compacted the number of pages freed during compaction
huge_pages the number of incompressible pages
huge_pages_since the number of incompressible pages since zram set up
================ =============================================================
File /sys/block/zram<id>/bd_stat
The bd_stat file represents a device's backing device statistics. It consists of
a single line of text and contains the following stats separated by whitespace:
============== =============================================================
bd_count size of data written in backing device.
Unit: 4K bytes
bd_reads the number of reads from backing device
Unit: 4K bytes
bd_writes the number of writes to backing device
Unit: 4K bytes
============== =============================================================
9) Deactivate
==============
::
swapoff /dev/zram0
umount /dev/zram1
10) Reset
=========
Write any positive value to 'reset' sysfs node::
echo 1 > /sys/block/zram0/reset
echo 1 > /sys/block/zram1/reset
This frees all the memory allocated for the given device and
resets the disksize to zero. You must set the disksize again
before reusing the device.
Optional Feature
================
IDLE pages tracking
-------------------
zram has built-in support for idle pages tracking (that is, allocated but
not used pages). This feature is useful for e.g. zram writeback and
recompression. In order to mark pages as idle, execute the following command::
echo all > /sys/block/zramX/idle
This will mark all allocated zram pages as idle. The idle mark will be
removed only when the page (block) is accessed (e.g. overwritten or freed).
Additionally, when CONFIG_ZRAM_TRACK_ENTRY_ACTIME is enabled, pages can be
marked as idle based on how many seconds have passed since the last access to
a particular zram page::
echo 86400 > /sys/block/zramX/idle
In this example, all pages which haven't been accessed in more than 86400
seconds (one day) will be marked idle.
writeback
---------
With CONFIG_ZRAM_WRITEBACK, zram can write idle/incompressible page
to backing storage rather than keeping it in memory.
To use the feature, admin should set up backing device via::
echo /dev/sda5 > /sys/block/zramX/backing_dev
before disksize setting. It supports only partitions at this moment.
If admin wants to use incompressible page writeback, they could do it via::
echo huge > /sys/block/zramX/writeback
Admin can request writeback of idle pages at right timing via::
echo idle > /sys/block/zramX/writeback
With the command, zram will writeback idle pages from memory to the storage.
Additionally, if a user choose to writeback only huge and idle pages
this can be accomplished with::
echo huge_idle > /sys/block/zramX/writeback
If a user chooses to writeback only incompressible pages (pages that none of
algorithms can compress) this can be accomplished with::
echo incompressible > /sys/block/zramX/writeback
If an admin wants to write a specific page in zram device to the backing device,
they could write a page index into the interface::
echo "page_index=1251" > /sys/block/zramX/writeback
In Linux 6.16 this interface underwent some rework. First, the interface
now supports `key=value` format for all of its parameters (`type=huge_idle`,
etc.) Second, the support for `page_indexes` was introduced, which specify
`LOW-HIGH` range (or ranges) of pages to be written-back. This reduces the
number of syscalls, but more importantly this enables optimal post-processing
target selection strategy. Usage example::
echo "type=idle" > /sys/block/zramX/writeback
echo "page_indexes=1-100 page_indexes=200-300" > \
/sys/block/zramX/writeback
We also now permit multiple page_index params per call and a mix of
single pages and page ranges::
echo page_index=42 page_index=99 page_indexes=100-200 \
page_indexes=500-700 > /sys/block/zramX/writeback
If there are lots of write IO with flash device, potentially, it has
flash wearout problem so that admin needs to design write limitation
to guarantee storage health for entire product life.
To overcome the concern, zram supports "writeback_limit" feature.
The "writeback_limit_enable"'s default value is 0 so that it doesn't limit
any writeback. IOW, if admin wants to apply writeback budget, they should
enable writeback_limit_enable via::
$ echo 1 > /sys/block/zramX/writeback_limit_enable
Once writeback_limit_enable is set, zram doesn't allow any writeback
until admin sets the budget via /sys/block/zramX/writeback_limit.
(If admin doesn't enable writeback_limit_enable, writeback_limit's value
assigned via /sys/block/zramX/writeback_limit is meaningless.)
If admin wants to limit writeback as per-day 400M, they could do it
like below::
$ MB_SHIFT=20
$ 4K_SHIFT=12
$ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
/sys/block/zram0/writeback_limit.
$ echo 1 > /sys/block/zram0/writeback_limit_enable
If admins want to allow further write again once the budget is exhausted,
they could do it like below::
$ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
/sys/block/zram0/writeback_limit
If an admin wants to see the remaining writeback budget since last set::
$ cat /sys/block/zramX/writeback_limit
If an admin wants to disable writeback limit, they could do::
$ echo 0 > /sys/block/zramX/writeback_limit_enable
The writeback_limit count will reset whenever you reset zram (e.g.,
system reboot, echo 1 > /sys/block/zramX/reset) so keeping how many of
writeback happened until you reset the zram to allocate extra writeback
budget in next setting is user's job.
If admin wants to measure writeback count in a certain period, they could
know it via /sys/block/zram0/bd_stat's 3rd column.
recompression
-------------
With CONFIG_ZRAM_MULTI_COMP, zram can recompress pages using alternative
(secondary) compression algorithms. The basic idea is that alternative
compression algorithm can provide better compression ratio at a price of
(potentially) slower compression/decompression speeds. Alternative compression
algorithm can, for example, be more successful compressing huge pages (those
that default algorithm failed to compress). Another application is idle pages
recompression - pages that are cold and sit in the memory can be recompressed
using more effective algorithm and, hence, reduce zsmalloc memory usage.
With CONFIG_ZRAM_MULTI_COMP, zram supports up to 4 compression algorithms:
one primary and up to 3 secondary ones. Primary zram compressor is explained
in "3) Select compression algorithm", secondary algorithms are configured
using recomp_algorithm device attribute.
Example:::
#show supported recompression algorithms
cat /sys/block/zramX/recomp_algorithm
#1: lzo lzo-rle lz4 lz4hc [zstd]
#2: lzo lzo-rle lz4 [lz4hc] zstd
Alternative compression algorithms are sorted by priority. In the example
above, zstd is used as the first alternative algorithm, which has priority
of 1, while lz4hc is configured as a compression algorithm with priority 2.
Alternative compression algorithm's priority is provided during algorithms
configuration:::
#select zstd recompression algorithm, priority 1
echo "algo=zstd priority=1" > /sys/block/zramX/recomp_algorithm
#select deflate recompression algorithm, priority 2
echo "algo=deflate priority=2" > /sys/block/zramX/recomp_algorithm
Another device attribute that CONFIG_ZRAM_MULTI_COMP enables is recompress,
which controls recompression.
Examples:::
#IDLE pages recompression is activated by `idle` mode
echo "type=idle" > /sys/block/zramX/recompress
#HUGE pages recompression is activated by `huge` mode
echo "type=huge" > /sys/block/zram0/recompress
#HUGE_IDLE pages recompression is activated by `huge_idle` mode
echo "type=huge_idle" > /sys/block/zramX/recompress
The number of idle pages can be significant, so user-space can pass a size
threshold (in bytes) to the recompress knob: zram will recompress only pages
of equal or greater size:::
#recompress all pages larger than 3000 bytes
echo "threshold=3000" > /sys/block/zramX/recompress
#recompress idle pages larger than 2000 bytes
echo "type=idle threshold=2000" > /sys/block/zramX/recompress
It is also possible to limit the number of pages zram re-compression will
attempt to recompress:::
echo "type=huge_idle max_pages=42" > /sys/block/zramX/recompress
During re-compression for every page, that matches re-compression criteria,
ZRAM iterates the list of registered alternative compression algorithms in
order of their priorities. ZRAM stops either when re-compression was
successful (re-compressed object is smaller in size than the original one)
and matches re-compression criteria (e.g. size threshold) or when there are
no secondary algorithms left to try. If none of the secondary algorithms can
successfully re-compressed the page such a page is marked as incompressible,
so ZRAM will not attempt to re-compress it in the future.
This re-compression behaviour, when it iterates through the list of
registered compression algorithms, increases our chances of finding the
algorithm that successfully compresses a particular page. Sometimes, however,
it is convenient (and sometimes even necessary) to limit recompression to
only one particular algorithm so that it will not try any other algorithms.
This can be achieved by providing a `algo` or `priority` parameter:::
#use zstd algorithm only (if registered)
echo "type=huge algo=zstd" > /sys/block/zramX/recompress
#use zstd algorithm only (if zstd was registered under priority 1)
echo "type=huge priority=1" > /sys/block/zramX/recompress
memory tracking
===============
With CONFIG_ZRAM_MEMORY_TRACKING, user can know information of the
zram block. It could be useful to catch cold or incompressible
pages of the process with*pagemap.
If you enable the feature, you could see block state via
/sys/kernel/debug/zram/zram0/block_state". The output is as follows::
300 75.033841 .wh...
301 63.806904 s.....
302 63.806919 ..hi..
303 62.801919 ....r.
304 146.781902 ..hi.n
First column
zram's block index.
Second column
access time since the system was booted
Third column
state of the block:
s:
same page
w:
written page to backing store
h:
huge page
i:
idle page
r:
recompressed page (secondary compression algorithm)
n:
none (including secondary) of algorithms could compress it
First line of above example says 300th block is accessed at 75.033841sec
and the block's state is huge so it is written back to the backing
storage. It's a debugging feature so anyone shouldn't rely on it to work
properly.
Nitin Gupta
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
소개·관리 방식·오류 처리
1-63`zram` module은 `/dev/zram<id>`(`<id>`는 0, 1, ...)라는 RAM 기반 block device를 만듭니다. 이 disk에 쓴 page는 압축되어 memory 자체에 저장됩니다. 매우 빠른 I/O와 압축에 따른 memory 절약을 제공하므로 `/tmp`, swap disk, `/var` 아래의 여러 cache 등에 사용할 수 있습니다.
각 zram device의 통계는 `/sys/block/zram<id>/` 아래 sysfs node로 내보냅니다. Device는 zram·zram_control sysfs attribute를 직접 사용하거나 util-linux가 제공하는 `zramctl` utility로 구성·관리할 수 있습니다.
이 문서는 zram 및 zram_control sysfs attribute를 사용하는 수동 구성만 설명합니다. `zramctl`은 util-linux 문서, man page 또는 `zramctl --help`를 참고해야 합니다. Zram maintainer는 util-linux나 zramctl을 개발·유지하지 않으므로 관련 질문은 `[email protected]`로 보냅니다.
수동 sysfs 방식과 util-linux 도구 방식의 책임 범위입니다.
아래 예제 대부분은 단순화를 위해 error checking을 생략합니다. Error 처리는 전적으로 사용자의 책임입니다. Zram sysfs attribute는 error가 나면 항상 negative value를 반환합니다.
수동 구성에서 처리해야 할 주요 negative return value입니다.
`echo`를 사용하면 shell에서 보이는 return value는 `echo` utility가 설정합니다. 일반적으로 명령의 `$?`를 검사해 error handler를 호출하면 충분합니다.
echo foo > /sys/block/zram0/comp_algorithm
if [ $? -ne 0 ]; then
handle_error
fi
Module load와 compression algorithm 선택
64-95`num_devices=4`로 module을 load하면 `/dev/zram0`부터 `/dev/zram3`까지 네 device를 만듭니다. Optional `num_devices` parameter는 미리 만들 device 수이며 default는 1입니다.
::
modprobe zram num_devices=4
This creates 4 devices: /dev/zram{0,1,2,3}
num_devices parameter is optional and tells zram how many devices should be
pre-created. Default: 1.
`comp_algorithm` device attribute를 읽으면 사용 가능한 compression algorithm과 현재 선택된 algorithm을 볼 수 있습니다. 현재 선택 항목은 대괄호로 표시됩니다. Device를 초기화한 뒤에는 compression algorithm을 바꿀 수 없습니다.
Examples::
#show supported compression algorithms
cat /sys/block/zram0/comp_algorithm
lzo [lz4]
#select lzo compression algorithm
echo lzo > /sys/block/zram0/comp_algorithm
현재 `comp_algorithm` 내용에는 zram이 지원하는 compression algorithm만 표시됩니다.
초기화 전에 algorithm을 확인하고 선택해야 합니다.
Compression algorithm parameter
96-126Compression algorithm은 dataset에 맞게 조정할 고유 parameter를 지원할 수 있습니다. ZRAM의 `algorithm_params` device attribute는 algorithm별 parameter configuration을 제공합니다.
여러 algorithm은 `level`을 지원하며 일부는 pre-trained dictionary도 지원합니다. 외부 dictionary를 쓰려면 다른 parameter와 함께 `dict`의 full path를 넘깁니다. Algorithm 이름 대신 등록 priority로 대상을 지정할 수도 있습니다.
#pass path to pre-trained zstd dictionary
echo "algo=zstd dict=/etc/dictionary" > /sys/block/zram0/algorithm_params
#same, but using algorithm priority
echo "priority=1 dict=/etc/dictionary" > \
/sys/block/zram0/algorithm_params
#pass path to pre-trained zstd dictionary and compression level
echo "algo=zstd level=8 dict=/etc/dictionary" > \
/sys/block/zram0/algorithm_params
Parameter는 algorithm마다 다릅니다. 모든 algorithm이 dictionary나 `level`을 지원하는 것은 아닙니다. 어떤 algorithm에서 `level`은 compression level이며 값이 클수록 ratio가 좋아지고 negative value도 허용할 수 있습니다. 다른 algorithm에서는 acceleration level이어서 값이 클수록 compression ratio가 낮아집니다.
같은 parameter 이름도 compressor에 따라 의미가 달라질 수 있습니다.
Disk size·memory limit·활성화
127-176`disksize` sysfs node에 byte 값이나 memory suffix가 붙은 값을 써서 device disk size를 정합니다.
# Initialize /dev/zram0 with 50MB disksize
echo $((50*1024*1024)) > /sys/block/zram0/disksize
# Using mem suffixes
echo 256K > /sys/block/zram0/disksize
echo 512M > /sys/block/zram0/disksize
echo 1G > /sys/block/zram0/disksize
일반적으로 2:1 compression ratio를 예상하므로 memory의 두 배보다 큰 zram은 이점이 적습니다. 사용하지 않는 상태에서도 disk size의 약 0.1%를 사용하므로 지나치게 큰 zram은 낭비입니다.
Optional `mem_limit` sysfs node는 compressed data 저장에 사용할 physical memory 최대량을 정합니다. Byte나 memory suffix를 사용할 수 있고 runtime에도 바꿀 수 있습니다. 0을 쓰면 제한을 끕니다.
# limit /dev/zram0 with 50MB memory
echo $((50*1024*1024)) > /sys/block/zram0/mem_limit
# Using mem suffixes
echo 256K > /sys/block/zram0/mem_limit
echo 512M > /sys/block/zram0/mem_limit
echo 1G > /sys/block/zram0/mem_limit
# To disable memory limit
echo 0 > /sys/block/zram0/mem_limit
Swap으로 활성화하려면 `mkswap`과 `swapon`을 사용합니다. Filesystem storage로 쓰려면 filesystem을 만들고 mount합니다.
::
mkswap /dev/zram0
swapon /dev/zram0
mkfs.ext4 /dev/zram1
mount /dev/zram1 /tmp
Logical capacity와 실제 compressed-memory 예산은 별개입니다.
Algorithm 선택 뒤 size를 정하고 용도에 맞게 활성화합니다.
Zram device 동적 추가·제거
177-196Zram control interface는 device를 필요할 때 동적으로 추가·제거할 수 있게 합니다. `hot_add` attribute를 read하면 새 `/dev/zramX`를 추가하고 device ID를 반환합니다. 실패하면 error code를 반환합니다.
Example::
cat /sys/class/zram-control/hot_add
1
기존 `/dev/zramX`를 제거하려면 X에 device ID를 넣어 `hot_remove`에 씁니다.
To remove the existing /dev/zramX device (where X is a device id)
execute::
echo X > /sys/class/zram-control/hot_remove
Read가 추가를, write가 제거를 수행합니다.
Device attribute와 access mode
197-225Device별 통계와 control은 `/sys/block/zram<id>/` 아래 node로 제공합니다. 더 자세한 ABI는 `Documentation/ABI/testing/sysfs-block-zram`을 참고합니다.
원문의 RW·RO·WO access와 기능입니다.
Block·I/O·memory·backing 통계
226-296User space는 다음 file을 사용해 device 통계를 읽는 것이 권장됩니다. `/sys/block/zram<id>/stat`은 block layer 통계이며 자세한 내용은 `Documentation/block/stat.rst`를 참고합니다.
`io_stat`은 block layer가 집계하지 않아 `zram<id>/stat`에 없는 device I/O 통계를 whitespace로 구분한 한 줄로 제공합니다.
Block layer 밖에서 집계되는 zram I/O 통계입니다.
`mm_stat`은 device memory-management 통계를 whitespace로 구분한 한 줄로 제공합니다.
압축 전후 크기, allocator overhead와 page 특성을 보여 줍니다.
`bd_stat`은 backing device 통계를 whitespace로 구분한 한 줄로 제공합니다.
Backing device의 data 양과 operation 수를 4-KiB 단위로 집계합니다.
비활성화와 reset
297-316Swap device는 `swapoff`, mounted filesystem은 `umount`로 먼저 비활성화합니다.
::
swapoff /dev/zram0
umount /dev/zram1
`reset` sysfs node에 positive value를 쓰면 해당 device에 할당된 memory를 모두 해제하고 `disksize`를 0으로 되돌립니다. Device를 다시 사용하려면 disk size를 다시 설정해야 합니다.
Write any positive value to 'reset' sysfs node::
echo 1 > /sys/block/zram0/reset
echo 1 > /sys/block/zram1/reset
This frees all the memory allocated for the given device and
resets the disksize to zero. You must set the disksize again
before reusing the device.
사용 중인 역할을 해제한 뒤 reset하고 다시 초기화합니다.
Idle page tracking
317-339Zram은 할당되었지만 사용되지 않는 idle page를 추적할 수 있습니다. 이 기능은 writeback과 recompression에 유용합니다. `idle`에 `all`을 쓰면 할당된 모든 zram page를 idle로 표시합니다.
zram has built-in support for idle pages tracking (that is, allocated but
not used pages). This feature is useful for e.g. zram writeback and
recompression. In order to mark pages as idle, execute the following command::
echo all > /sys/block/zramX/idle
Idle mark는 해당 page(block)에 access해 overwrite하거나 free할 때만 제거됩니다. `CONFIG_ZRAM_TRACK_ENTRY_ACTIME`을 enable하면 마지막 access 뒤 지난 초 수를 기준으로 page를 idle 표시할 수 있습니다.
Additionally, when CONFIG_ZRAM_TRACK_ENTRY_ACTIME is enabled, pages can be
marked as idle based on how many seconds have passed since the last access to
a particular zram page::
echo 86400 > /sys/block/zramX/idle
In this example, all pages which haven't been accessed in more than 86400
seconds (one day) will be marked idle.
모든 page 또는 access age 기준으로 idle set을 만듭니다.
Writeback 대상과 page 선택
340-391`CONFIG_ZRAM_WRITEBACK`을 사용하면 idle 또는 incompressible page를 memory에 유지하지 않고 backing storage에 쓸 수 있습니다. `disksize`를 설정하기 전에 `backing_dev`를 지정해야 하며 현재는 partition만 지원합니다.
With CONFIG_ZRAM_WRITEBACK, zram can write idle/incompressible page
to backing storage rather than keeping it in memory.
To use the feature, admin should set up backing device via::
echo /dev/sda5 > /sys/block/zramX/backing_dev
before disksize setting. It supports only partitions at this moment.
`writeback`에 type을 써서 대상을 고릅니다. `huge`는 기존 huge-page 분류, `idle`은 idle page, `huge_idle`은 두 조건을 모두 만족하는 page, `incompressible`은 어떤 algorithm도 압축하지 못한 page를 내보냅니다.
If admin wants to use incompressible page writeback, they could do it via::
echo huge > /sys/block/zramX/writeback
Admin can request writeback of idle pages at right timing via::
echo idle > /sys/block/zramX/writeback
With the command, zram will writeback idle pages from memory to the storage.
Additionally, if a user choose to writeback only huge and idle pages
this can be accomplished with::
echo huge_idle > /sys/block/zramX/writeback
If a user chooses to writeback only incompressible pages (pages that none of
algorithms can compress) this can be accomplished with::
echo incompressible > /sys/block/zramX/writeback
Writeback command가 선택하는 page 집합입니다.
특정 page 하나를 쓰려면 `page_index`를 지정합니다. Linux 6.16부터 모든 parameter가 `key=value` 형식을 지원하고, `page_indexes=LOW-HIGH`로 하나 이상의 범위를 지정할 수 있습니다. 이 방식은 syscall 수를 줄이고 writeback 뒤 처리할 target을 효율적으로 선택하게 합니다.
If an admin wants to write a specific page in zram device to the backing device,
they could write a page index into the interface::
echo "page_index=1251" > /sys/block/zramX/writeback
In Linux 6.16 this interface underwent some rework. First, the interface
now supports `key=value` format for all of its parameters (`type=huge_idle`,
etc.) Second, the support for `page_indexes` was introduced, which specify
`LOW-HIGH` range (or ranges) of pages to be written-back. This reduces the
number of syscalls, but more importantly this enables optimal post-processing
target selection strategy. Usage example::
echo "type=idle" > /sys/block/zramX/writeback
echo "page_indexes=1-100 page_indexes=200-300" > \
/sys/block/zramX/writeback
We also now permit multiple page_index params per call and a mix of
single pages and page ranges::
echo page_index=42 page_index=99 page_indexes=100-200 \
page_indexes=500-700 > /sys/block/zramX/writeback
한 호출에 여러 `page_index`를 넣거나 single page와 `page_indexes` range를 섞을 수도 있습니다.
Type, single index, range를 조합하는 인터페이스입니다.
Writeback budget와 flash 수명 관리
392-439Flash device에 write I/O가 많으면 wearout 문제가 생길 수 있으므로 제품 수명 동안 storage health를 지킬 write 제한을 설계해야 합니다. Zram은 이를 위해 `writeback_limit` 기능을 제공합니다.
`writeback_limit_enable` default는 0이라 제한하지 않습니다. Budget을 적용하려면 먼저 이 기능을 enable합니다. Enable한 뒤에는 `/sys/block/zramX/writeback_limit`에 budget을 설정하기 전까지 writeback을 허용하지 않습니다. 반대로 enable하지 않은 상태에서 쓴 limit 값은 의미가 없습니다.
To overcome the concern, zram supports "writeback_limit" feature.
The "writeback_limit_enable"'s default value is 0 so that it doesn't limit
any writeback. IOW, if admin wants to apply writeback budget, they should
enable writeback_limit_enable via::
$ echo 1 > /sys/block/zramX/writeback_limit_enable
Once writeback_limit_enable is set, zram doesn't allow any writeback
until admin sets the budget via /sys/block/zramX/writeback_limit.
(If admin doesn't enable writeback_limit_enable, writeback_limit's value
assigned via /sys/block/zramX/writeback_limit is meaningless.)
하루 400 MiB budget 예제는 MiB를 4-KiB unit으로 변환해 limit에 쓰고 기능을 enable합니다.
If admin wants to limit writeback as per-day 400M, they could do it
like below::
$ MB_SHIFT=20
$ 4K_SHIFT=12
$ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
/sys/block/zram0/writeback_limit.
$ echo 1 > /sys/block/zram0/writeback_limit_enable
Budget을 모두 쓴 뒤 다시 허용하려면 새 budget을 limit에 씁니다. 남은 budget은 `writeback_limit`을 읽어 확인하고, 기능을 끄려면 enable node에 0을 씁니다.
If admins want to allow further write again once the budget is exhausted,
they could do it like below::
$ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
/sys/block/zram0/writeback_limit
If an admin wants to see the remaining writeback budget since last set::
$ cat /sys/block/zramX/writeback_limit
If an admin wants to disable writeback limit, they could do::
$ echo 0 > /sys/block/zramX/writeback_limit_enable
Zram reset, system reboot 또는 `echo 1 > /sys/block/zramX/reset` 때 writeback-limit count도 reset됩니다. 다음 설정에서 추가 budget을 올바르게 배정하려면 reset 전까지 발생한 writeback 양을 user가 보존해야 합니다. 특정 기간의 writeback 수는 `/sys/block/zram0/bd_stat` 세 번째 column으로 측정할 수 있습니다.
4-KiB 단위 budget을 enable·소비·보충·reset합니다.
Secondary compressor와 recompression
440-526`CONFIG_ZRAM_MULTI_COMP`를 사용하면 alternative secondary compression algorithm으로 page를 다시 압축할 수 있습니다. Secondary algorithm은 느릴 수 있지만 더 나은 compression ratio를 제공할 수 있습니다. Primary algorithm이 압축하지 못한 huge page나 memory에 오래 머문 cold idle page를 더 효과적으로 압축해 zsmalloc memory 사용량을 줄이는 것이 대표 용도입니다.
Zram은 primary 하나와 secondary 최대 세 개, 합계 최대 네 compression algorithm을 지원합니다. Primary compressor는 앞의 compression-algorithm 선택 절차로 정하고, secondary는 `recomp_algorithm` device attribute로 priority와 함께 구성합니다.
Example:::
#show supported recompression algorithms
cat /sys/block/zramX/recomp_algorithm
#1: lzo lzo-rle lz4 lz4hc [zstd]
#2: lzo lzo-rle lz4 [lz4hc] zstd
Alternative compression algorithms are sorted by priority. In the example
above, zstd is used as the first alternative algorithm, which has priority
of 1, while lz4hc is configured as a compression algorithm with priority 2.
Alternative compression algorithm's priority is provided during algorithms
configuration:::
#select zstd recompression algorithm, priority 1
echo "algo=zstd priority=1" > /sys/block/zramX/recomp_algorithm
#select deflate recompression algorithm, priority 2
echo "algo=deflate priority=2" > /sys/block/zramX/recomp_algorithm
예제의 secondary compressor 등록 순서입니다.
`recompress` attribute가 recompression 실행을 제어합니다. `type=idle`, `type=huge`, `type=huge_idle`로 page 집합을 선택합니다.
Another device attribute that CONFIG_ZRAM_MULTI_COMP enables is recompress,
which controls recompression.
Examples:::
#IDLE pages recompression is activated by `idle` mode
echo "type=idle" > /sys/block/zramX/recompress
#HUGE pages recompression is activated by `huge` mode
echo "type=huge" > /sys/block/zram0/recompress
#HUGE_IDLE pages recompression is activated by `huge_idle` mode
echo "type=huge_idle" > /sys/block/zramX/recompress
Idle page 수가 많을 수 있으므로 byte 단위 `threshold`를 주면 object 크기가 그 이상인 page만 다시 압축합니다. `max_pages`는 시도할 page 수를 제한합니다.
The number of idle pages can be significant, so user-space can pass a size
threshold (in bytes) to the recompress knob: zram will recompress only pages
of equal or greater size:::
#recompress all pages larger than 3000 bytes
echo "threshold=3000" > /sys/block/zramX/recompress
#recompress idle pages larger than 2000 bytes
echo "type=idle threshold=2000" > /sys/block/zramX/recompress
It is also possible to limit the number of pages zram re-compression will
attempt to recompress:::
echo "type=huge_idle max_pages=42" > /sys/block/zramX/recompress
Type과 size·count 제한을 함께 적용할 수 있습니다.
조건에 맞는 각 page에 대해 ZRAM은 등록된 secondary algorithm을 priority 순서로 시도합니다. 재압축 object가 원래보다 작고 threshold 같은 조건도 만족하면 성공으로 멈춥니다. 모든 secondary를 소진해도 성공하지 못하면 page를 incompressible로 표시하고 앞으로 다시 시도하지 않습니다.
여러 algorithm을 순회하면 특정 page를 압축할 algorithm을 찾을 가능성이 커집니다. 다른 algorithm을 시도하지 않고 하나만 제한해야 할 때는 `algo` 또는 `priority`를 지정합니다.
This can be achieved by providing a `algo` or `priority` parameter:::
#use zstd algorithm only (if registered)
echo "type=huge algo=zstd" > /sys/block/zramX/recompress
#use zstd algorithm only (if zstd was registered under priority 1)
echo "type=huge priority=1" > /sys/block/zramX/recompress
Filter를 통과한 page에 secondary compressor를 priority 순으로 적용합니다.
Block state memory tracking
527-569`CONFIG_ZRAM_MEMORY_TRACKING`을 사용하면 zram block 정보를 확인할 수 있습니다. Process의 cold 또는 incompressible page를 `pagemap`과 함께 찾는 데 유용할 수 있습니다.
기능을 enable하면 `/sys/kernel/debug/zram/zram0/block_state`에서 block state를 볼 수 있습니다. 출력의 첫 column은 zram block index, 두 번째는 system boot 이후 access time, 세 번째는 block state flag입니다.
If you enable the feature, you could see block state via
/sys/kernel/debug/zram/zram0/block_state". The output is as follows::
300 75.033841 .wh...
301 63.806904 s.....
302 63.806919 ..hi..
303 62.801919 ....r.
304 146.781902 ..hi.n
세 번째 column의 문자 위치가 나타내는 상태입니다.
예제 첫 줄은 300번째 block이 boot 후 75.033841초에 access되었고 huge state이며 backing storage에 writeback되었음을 뜻합니다. 이 인터페이스는 debugging feature이므로 정상 동작을 보장하는 안정적 ABI로 의존해서는 안 됩니다.
원문 저자는 Nitin Gupta이며 연락처는 `[email protected]`입니다.
Configuration and activation
zram.rst:1-196Sysfs로 compressor·size·memory limit을 설정하고 swap 또는 filesystem으로 활성화하며 device를 hot-add/remove합니다.