1 ========================================
2 zram: Compressed RAM-based block devices
3 ========================================
8 The zram module creates RAM-based block devices named /dev/zram<id>
9 (<id> = 0, 1, ...). Pages written to these disks are compressed and stored
10 in memory itself. These disks allow very fast I/O and compression provides
11 good amounts of memory savings. Some of the use cases include /tmp storage,
12 use as swap disks, various caches under /var and maybe many more. :)
14 Statistics for individual zram devices are exported through sysfs nodes at
20 There are several ways to configure and manage zram device(-s):
22 a) using zram and zram_control sysfs attributes
23 b) using zramctl utility, provided by util-linux (util-linux@vger.kernel.org).
25 In this document we will describe only 'manual' zram configuration steps,
26 IOW, zram and zram_control sysfs attributes.
28 In order to get a better idea about zramctl please consult util-linux
29 documentation, zramctl man-page or `zramctl --help`. Please be informed
30 that zram maintainers do not develop/maintain util-linux or zramctl, should
31 you have any questions please contact util-linux@vger.kernel.org
33 Following shows a typical sequence of steps for using zram.
38 For the sake of simplicity we skip error checking parts in most of the
39 examples below. However, it is your sole responsibility to handle errors.
41 zram sysfs attributes always return negative values in case of errors.
42 The list of possible return codes:
44 ======== =============================================================
45 -EBUSY an attempt to modify an attribute that cannot be changed once
46 the device has been initialised. Please reset device first.
47 -ENOMEM zram was not able to allocate enough memory to fulfil your
49 -EINVAL invalid input has been provided.
50 -EAGAIN re-try operation later (e.g. when attempting to run recompress
51 and writeback simultaneously).
52 ======== =============================================================
54 If you use 'echo', the returned value is set by the 'echo' utility,
55 and, in general case, something like::
57 echo foo > /sys/block/zram0/comp_algorithm
69 modprobe zram num_devices=4
71 This creates 4 devices: /dev/zram{0,1,2,3}
73 num_devices parameter is optional and tells zram how many devices should be
74 pre-created. Default: 1.
76 2) Select compression algorithm
77 ===============================
79 Using comp_algorithm device attribute one can see available and
80 currently selected (shown in square brackets) compression algorithms,
81 or change the selected compression algorithm (once the device is initialised
82 there is no way to change compression algorithm).
86 #show supported compression algorithms
87 cat /sys/block/zram0/comp_algorithm
90 #select lzo compression algorithm
91 echo lzo > /sys/block/zram0/comp_algorithm
93 For the time being, the `comp_algorithm` content shows only compression
94 algorithms that are supported by zram.
96 3) Set compression algorithm parameters: Optional
97 =================================================
99 Compression algorithms may support specific parameters which can be
100 tweaked for particular dataset. ZRAM has an `algorithm_params` device
101 attribute which provides a per-algorithm params configuration.
103 For example, several compression algorithms support `level` parameter.
104 In addition, certain compression algorithms support pre-trained dictionaries,
105 which significantly change algorithms' characteristics. In order to configure
106 compression algorithm to use external pre-trained dictionary, pass full
107 path to the `dict` along with other parameters::
109 #pass path to pre-trained zstd dictionary
110 echo "algo=zstd dict=/etc/dictionary" > /sys/block/zram0/algorithm_params
112 #same, but using algorithm priority
113 echo "priority=1 dict=/etc/dictionary" > \
114 /sys/block/zram0/algorithm_params
116 #pass path to pre-trained zstd dictionary and compression level
117 echo "algo=zstd level=8 dict=/etc/dictionary" > \
118 /sys/block/zram0/algorithm_params
120 Parameters are algorithm specific: not all algorithms support pre-trained
121 dictionaries, not all algorithms support `level`. Furthermore, for certain
122 algorithms `level` controls the compression level (the higher the value the
123 better the compression ratio, it even can take negatives values for some
124 algorithms), for other algorithms `level` is acceleration level (the higher
125 the value the lower the compression ratio).
130 Set disk size by writing the value to sysfs node 'disksize'.
131 The value can be either in bytes or you can use mem suffixes.
134 # Initialize /dev/zram0 with 50MB disksize
135 echo $((50*1024*1024)) > /sys/block/zram0/disksize
138 echo 256K > /sys/block/zram0/disksize
139 echo 512M > /sys/block/zram0/disksize
140 echo 1G > /sys/block/zram0/disksize
143 There is little point creating a zram of greater than twice the size of memory
144 since we expect a 2:1 compression ratio. Note that zram uses about 0.1% of the
145 size of the disk when not in use so a huge zram is wasteful.
147 5) Set memory limit: Optional
148 =============================
150 Set memory limit by writing the value to sysfs node 'mem_limit'.
151 The value can be either in bytes or you can use mem suffixes.
152 In addition, you could change the value in runtime.
155 # limit /dev/zram0 with 50MB memory
156 echo $((50*1024*1024)) > /sys/block/zram0/mem_limit
159 echo 256K > /sys/block/zram0/mem_limit
160 echo 512M > /sys/block/zram0/mem_limit
161 echo 1G > /sys/block/zram0/mem_limit
163 # To disable memory limit
164 echo 0 > /sys/block/zram0/mem_limit
175 mount /dev/zram1 /tmp
177 7) Add/remove zram devices
178 ==========================
180 zram provides a control interface, which enables dynamic (on-demand) device
181 addition and removal.
183 In order to add a new /dev/zramX device, perform a read operation on the hot_add
184 attribute. This will return either the new device's device id (meaning that you
185 can use /dev/zram<id>) or an error code.
189 cat /sys/class/zram-control/hot_add
192 To remove the existing /dev/zramX device (where X is a device id)
195 echo X > /sys/class/zram-control/hot_remove
200 Per-device statistics are exported as various nodes under /sys/block/zram<id>/
202 A brief description of exported device attributes follows. For more details
203 please read Documentation/ABI/testing/sysfs-block-zram.
205 ====================== ====== ===============================================
206 Name access description
207 ====================== ====== ===============================================
208 disksize RW show and set the device's disk size
209 initstate RO shows the initialization state of the device
210 reset WO trigger device reset
211 mem_used_max WO reset the `mem_used_max` counter (see later)
212 mem_limit WO specifies the maximum amount of memory ZRAM can
213 use to store the compressed data
214 writeback_limit WO specifies the maximum amount of write IO zram
215 can write out to backing device as 4KB unit
216 writeback_limit_enable RW show and set writeback_limit feature
217 comp_algorithm RW show and change the compression algorithm
218 algorithm_params WO setup compression algorithm parameters
219 compact WO trigger memory compaction
220 debug_stat RO this file is used for zram debugging purposes
221 backing_dev RW set up backend storage for zram to write out
222 idle WO mark allocated slot as idle
223 ====================== ====== ===============================================
226 User space is advised to use the following files to read the device statistics.
228 File /sys/block/zram<id>/stat
230 Represents block layer statistics. Read Documentation/block/stat.rst for
233 File /sys/block/zram<id>/io_stat
235 The stat file represents device's I/O statistics not accounted by block
236 layer and, thus, not available in zram<id>/stat file. It consists of a
237 single line of text and contains the following stats separated by
240 ============= =============================================================
241 failed_reads The number of failed reads
242 failed_writes The number of failed writes
243 invalid_io The number of non-page-size-aligned I/O requests
244 notify_free Depending on device usage scenario it may account
246 a) the number of pages freed because of swap slot free
248 b) the number of pages freed because of
249 REQ_OP_DISCARD requests sent by bio. The former ones are
250 sent to a swap block device when a swap slot is freed,
251 which implies that this disk is being used as a swap disk.
253 The latter ones are sent by filesystem mounted with
254 discard option, whenever some data blocks are getting
256 ============= =============================================================
258 File /sys/block/zram<id>/mm_stat
260 The mm_stat file represents the device's mm statistics. It consists of a single
261 line of text and contains the following stats separated by whitespace:
263 ================ =============================================================
264 orig_data_size uncompressed size of data stored in this disk.
266 compr_data_size compressed size of data stored in this disk
267 mem_used_total the amount of memory allocated for this disk. This
268 includes allocator fragmentation and metadata overhead,
269 allocated for this disk. So, allocator space efficiency
270 can be calculated using compr_data_size and this statistic.
272 mem_limit the maximum amount of memory ZRAM can use to store
274 mem_used_max the maximum amount of memory zram has consumed to
276 same_pages the number of same element filled pages written to this disk.
277 No memory is allocated for such pages.
278 pages_compacted the number of pages freed during compaction
279 huge_pages the number of incompressible pages
280 huge_pages_since the number of incompressible pages since zram set up
281 ================ =============================================================
283 File /sys/block/zram<id>/bd_stat
285 The bd_stat file represents a device's backing device statistics. It consists of
286 a single line of text and contains the following stats separated by whitespace:
288 ============== =============================================================
289 bd_count size of data written in backing device.
291 bd_reads the number of reads from backing device
293 bd_writes the number of writes to backing device
295 ============== =============================================================
308 Write any positive value to 'reset' sysfs node::
310 echo 1 > /sys/block/zram0/reset
311 echo 1 > /sys/block/zram1/reset
313 This frees all the memory allocated for the given device and
314 resets the disksize to zero. You must set the disksize again
315 before reusing the device.
323 zram has built-in support for idle pages tracking (that is, allocated but
324 not used pages). This feature is useful for e.g. zram writeback and
325 recompression. In order to mark pages as idle, execute the following command::
327 echo all > /sys/block/zramX/idle
329 This will mark all allocated zram pages as idle. The idle mark will be
330 removed only when the page (block) is accessed (e.g. overwritten or freed).
331 Additionally, when CONFIG_ZRAM_TRACK_ENTRY_ACTIME is enabled, pages can be
332 marked as idle based on how many seconds have passed since the last access to
333 a particular zram page::
335 echo 86400 > /sys/block/zramX/idle
337 In this example, all pages which haven't been accessed in more than 86400
338 seconds (one day) will be marked idle.
343 With CONFIG_ZRAM_WRITEBACK, zram can write idle/incompressible page
344 to backing storage rather than keeping it in memory.
345 To use the feature, admin should set up backing device via::
347 echo /dev/sda5 > /sys/block/zramX/backing_dev
349 before disksize setting. It supports only partitions at this moment.
350 If admin wants to use incompressible page writeback, they could do it via::
352 echo huge > /sys/block/zramX/writeback
354 Admin can request writeback of idle pages at right timing via::
356 echo idle > /sys/block/zramX/writeback
358 With the command, zram will writeback idle pages from memory to the storage.
360 Additionally, if a user choose to writeback only huge and idle pages
361 this can be accomplished with::
363 echo huge_idle > /sys/block/zramX/writeback
365 If a user chooses to writeback only incompressible pages (pages that none of
366 algorithms can compress) this can be accomplished with::
368 echo incompressible > /sys/block/zramX/writeback
370 If an admin wants to write a specific page in zram device to the backing device,
371 they could write a page index into the interface::
373 echo "page_index=1251" > /sys/block/zramX/writeback
375 In Linux 6.16 this interface underwent some rework. First, the interface
376 now supports `key=value` format for all of its parameters (`type=huge_idle`,
377 etc.) Second, the support for `page_indexes` was introduced, which specify
378 `LOW-HIGH` range (or ranges) of pages to be written-back. This reduces the
379 number of syscalls, but more importantly this enables optimal post-processing
380 target selection strategy. Usage example::
382 echo "type=idle" > /sys/block/zramX/writeback
383 echo "page_indexes=1-100 page_indexes=200-300" > \
384 /sys/block/zramX/writeback
386 We also now permit multiple page_index params per call and a mix of
387 single pages and page ranges::
389 echo page_index=42 page_index=99 page_indexes=100-200 \
390 page_indexes=500-700 > /sys/block/zramX/writeback
392 If there are lots of write IO with flash device, potentially, it has
393 flash wearout problem so that admin needs to design write limitation
394 to guarantee storage health for entire product life.
396 To overcome the concern, zram supports "writeback_limit" feature.
397 The "writeback_limit_enable"'s default value is 0 so that it doesn't limit
398 any writeback. IOW, if admin wants to apply writeback budget, they should
399 enable writeback_limit_enable via::
401 $ echo 1 > /sys/block/zramX/writeback_limit_enable
403 Once writeback_limit_enable is set, zram doesn't allow any writeback
404 until admin sets the budget via /sys/block/zramX/writeback_limit.
406 (If admin doesn't enable writeback_limit_enable, writeback_limit's value
407 assigned via /sys/block/zramX/writeback_limit is meaningless.)
409 If admin wants to limit writeback as per-day 400M, they could do it
414 $ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
415 /sys/block/zram0/writeback_limit.
416 $ echo 1 > /sys/block/zram0/writeback_limit_enable
418 If admins want to allow further write again once the budget is exhausted,
419 they could do it like below::
421 $ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
422 /sys/block/zram0/writeback_limit
424 If an admin wants to see the remaining writeback budget since last set::
426 $ cat /sys/block/zramX/writeback_limit
428 If an admin wants to disable writeback limit, they could do::
430 $ echo 0 > /sys/block/zramX/writeback_limit_enable
432 The writeback_limit count will reset whenever you reset zram (e.g.,
433 system reboot, echo 1 > /sys/block/zramX/reset) so keeping how many of
434 writeback happened until you reset the zram to allocate extra writeback
435 budget in next setting is user's job.
437 If admin wants to measure writeback count in a certain period, they could
438 know it via /sys/block/zram0/bd_stat's 3rd column.
443 With CONFIG_ZRAM_MULTI_COMP, zram can recompress pages using alternative
444 (secondary) compression algorithms. The basic idea is that alternative
445 compression algorithm can provide better compression ratio at a price of
446 (potentially) slower compression/decompression speeds. Alternative compression
447 algorithm can, for example, be more successful compressing huge pages (those
448 that default algorithm failed to compress). Another application is idle pages
449 recompression - pages that are cold and sit in the memory can be recompressed
450 using more effective algorithm and, hence, reduce zsmalloc memory usage.
452 With CONFIG_ZRAM_MULTI_COMP, zram supports up to 4 compression algorithms:
453 one primary and up to 3 secondary ones. Primary zram compressor is explained
454 in "3) Select compression algorithm", secondary algorithms are configured
455 using recomp_algorithm device attribute.
459 #show supported recompression algorithms
460 cat /sys/block/zramX/recomp_algorithm
461 #1: lzo lzo-rle lz4 lz4hc [zstd]
462 #2: lzo lzo-rle lz4 [lz4hc] zstd
464 Alternative compression algorithms are sorted by priority. In the example
465 above, zstd is used as the first alternative algorithm, which has priority
466 of 1, while lz4hc is configured as a compression algorithm with priority 2.
467 Alternative compression algorithm's priority is provided during algorithms
470 #select zstd recompression algorithm, priority 1
471 echo "algo=zstd priority=1" > /sys/block/zramX/recomp_algorithm
473 #select deflate recompression algorithm, priority 2
474 echo "algo=deflate priority=2" > /sys/block/zramX/recomp_algorithm
476 Another device attribute that CONFIG_ZRAM_MULTI_COMP enables is recompress,
477 which controls recompression.
481 #IDLE pages recompression is activated by `idle` mode
482 echo "type=idle" > /sys/block/zramX/recompress
484 #HUGE pages recompression is activated by `huge` mode
485 echo "type=huge" > /sys/block/zram0/recompress
487 #HUGE_IDLE pages recompression is activated by `huge_idle` mode
488 echo "type=huge_idle" > /sys/block/zramX/recompress
490 The number of idle pages can be significant, so user-space can pass a size
491 threshold (in bytes) to the recompress knob: zram will recompress only pages
492 of equal or greater size:::
494 #recompress all pages larger than 3000 bytes
495 echo "threshold=3000" > /sys/block/zramX/recompress
497 #recompress idle pages larger than 2000 bytes
498 echo "type=idle threshold=2000" > /sys/block/zramX/recompress
500 It is also possible to limit the number of pages zram re-compression will
501 attempt to recompress:::
503 echo "type=huge_idle max_pages=42" > /sys/block/zramX/recompress
505 During re-compression for every page, that matches re-compression criteria,
506 ZRAM iterates the list of registered alternative compression algorithms in
507 order of their priorities. ZRAM stops either when re-compression was
508 successful (re-compressed object is smaller in size than the original one)
509 and matches re-compression criteria (e.g. size threshold) or when there are
510 no secondary algorithms left to try. If none of the secondary algorithms can
511 successfully re-compressed the page such a page is marked as incompressible,
512 so ZRAM will not attempt to re-compress it in the future.
514 This re-compression behaviour, when it iterates through the list of
515 registered compression algorithms, increases our chances of finding the
516 algorithm that successfully compresses a particular page. Sometimes, however,
517 it is convenient (and sometimes even necessary) to limit recompression to
518 only one particular algorithm so that it will not try any other algorithms.
519 This can be achieved by providing a `algo` or `priority` parameter:::
521 #use zstd algorithm only (if registered)
522 echo "type=huge algo=zstd" > /sys/block/zramX/recompress
524 #use zstd algorithm only (if zstd was registered under priority 1)
525 echo "type=huge priority=1" > /sys/block/zramX/recompress
530 With CONFIG_ZRAM_MEMORY_TRACKING, user can know information of the
531 zram block. It could be useful to catch cold or incompressible
532 pages of the process with*pagemap.
534 If you enable the feature, you could see block state via
535 /sys/kernel/debug/zram/zram0/block_state". The output is as follows::
541 304 146.781902 ..hi.n
546 access time since the system was booted
553 written page to backing store
559 recompressed page (secondary compression algorithm)
561 none (including secondary) of algorithms could compress it
563 First line of above example says 300th block is accessed at 75.033841sec
564 and the block's state is huge so it is written back to the backing
565 storage. It's a debugging feature so anyone shouldn't rely on it to work