요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
=====
zswap
=====
Overview
========
Zswap is a lightweight compressed cache for swap pages. It takes pages that are
in the process of being swapped out and attempts to compress them into a
dynamically allocated RAM-based memory pool. zswap basically trades CPU cycles
for potentially reduced swap I/O. This trade-off can also result in a
significant performance improvement if reads from the compressed cache are
faster than reads from a swap device.
Some potential benefits:
* Desktop/laptop users with limited RAM capacities can mitigate the
performance impact of swapping.
* Overcommitted guests that share a common I/O resource can
dramatically reduce their swap I/O pressure, avoiding heavy handed I/O
throttling by the hypervisor. This allows more work to get done with less
impact to the guest workload and guests sharing the I/O subsystem
* Users with SSDs as swap devices can extend the life of the device by
drastically reducing life-shortening writes.
Zswap evicts pages from compressed cache on an LRU basis to the backing swap
device when the compressed pool reaches its size limit. This requirement had
been identified in prior community discussions.
Whether Zswap is enabled at the boot time depends on whether
the ``CONFIG_ZSWAP_DEFAULT_ON`` Kconfig option is enabled or not.
This setting can then be overridden by providing the kernel command line
``zswap.enabled=`` option, for example ``zswap.enabled=0``.
Zswap can also be enabled and disabled at runtime using the sysfs interface.
An example command to enable zswap at runtime, assuming sysfs is mounted
at ``/sys``, is::
echo 1 > /sys/module/zswap/parameters/enabled
When zswap is disabled at runtime it will stop storing pages that are
being swapped out. However, it will _not_ immediately write out or fault
back into memory all of the pages stored in the compressed pool. The
pages stored in zswap will remain in the compressed pool until they are
either invalidated or faulted back into memory. In order to force all
pages out of the compressed pool, a swapoff on the swap device(s) will
fault back into memory all swapped out pages, including those in the
compressed pool.
Design
======
Zswap receives pages for compression from the swap subsystem and is able to
evict pages from its own compressed pool on an LRU basis and write them back to
the backing swap device in the case that the compressed pool is full.
Zswap makes use of zsmalloc for the managing the compressed memory pool. Each
allocation in zsmalloc is not directly accessible by address. Rather, a handle is
returned by the allocation routine and that handle must be mapped before being
accessed. The compressed memory pool grows on demand and shrinks as compressed
pages are freed. The pool is not preallocated.
When a swap page is passed from swapout to zswap, zswap maintains a mapping
of the swap entry, a combination of the swap type and swap offset, to the
zsmalloc handle that references that compressed swap page. This mapping is
achieved with a red-black tree per swap type. The swap offset is the search
key for the tree nodes.
During a page fault on a PTE that is a swap entry, the swapin code calls the
zswap load function to decompress the page into the page allocated by the page
fault handler.
Once there are no PTEs referencing a swap page stored in zswap (i.e. the count
in the swap_map goes to 0) the swap code calls the zswap invalidate function
to free the compressed entry.
Zswap seeks to be simple in its policies. Sysfs attributes allow for one user
controlled policy:
* max_pool_percent - The maximum percentage of memory that the compressed
pool can occupy.
The default compressor is selected in ``CONFIG_ZSWAP_COMPRESSOR_DEFAULT``
Kconfig option, but it can be overridden at boot time by setting the
``compressor`` attribute, e.g. ``zswap.compressor=lzo``.
It can also be changed at runtime using the sysfs "compressor"
attribute, e.g.::
echo lzo > /sys/module/zswap/parameters/compressor
When the compressor parameter is changed at runtime, any existing compressed
pages are not modified; they are left in their own pool. When a request is
made for a page in an old pool, it is uncompressed using its original
compressor. Once all pages are removed from an old pool, the pool and its
compressor are freed.
Some of the pages in zswap are same-value filled pages (i.e. contents of the
page have same value or repetitive pattern). These pages include zero-filled
pages and they are handled differently. During store operation, a page is
checked if it is a same-value filled page before compressing it. If true, the
compressed length of the page is set to zero and the pattern or same-filled
value is stored.
To prevent zswap from shrinking pool when zswap is full and there's a high
pressure on swap (this will result in flipping pages in and out zswap pool
without any real benefit but with a performance drop for the system), a
special parameter has been introduced to implement a sort of hysteresis to
refuse taking pages into zswap pool until it has sufficient space if the limit
has been hit. To set the threshold at which zswap would start accepting pages
again after it became full, use the sysfs ``accept_threshold_percent``
attribute, e. g.::
echo 80 > /sys/module/zswap/parameters/accept_threshold_percent
Setting this parameter to 100 will disable the hysteresis.
Some users cannot tolerate the swapping that comes with zswap store failures
and zswap writebacks. Swapping can be disabled entirely (without disabling
zswap itself) on a cgroup-basis as follows::
echo 0 > /sys/fs/cgroup/<cgroup-name>/memory.zswap.writeback
Note that if the store failures are recurring (for e.g if the pages are
incompressible), users can observe reclaim inefficiency after disabling
writeback (because the same pages might be rejected again and again).
When there is a sizable amount of cold memory residing in the zswap pool, it
can be advantageous to proactively write these cold pages to swap and reclaim
the memory for other use cases. By default, the zswap shrinker is disabled.
User can enable it as follows::
echo Y > /sys/module/zswap/parameters/shrinker_enabled
This can be enabled at the boot time if ``CONFIG_ZSWAP_SHRINKER_DEFAULT_ON`` is
selected.
A debugfs interface is provided for various statistic about pool size, number
of pages stored, same-value filled pages and various counters for the reasons
pages are rejected.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
개요
1-14Zswap은 swap page를 위한 경량 compressed cache입니다. Swapout 중인 page를 받아 동적으로 할당한 RAM 기반 memory pool에 압축해 넣으려 시도합니다.
기본적으로 zswap은 CPU cycle을 잠재적인 swap I/O 감소와 교환합니다. Compressed cache에서 읽는 편이 swap device에서 읽는 것보다 빠르면 이 교환은 상당한 성능 향상으로 이어질 수 있습니다.
효과와 eviction
15-28| 대상 | 직접 효과 | 운영 이점 |
|---|---|---|
| RAM이 제한된 desktop/laptop | swap I/O latency 완화 | swapping의 체감 성능 저하 감소 |
| 공통 I/O를 공유하는 overcommitted guest | swap I/O pressure 감소 | hypervisor의 거친 I/O throttling과 이웃 guest 영향 완화 |
| SSD swap device | 수명 단축 write 감소 | device endurance 연장 |
Compressed pool이 size limit에 도달하면 zswap은 LRU 기준으로 page를 cache에서 축출해 backing swap device에 기록합니다. 이러한 bounded cache 요구 사항은 이전 community 논의에서 확인된 바 있습니다.
Boot·runtime 활성화
29-48Boot 시 zswap 활성화 여부는 `CONFIG_ZSWAP_DEFAULT_ON` Kconfig option에 달려 있습니다. Kernel command line의 `zswap.enabled=`로 이를 override할 수 있으며, 예를 들어 `zswap.enabled=0`은 비활성화합니다.
Sysfs가 `/sys`에 mount됐다고 가정하면 runtime 활성화는 다음과 같습니다.
echo 1 > /sys/module/zswap/parameters/enabled
Runtime에 zswap을 비활성화하면 이후 swapout page의 저장은 중단되지만 compressed pool의 기존 page를 즉시 backing swap으로 쓰거나 memory로 fault-in하지는 않습니다. 기존 page는 invalidate되거나 다시 memory로 fault-in될 때까지 pool에 남습니다.
Compressed pool의 모든 page를 강제로 내보내려면 swap device에 `swapoff`를 실행합니다. 그러면 compressed pool의 page를 포함한 모든 swapped-out page가 memory로 fault-in됩니다.
Pool과 mapping 설계
49-75Zswap은 swap subsystem에서 compression 대상 page를 받고, compressed pool이 가득 차면 자체 pool의 page를 LRU 순서로 축출해 backing swap device에 writeback합니다.
| 구성 | 구현 | 의미 |
|---|---|---|
| allocator | zsmalloc | 직접 주소 대신 handle을 반환하며 access 전에 mapping 필요 |
| pool 크기 | on-demand | page 저장 시 증가하고 해제 시 감소하며 preallocate하지 않음 |
| mapping key | swap type + swap offset | swap type별 red-black tree에서 offset을 search key로 사용 |
| mapping value | zsmalloc handle | compressed swap page를 참조 |
Zswap은 compressed memory pool 관리에 zsmalloc을 사용합니다. 각 allocation은 address로 직접 접근할 수 없고 allocation routine이 반환한 handle을 먼저 mapping해야 합니다. Pool은 필요에 따라 증가하고 compressed page가 해제되면 줄어들며 preallocate하지 않습니다.
Swapout이 page를 zswap에 넘기면 zswap은 swap type과 swap offset의 조합인 swap entry를 compressed page의 zsmalloc handle에 연결합니다. Swap type마다 red-black tree 하나를 두고 swap offset을 node search key로 사용합니다.
Swap-entry PTE에서 page fault가 나면 swapin code가 zswap load function을 호출해 fault handler가 할당한 page로 압축을 풉니다. Zswap에 저장된 swap page를 참조하는 PTE가 없어져 `swap_map` count가 0이 되면 swap code가 zswap invalidate function을 호출해 compressed entry를 해제합니다.
RAM의 compressed pool은 backing swap 앞에 놓인 bounded cache로 동작합니다.
Pool 한도와 compressor
76-95Zswap은 단순한 policy를 지향하며, 사용자가 제어하는 핵심 pool policy는 `max_pool_percent`입니다. 이 값은 compressed pool이 차지할 수 있는 최대 memory 비율을 정합니다.
| knob | boot/default | 역할 |
|---|---|---|
| `enabled` | `CONFIG_ZSWAP_DEFAULT_ON`, `zswap.enabled=` | runtime store 활성화·비활성화 |
| `max_pool_percent` | sysfs | compressed pool이 차지할 수 있는 최대 memory 비율 |
| `compressor` | `CONFIG_ZSWAP_COMPRESSOR_DEFAULT`, `zswap.compressor=` | 새 pool의 compressor 선택 |
| `accept_threshold_percent` | sysfs | full 뒤 page 수용을 재개할 pool 사용률 threshold |
| `memory.zswap.writeback` | cgroup | zswap store failure와 eviction의 swap writeback 허용 여부 |
| `shrinker_enabled` | `CONFIG_ZSWAP_SHRINKER_DEFAULT_ON` | cold zswap page의 proactive writeback·reclaim |
기본 compressor는 `CONFIG_ZSWAP_COMPRESSOR_DEFAULT` Kconfig option으로 선택하며 boot parameter `zswap.compressor=lzo`처럼 `compressor`를 override할 수 있습니다. Runtime 변경 예시는 다음과 같습니다.
echo lzo > /sys/module/zswap/parameters/compressor
Runtime에 compressor를 바꿔도 기존 compressed page는 수정하지 않고 원래 pool에 남습니다. Old pool의 page를 요청하면 원래 compressor로 압축을 풉니다. Old pool의 page가 모두 제거되면 그 pool과 compressor도 해제됩니다.
Same-filled page와 hysteresis
96-115Zswap page 중에는 page 전체가 같은 값이나 반복 pattern으로 채워진 same-value filled page가 있으며 zero-filled page도 여기에 포함됩니다. Store 과정에서는 compression 전에 이를 검사해 다르게 처리합니다.
| 단계 | 동작 |
|---|---|
| 탐지 | compression 전에 same-value 또는 repetitive pattern인지 검사 |
| zero-filled page | same-filled page의 한 종류로 별도 처리 |
| 저장 | compressed length를 0으로 두고 pattern 또는 same-filled value만 저장 |
Pool이 가득 차고 swap pressure가 높을 때 zswap이 pool을 줄이면서 같은 page를 안팎으로 반복 이동시키면 실질적 이득 없이 성능이 떨어집니다. 이를 막기 위해 충분한 공간이 생길 때까지 새 page 수용을 거부하는 hysteresis parameter가 있습니다.
| 관점 | 정책 |
|---|---|
| 목적 | full 상태의 높은 swap pressure에서 page가 pool 안팎으로 반복 이동하는 thrashing 방지 |
| 재수용 | `accept_threshold_percent` 아래로 충분한 공간이 생길 때까지 새 page 거부 |
| 비활성화 | 값을 100으로 설정 |
Full 뒤 재수용 threshold 설정 예시는 다음과 같습니다.
echo 80 > /sys/module/zswap/parameters/accept_threshold_percent
`accept_threshold_percent=100`은 hysteresis를 비활성화합니다.
Cgroup writeback 제어
116-125일부 사용자는 zswap store failure와 zswap writeback에 따르는 swapping을 허용할 수 없습니다. Zswap 자체는 켠 채 cgroup 단위로 swapping을 완전히 막을 수 있습니다.
echo 0 > /sys/fs/cgroup/<cgroup-name>/memory.zswap.writeback
| 상태 | 결과 |
|---|---|
| writeback 허용 | store failure 또는 LRU eviction 시 backing swap으로 page 기록 |
| writeback 비활성화 | swapping은 막지만 incompressible page가 반복 거부되면 reclaim 효율 저하 |
Page가 incompressible한 경우처럼 store failure가 반복되면 writeback 비활성화 후 같은 page가 계속 거부되어 reclaim 효율이 낮아질 수 있습니다.
Cold page shrinker와 debugfs
126-138Zswap pool에 cold memory가 상당량 있으면 이를 미리 swap으로 기록하고 memory를 다른 용도로 회수하는 편이 유리할 수 있습니다. Zswap shrinker는 기본적으로 비활성화되어 있으며 다음과 같이 켭니다.
echo Y > /sys/module/zswap/parameters/shrinker_enabled
`CONFIG_ZSWAP_SHRINKER_DEFAULT_ON`을 선택하면 boot 시부터 shrinker를 활성화할 수 있습니다.
| debugfs 통계 | 의미 |
|---|---|
| pool size | 현재 compressed pool memory 사용량 |
| stored pages | pool에 저장된 page 수 |
| same-value filled pages | pattern만 저장한 page 수 |
| reject counters | page가 거부된 원인별 counter |
Debugfs interface는 pool size, 저장 page 수, same-value filled page 수와 page가 거부된 여러 원인별 counter를 제공합니다.
운영 핵심
zswap.rst:1-138Zswap은 swap을 대체하지 않고 backing swap 앞에서 동작하는 압축 cache입니다. CPU 비용, RAM pool 사용량, swap I/O 감소의 균형을 workload에 맞추고, full 상태의 eviction과 writeback 비활성화 시 reclaim 실패를 함께 관찰해야 합니다.