← Documents Documentation/admin-guide/mm/zswap.rst GitHub 원문 ↗

Linux 6.18.37 · Administration / Memory Management

zswap

RAM 기반 compressed swap cache의 수명 주기, pool·compressor 정책, hysteresis·writeback·shrinker와 debugfs 통계를 설명합니다.

Source pathDocumentation/admin-guide/mm/zswap.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

운영 핵심

zswap.rst:1-138

Zswap은 swap을 대체하지 않고 backing swap 앞에서 동작하는 압축 cache입니다. CPU 비용, RAM pool 사용량, swap I/O 감소의 균형을 workload에 맞추고, full 상태의 eviction과 writeback 비활성화 시 reclaim 실패를 함께 관찰해야 합니다.

관점핵심
역할swapout page를 RAM에서 압축해 backing swap I/O를 줄이는 cache
비용 교환CPU compression cycle을 swap read/write 감소와 교환
용량 한도`max_pool_percent` 도달 시 LRU page를 backing swap으로 eviction
정책compressor, hysteresis, cgroup writeback, shrinker를 독립 제어
관찰debugfs에서 pool size, page 수, same-filled 및 reject counter 확인

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 =====
2 zswap
3 =====
4
5 Overview
6 ========
7
8 Zswap is a lightweight compressed cache for swap pages. It takes pages that are
9 in the process of being swapped out and attempts to compress them into a
10 dynamically allocated RAM-based memory pool. zswap basically trades CPU cycles
11 for potentially reduced swap I/O. This trade-off can also result in a
12 significant performance improvement if reads from the compressed cache are
13 faster than reads from a swap device.
14
15 Some potential benefits:
16
17 * Desktop/laptop users with limited RAM capacities can mitigate the
18 performance impact of swapping.
19 * Overcommitted guests that share a common I/O resource can
20 dramatically reduce their swap I/O pressure, avoiding heavy handed I/O
21 throttling by the hypervisor. This allows more work to get done with less
22 impact to the guest workload and guests sharing the I/O subsystem
23 * Users with SSDs as swap devices can extend the life of the device by
24 drastically reducing life-shortening writes.
25
26 Zswap evicts pages from compressed cache on an LRU basis to the backing swap
27 device when the compressed pool reaches its size limit. This requirement had
28 been identified in prior community discussions.
29
30 Whether Zswap is enabled at the boot time depends on whether
31 the ``CONFIG_ZSWAP_DEFAULT_ON`` Kconfig option is enabled or not.
32 This setting can then be overridden by providing the kernel command line
33 ``zswap.enabled=`` option, for example ``zswap.enabled=0``.
34 Zswap can also be enabled and disabled at runtime using the sysfs interface.
35 An example command to enable zswap at runtime, assuming sysfs is mounted
36 at ``/sys``, is::
37
38 echo 1 > /sys/module/zswap/parameters/enabled
39
40 When zswap is disabled at runtime it will stop storing pages that are
41 being swapped out. However, it will _not_ immediately write out or fault
42 back into memory all of the pages stored in the compressed pool. The
43 pages stored in zswap will remain in the compressed pool until they are
44 either invalidated or faulted back into memory. In order to force all
45 pages out of the compressed pool, a swapoff on the swap device(s) will
46 fault back into memory all swapped out pages, including those in the
47 compressed pool.
48
49 Design
50 ======
51
52 Zswap receives pages for compression from the swap subsystem and is able to
53 evict pages from its own compressed pool on an LRU basis and write them back to
54 the backing swap device in the case that the compressed pool is full.
55
56 Zswap makes use of zsmalloc for the managing the compressed memory pool. Each
57 allocation in zsmalloc is not directly accessible by address. Rather, a handle is
58 returned by the allocation routine and that handle must be mapped before being
59 accessed. The compressed memory pool grows on demand and shrinks as compressed
60 pages are freed. The pool is not preallocated.
61
62 When a swap page is passed from swapout to zswap, zswap maintains a mapping
63 of the swap entry, a combination of the swap type and swap offset, to the
64 zsmalloc handle that references that compressed swap page. This mapping is
65 achieved with a red-black tree per swap type. The swap offset is the search
66 key for the tree nodes.
67
68 During a page fault on a PTE that is a swap entry, the swapin code calls the
69 zswap load function to decompress the page into the page allocated by the page
70 fault handler.
71
72 Once there are no PTEs referencing a swap page stored in zswap (i.e. the count
73 in the swap_map goes to 0) the swap code calls the zswap invalidate function
74 to free the compressed entry.
75
76 Zswap seeks to be simple in its policies. Sysfs attributes allow for one user
77 controlled policy:
78
79 * max_pool_percent - The maximum percentage of memory that the compressed
80 pool can occupy.
81
82 The default compressor is selected in ``CONFIG_ZSWAP_COMPRESSOR_DEFAULT``
83 Kconfig option, but it can be overridden at boot time by setting the
84 ``compressor`` attribute, e.g. ``zswap.compressor=lzo``.
85 It can also be changed at runtime using the sysfs "compressor"
86 attribute, e.g.::
87
88 echo lzo > /sys/module/zswap/parameters/compressor
89
90 When the compressor parameter is changed at runtime, any existing compressed
91 pages are not modified; they are left in their own pool. When a request is
92 made for a page in an old pool, it is uncompressed using its original
93 compressor. Once all pages are removed from an old pool, the pool and its
94 compressor are freed.
95
96 Some of the pages in zswap are same-value filled pages (i.e. contents of the
97 page have same value or repetitive pattern). These pages include zero-filled
98 pages and they are handled differently. During store operation, a page is
99 checked if it is a same-value filled page before compressing it. If true, the
100 compressed length of the page is set to zero and the pattern or same-filled
101 value is stored.
102
103 To prevent zswap from shrinking pool when zswap is full and there's a high
104 pressure on swap (this will result in flipping pages in and out zswap pool
105 without any real benefit but with a performance drop for the system), a
106 special parameter has been introduced to implement a sort of hysteresis to
107 refuse taking pages into zswap pool until it has sufficient space if the limit
108 has been hit. To set the threshold at which zswap would start accepting pages
109 again after it became full, use the sysfs ``accept_threshold_percent``
110 attribute, e. g.::
111
112 echo 80 > /sys/module/zswap/parameters/accept_threshold_percent
113
114 Setting this parameter to 100 will disable the hysteresis.
115
116 Some users cannot tolerate the swapping that comes with zswap store failures
117 and zswap writebacks. Swapping can be disabled entirely (without disabling
118 zswap itself) on a cgroup-basis as follows::
119
120 echo 0 > /sys/fs/cgroup/<cgroup-name>/memory.zswap.writeback
121
122 Note that if the store failures are recurring (for e.g if the pages are
123 incompressible), users can observe reclaim inefficiency after disabling
124 writeback (because the same pages might be rejected again and again).
125
126 When there is a sizable amount of cold memory residing in the zswap pool, it
127 can be advantageous to proactively write these cold pages to swap and reclaim
128 the memory for other use cases. By default, the zswap shrinker is disabled.
129 User can enable it as follows::
130
131 echo Y > /sys/module/zswap/parameters/shrinker_enabled
132
133 This can be enabled at the boot time if ``CONFIG_ZSWAP_SHRINKER_DEFAULT_ON`` is
134 selected.
135
136 A debugfs interface is provided for various statistic about pool size, number
137 of pages stored, same-value filled pages and various counters for the reasons
138 pages are rejected.
139

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

개요

1-14

Zswap은 swap page를 위한 경량 compressed cache입니다. Swapout 중인 page를 받아 동적으로 할당한 RAM 기반 memory pool에 압축해 넣으려 시도합니다.

기본적으로 zswap은 CPU cycle을 잠재적인 swap I/O 감소와 교환합니다. Compressed cache에서 읽는 편이 swap device에서 읽는 것보다 빠르면 이 교환은 상당한 성능 향상으로 이어질 수 있습니다.

효과와 eviction

15-28
대상직접 효과운영 이점
RAM이 제한된 desktop/laptopswap I/O latency 완화swapping의 체감 성능 저하 감소
공통 I/O를 공유하는 overcommitted guestswap 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-48

Boot 시 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-75

Zswap은 swap subsystem에서 compression 대상 page를 받고, compressed pool이 가득 차면 자체 pool의 page를 LRU 순서로 축출해 backing swap device에 writeback합니다.

구성구현의미
allocatorzsmalloc직접 주소 대신 handle을 반환하며 access 전에 mapping 필요
pool 크기on-demandpage 저장 시 증가하고 해제 시 감소하며 preallocate하지 않음
mapping keyswap type + swap offsetswap type별 red-black tree에서 offset을 search key로 사용
mapping valuezsmalloc handlecompressed 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를 해제합니다.

Zswap page 수명 주기
단계입력·조건동작
01 1swapout page압축 후 zsmalloc pool에 store
02 2swap-entry page faultload 후 fault page에 decompress
03 3pool size limitLRU victim을 backing swap에 writeback
04 4`swap_map == 0`compressed entry invalidate

RAM의 compressed pool은 backing swap 앞에 놓인 bounded cache로 동작합니다.

Pool 한도와 compressor

76-95

Zswap은 단순한 policy를 지향하며, 사용자가 제어하는 핵심 pool policy는 `max_pool_percent`입니다. 이 값은 compressed pool이 차지할 수 있는 최대 memory 비율을 정합니다.

knobboot/default역할
`enabled``CONFIG_ZSWAP_DEFAULT_ON`, `zswap.enabled=`runtime store 활성화·비활성화
`max_pool_percent`sysfscompressed pool이 차지할 수 있는 최대 memory 비율
`compressor``CONFIG_ZSWAP_COMPRESSOR_DEFAULT`, `zswap.compressor=`새 pool의 compressor 선택
`accept_threshold_percent`sysfsfull 뒤 page 수용을 재개할 pool 사용률 threshold
`memory.zswap.writeback`cgroupzswap 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-115

Zswap page 중에는 page 전체가 같은 값이나 반복 pattern으로 채워진 same-value filled page가 있으며 zero-filled page도 여기에 포함됩니다. Store 과정에서는 compression 전에 이를 검사해 다르게 처리합니다.

단계동작
탐지compression 전에 same-value 또는 repetitive pattern인지 검사
zero-filled pagesame-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-138

Zswap 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 pagespool에 저장된 page 수
same-value filled pagespattern만 저장한 page 수
reject counterspage가 거부된 원인별 counter

Debugfs interface는 pool size, 저장 page 수, same-value filled page 수와 page가 거부된 여러 원인별 counter를 제공합니다.