zram.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. ========================================
  2. zram: Compressed RAM-based block devices
  3. ========================================
  4. Introduction
  5. ============
  6. The zram module creates RAM-based block devices named /dev/zram<id>
  7. (<id> = 0, 1, ...). Pages written to these disks are compressed and stored
  8. in memory itself. These disks allow very fast I/O and compression provides
  9. good amounts of memory savings. Some of the use cases include /tmp storage,
  10. use as swap disks, various caches under /var and maybe many more. :)
  11. Statistics for individual zram devices are exported through sysfs nodes at
  12. /sys/block/zram<id>/
  13. Usage
  14. =====
  15. There are several ways to configure and manage zram device(-s):
  16. a) using zram and zram_control sysfs attributes
  17. b) using zramctl utility, provided by util-linux (util-linux@vger.kernel.org).
  18. In this document we will describe only 'manual' zram configuration steps,
  19. IOW, zram and zram_control sysfs attributes.
  20. In order to get a better idea about zramctl please consult util-linux
  21. documentation, zramctl man-page or `zramctl --help`. Please be informed
  22. that zram maintainers do not develop/maintain util-linux or zramctl, should
  23. you have any questions please contact util-linux@vger.kernel.org
  24. Following shows a typical sequence of steps for using zram.
  25. WARNING
  26. =======
  27. For the sake of simplicity we skip error checking parts in most of the
  28. examples below. However, it is your sole responsibility to handle errors.
  29. zram sysfs attributes always return negative values in case of errors.
  30. The list of possible return codes:
  31. ======== =============================================================
  32. -EBUSY an attempt to modify an attribute that cannot be changed once
  33. the device has been initialised. Please reset device first.
  34. -ENOMEM zram was not able to allocate enough memory to fulfil your
  35. needs.
  36. -EINVAL invalid input has been provided.
  37. -EAGAIN re-try operation later (e.g. when attempting to run recompress
  38. and writeback simultaneously).
  39. ======== =============================================================
  40. If you use 'echo', the returned value is set by the 'echo' utility,
  41. and, in general case, something like::
  42. echo foo > /sys/block/zram0/comp_algorithm
  43. if [ $? -ne 0 ]; then
  44. handle_error
  45. fi
  46. should suffice.
  47. 1) Load Module
  48. ==============
  49. ::
  50. modprobe zram num_devices=4
  51. This creates 4 devices: /dev/zram{0,1,2,3}
  52. num_devices parameter is optional and tells zram how many devices should be
  53. pre-created. Default: 1.
  54. 2) Select compression algorithm
  55. ===============================
  56. Using comp_algorithm device attribute one can see available and
  57. currently selected (shown in square brackets) compression algorithms,
  58. or change the selected compression algorithm (once the device is initialised
  59. there is no way to change compression algorithm).
  60. Examples::
  61. #show supported compression algorithms
  62. cat /sys/block/zram0/comp_algorithm
  63. lzo [lz4]
  64. #select lzo compression algorithm
  65. echo lzo > /sys/block/zram0/comp_algorithm
  66. For the time being, the `comp_algorithm` content shows only compression
  67. algorithms that are supported by zram.
  68. 3) Set compression algorithm parameters: Optional
  69. =================================================
  70. Compression algorithms may support specific parameters which can be
  71. tweaked for particular dataset. ZRAM has an `algorithm_params` device
  72. attribute which provides a per-algorithm params configuration.
  73. For example, several compression algorithms support `level` parameter.
  74. In addition, certain compression algorithms support pre-trained dictionaries,
  75. which significantly change algorithms' characteristics. In order to configure
  76. compression algorithm to use external pre-trained dictionary, pass full
  77. path to the `dict` along with other parameters::
  78. #pass path to pre-trained zstd dictionary
  79. echo "algo=zstd dict=/etc/dictionary" > /sys/block/zram0/algorithm_params
  80. #same, but using algorithm priority
  81. echo "priority=1 dict=/etc/dictionary" > \
  82. /sys/block/zram0/algorithm_params
  83. #pass path to pre-trained zstd dictionary and compression level
  84. echo "algo=zstd level=8 dict=/etc/dictionary" > \
  85. /sys/block/zram0/algorithm_params
  86. Parameters are algorithm specific: not all algorithms support pre-trained
  87. dictionaries, not all algorithms support `level`. Furthermore, for certain
  88. algorithms `level` controls the compression level (the higher the value the
  89. better the compression ratio, it even can take negatives values for some
  90. algorithms), for other algorithms `level` is acceleration level (the higher
  91. the value the lower the compression ratio).
  92. 4) Set Disksize
  93. ===============
  94. Set disk size by writing the value to sysfs node 'disksize'.
  95. The value can be either in bytes or you can use mem suffixes.
  96. Examples::
  97. # Initialize /dev/zram0 with 50MB disksize
  98. echo $((50*1024*1024)) > /sys/block/zram0/disksize
  99. # Using mem suffixes
  100. echo 256K > /sys/block/zram0/disksize
  101. echo 512M > /sys/block/zram0/disksize
  102. echo 1G > /sys/block/zram0/disksize
  103. Note:
  104. There is little point creating a zram of greater than twice the size of memory
  105. since we expect a 2:1 compression ratio. Note that zram uses about 0.1% of the
  106. size of the disk when not in use so a huge zram is wasteful.
  107. 5) Set memory limit: Optional
  108. =============================
  109. Set memory limit by writing the value to sysfs node 'mem_limit'.
  110. The value can be either in bytes or you can use mem suffixes.
  111. In addition, you could change the value in runtime.
  112. Examples::
  113. # limit /dev/zram0 with 50MB memory
  114. echo $((50*1024*1024)) > /sys/block/zram0/mem_limit
  115. # Using mem suffixes
  116. echo 256K > /sys/block/zram0/mem_limit
  117. echo 512M > /sys/block/zram0/mem_limit
  118. echo 1G > /sys/block/zram0/mem_limit
  119. # To disable memory limit
  120. echo 0 > /sys/block/zram0/mem_limit
  121. 6) Activate
  122. ===========
  123. ::
  124. mkswap /dev/zram0
  125. swapon /dev/zram0
  126. mkfs.ext4 /dev/zram1
  127. mount /dev/zram1 /tmp
  128. 7) Add/remove zram devices
  129. ==========================
  130. zram provides a control interface, which enables dynamic (on-demand) device
  131. addition and removal.
  132. In order to add a new /dev/zramX device, perform a read operation on the hot_add
  133. attribute. This will return either the new device's device id (meaning that you
  134. can use /dev/zram<id>) or an error code.
  135. Example::
  136. cat /sys/class/zram-control/hot_add
  137. 1
  138. To remove the existing /dev/zramX device (where X is a device id)
  139. execute::
  140. echo X > /sys/class/zram-control/hot_remove
  141. 8) Stats
  142. ========
  143. Per-device statistics are exported as various nodes under /sys/block/zram<id>/
  144. A brief description of exported device attributes follows. For more details
  145. please read Documentation/ABI/testing/sysfs-block-zram.
  146. ====================== ====== ===============================================
  147. Name access description
  148. ====================== ====== ===============================================
  149. disksize RW show and set the device's disk size
  150. initstate RO shows the initialization state of the device
  151. reset WO trigger device reset
  152. mem_used_max WO reset the `mem_used_max` counter (see later)
  153. mem_limit WO specifies the maximum amount of memory ZRAM can
  154. use to store the compressed data
  155. writeback_limit WO specifies the maximum amount of write IO zram
  156. can write out to backing device as 4KB unit
  157. writeback_limit_enable RW show and set writeback_limit feature
  158. writeback_batch_size RW show and set maximum number of in-flight
  159. writeback operations
  160. compressed_writeback RW show and set compressed writeback feature
  161. comp_algorithm RW show and change the compression algorithm
  162. algorithm_params WO setup compression algorithm parameters
  163. compact WO trigger memory compaction
  164. debug_stat RO this file is used for zram debugging purposes
  165. backing_dev RW set up backend storage for zram to write out
  166. idle WO mark allocated slot as idle
  167. ====================== ====== ===============================================
  168. User space is advised to use the following files to read the device statistics.
  169. File /sys/block/zram<id>/stat
  170. Represents block layer statistics. Read Documentation/block/stat.rst for
  171. details.
  172. File /sys/block/zram<id>/io_stat
  173. The stat file represents device's I/O statistics not accounted by block
  174. layer and, thus, not available in zram<id>/stat file. It consists of a
  175. single line of text and contains the following stats separated by
  176. whitespace:
  177. ============= =============================================================
  178. failed_reads The number of failed reads
  179. failed_writes The number of failed writes
  180. invalid_io The number of non-page-size-aligned I/O requests
  181. notify_free Depending on device usage scenario it may account
  182. a) the number of pages freed because of swap slot free
  183. notifications
  184. b) the number of pages freed because of
  185. REQ_OP_DISCARD requests sent by bio. The former ones are
  186. sent to a swap block device when a swap slot is freed,
  187. which implies that this disk is being used as a swap disk.
  188. The latter ones are sent by filesystem mounted with
  189. discard option, whenever some data blocks are getting
  190. discarded.
  191. ============= =============================================================
  192. File /sys/block/zram<id>/mm_stat
  193. The mm_stat file represents the device's mm statistics. It consists of a single
  194. line of text and contains the following stats separated by whitespace:
  195. ================ =============================================================
  196. orig_data_size uncompressed size of data stored in this disk.
  197. Unit: bytes
  198. compr_data_size compressed size of data stored in this disk
  199. mem_used_total the amount of memory allocated for this disk. This
  200. includes allocator fragmentation and metadata overhead,
  201. allocated for this disk. So, allocator space efficiency
  202. can be calculated using compr_data_size and this statistic.
  203. Unit: bytes
  204. mem_limit the maximum amount of memory ZRAM can use to store
  205. the compressed data
  206. mem_used_max the maximum amount of memory zram has consumed to
  207. store the data
  208. same_pages the number of same element filled pages written to this disk.
  209. No memory is allocated for such pages.
  210. pages_compacted the number of pages freed during compaction
  211. huge_pages the number of incompressible pages
  212. huge_pages_since the number of incompressible pages since zram set up
  213. ================ =============================================================
  214. File /sys/block/zram<id>/bd_stat
  215. The bd_stat file represents a device's backing device statistics. It consists of
  216. a single line of text and contains the following stats separated by whitespace:
  217. ============== =============================================================
  218. bd_count size of data written in backing device.
  219. Unit: 4K bytes
  220. bd_reads the number of reads from backing device
  221. Unit: 4K bytes
  222. bd_writes the number of writes to backing device
  223. Unit: 4K bytes
  224. ============== =============================================================
  225. 9) Deactivate
  226. ==============
  227. ::
  228. swapoff /dev/zram0
  229. umount /dev/zram1
  230. 10) Reset
  231. =========
  232. Write any positive value to 'reset' sysfs node::
  233. echo 1 > /sys/block/zram0/reset
  234. echo 1 > /sys/block/zram1/reset
  235. This frees all the memory allocated for the given device and
  236. resets the disksize to zero. You must set the disksize again
  237. before reusing the device.
  238. Optional Feature
  239. ================
  240. IDLE pages tracking
  241. -------------------
  242. zram has built-in support for idle pages tracking (that is, allocated but
  243. not used pages). This feature is useful for e.g. zram writeback and
  244. recompression. In order to mark pages as idle, execute the following command::
  245. echo all > /sys/block/zramX/idle
  246. This will mark all allocated zram pages as idle. The idle mark will be
  247. removed only when the page (block) is accessed (e.g. overwritten or freed).
  248. Additionally, when CONFIG_ZRAM_TRACK_ENTRY_ACTIME is enabled, pages can be
  249. marked as idle based on how many seconds have passed since the last access to
  250. a particular zram page::
  251. echo 86400 > /sys/block/zramX/idle
  252. In this example, all pages which haven't been accessed in more than 86400
  253. seconds (one day) will be marked idle.
  254. writeback
  255. ---------
  256. With CONFIG_ZRAM_WRITEBACK, zram can write idle/incompressible page
  257. to backing storage rather than keeping it in memory.
  258. To use the feature, admin should set up backing device via::
  259. echo /dev/sda5 > /sys/block/zramX/backing_dev
  260. before disksize setting. It supports only partitions at this moment.
  261. If admin wants to use incompressible page writeback, they could do it via::
  262. echo huge > /sys/block/zramX/writeback
  263. Admin can request writeback of idle pages at right timing via::
  264. echo idle > /sys/block/zramX/writeback
  265. With the command, zram will writeback idle pages from memory to the storage.
  266. Additionally, if a user choose to writeback only huge and idle pages
  267. this can be accomplished with::
  268. echo huge_idle > /sys/block/zramX/writeback
  269. If a user chooses to writeback only incompressible pages (pages that none of
  270. algorithms can compress) this can be accomplished with::
  271. echo incompressible > /sys/block/zramX/writeback
  272. If an admin wants to write a specific page in zram device to the backing device,
  273. they could write a page index into the interface::
  274. echo "page_index=1251" > /sys/block/zramX/writeback
  275. In Linux 6.16 this interface underwent some rework. First, the interface
  276. now supports `key=value` format for all of its parameters (`type=huge_idle`,
  277. etc.) Second, the support for `page_indexes` was introduced, which specify
  278. `LOW-HIGH` range (or ranges) of pages to be written-back. This reduces the
  279. number of syscalls, but more importantly this enables optimal post-processing
  280. target selection strategy. Usage example::
  281. echo "type=idle" > /sys/block/zramX/writeback
  282. echo "page_indexes=1-100 page_indexes=200-300" > \
  283. /sys/block/zramX/writeback
  284. We also now permit multiple page_index params per call and a mix of
  285. single pages and page ranges::
  286. echo page_index=42 page_index=99 page_indexes=100-200 \
  287. page_indexes=500-700 > /sys/block/zramX/writeback
  288. If there are lots of write IO with flash device, potentially, it has
  289. flash wearout problem so that admin needs to design write limitation
  290. to guarantee storage health for entire product life.
  291. To overcome the concern, zram supports "writeback_limit" feature.
  292. The "writeback_limit_enable"'s default value is 0 so that it doesn't limit
  293. any writeback. IOW, if admin wants to apply writeback budget, they should
  294. enable writeback_limit_enable via::
  295. $ echo 1 > /sys/block/zramX/writeback_limit_enable
  296. Once writeback_limit_enable is set, zram doesn't allow any writeback
  297. until admin sets the budget via /sys/block/zramX/writeback_limit.
  298. (If admin doesn't enable writeback_limit_enable, writeback_limit's value
  299. assigned via /sys/block/zramX/writeback_limit is meaningless.)
  300. If admin wants to limit writeback as per-day 400M, they could do it
  301. like below::
  302. $ MB_SHIFT=20
  303. $ 4K_SHIFT=12
  304. $ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
  305. /sys/block/zram0/writeback_limit.
  306. $ echo 1 > /sys/block/zram0/writeback_limit_enable
  307. If admins want to allow further write again once the budget is exhausted,
  308. they could do it like below::
  309. $ echo $((400<<MB_SHIFT>>4K_SHIFT)) > \
  310. /sys/block/zram0/writeback_limit
  311. If an admin wants to see the remaining writeback budget since last set::
  312. $ cat /sys/block/zramX/writeback_limit
  313. If an admin wants to disable writeback limit, they could do::
  314. $ echo 0 > /sys/block/zramX/writeback_limit_enable
  315. The writeback_limit count will reset whenever you reset zram (e.g.,
  316. system reboot, echo 1 > /sys/block/zramX/reset) so keeping how many of
  317. writeback happened until you reset the zram to allocate extra writeback
  318. budget in next setting is user's job.
  319. By default zram stores written back pages in decompressed (raw) form, which
  320. means that writeback operation involves decompression of the page before
  321. writing it to the backing device. This behavior can be changed by enabling
  322. `compressed_writeback` feature, which causes zram to write compressed pages
  323. to the backing device, thus avoiding decompression overhead. To enable
  324. this feature, execute::
  325. $ echo yes > /sys/block/zramX/compressed_writeback
  326. Note that this feature should be configured before the `zramX` device is
  327. initialized.
  328. Depending on backing device storage type, writeback operation may benefit
  329. from a higher number of in-flight write requests (batched writes). The
  330. number of maximum in-flight writeback operations can be configured via
  331. `writeback_batch_size` attribute. To change the default value (which is 32),
  332. execute::
  333. $ echo 64 > /sys/block/zramX/writeback_batch_size
  334. If admin wants to measure writeback count in a certain period, they could
  335. know it via /sys/block/zram0/bd_stat's 3rd column.
  336. recompression
  337. -------------
  338. With CONFIG_ZRAM_MULTI_COMP, zram can recompress pages using alternative
  339. (secondary) compression algorithms. The basic idea is that alternative
  340. compression algorithm can provide better compression ratio at a price of
  341. (potentially) slower compression/decompression speeds. Alternative compression
  342. algorithm can, for example, be more successful compressing huge pages (those
  343. that default algorithm failed to compress). Another application is idle pages
  344. recompression - pages that are cold and sit in the memory can be recompressed
  345. using more effective algorithm and, hence, reduce zsmalloc memory usage.
  346. With CONFIG_ZRAM_MULTI_COMP, zram supports up to 4 compression algorithms:
  347. one primary and up to 3 secondary ones. Primary zram compressor is explained
  348. in "3) Select compression algorithm", secondary algorithms are configured
  349. using recomp_algorithm device attribute.
  350. Example:::
  351. #show supported recompression algorithms
  352. cat /sys/block/zramX/recomp_algorithm
  353. #1: lzo lzo-rle lz4 lz4hc [zstd]
  354. #2: lzo lzo-rle lz4 [lz4hc] zstd
  355. Alternative compression algorithms are sorted by priority. In the example
  356. above, zstd is used as the first alternative algorithm, which has priority
  357. of 1, while lz4hc is configured as a compression algorithm with priority 2.
  358. Alternative compression algorithm's priority is provided during algorithms
  359. configuration:::
  360. #select zstd recompression algorithm, priority 1
  361. echo "algo=zstd priority=1" > /sys/block/zramX/recomp_algorithm
  362. #select deflate recompression algorithm, priority 2
  363. echo "algo=deflate priority=2" > /sys/block/zramX/recomp_algorithm
  364. Another device attribute that CONFIG_ZRAM_MULTI_COMP enables is recompress,
  365. which controls recompression.
  366. Examples:::
  367. #IDLE pages recompression is activated by `idle` mode
  368. echo "type=idle" > /sys/block/zramX/recompress
  369. #HUGE pages recompression is activated by `huge` mode
  370. echo "type=huge" > /sys/block/zram0/recompress
  371. #HUGE_IDLE pages recompression is activated by `huge_idle` mode
  372. echo "type=huge_idle" > /sys/block/zramX/recompress
  373. The number of idle pages can be significant, so user-space can pass a size
  374. threshold (in bytes) to the recompress knob: zram will recompress only pages
  375. of equal or greater size:::
  376. #recompress all pages larger than 3000 bytes
  377. echo "threshold=3000" > /sys/block/zramX/recompress
  378. #recompress idle pages larger than 2000 bytes
  379. echo "type=idle threshold=2000" > /sys/block/zramX/recompress
  380. It is also possible to limit the number of pages zram re-compression will
  381. attempt to recompress:::
  382. echo "type=huge_idle max_pages=42" > /sys/block/zramX/recompress
  383. During re-compression for every page, that matches re-compression criteria,
  384. ZRAM iterates the list of registered alternative compression algorithms in
  385. order of their priorities. ZRAM stops either when re-compression was
  386. successful (re-compressed object is smaller in size than the original one)
  387. and matches re-compression criteria (e.g. size threshold) or when there are
  388. no secondary algorithms left to try. If none of the secondary algorithms can
  389. successfully re-compressed the page such a page is marked as incompressible,
  390. so ZRAM will not attempt to re-compress it in the future.
  391. This re-compression behaviour, when it iterates through the list of
  392. registered compression algorithms, increases our chances of finding the
  393. algorithm that successfully compresses a particular page. Sometimes, however,
  394. it is convenient (and sometimes even necessary) to limit recompression to
  395. only one particular algorithm so that it will not try any other algorithms.
  396. This can be achieved by providing a `algo` or `priority` parameter:::
  397. #use zstd algorithm only (if registered)
  398. echo "type=huge algo=zstd" > /sys/block/zramX/recompress
  399. #use zstd algorithm only (if zstd was registered under priority 1)
  400. echo "type=huge priority=1" > /sys/block/zramX/recompress
  401. memory tracking
  402. ===============
  403. With CONFIG_ZRAM_MEMORY_TRACKING, user can know information of the
  404. zram block. It could be useful to catch cold or incompressible
  405. pages of the process with*pagemap.
  406. If you enable the feature, you could see block state via
  407. /sys/kernel/debug/zram/zram0/block_state". The output is as follows::
  408. 300 75.033841 .wh...
  409. 301 63.806904 s.....
  410. 302 63.806919 ..hi..
  411. 303 62.801919 ....r.
  412. 304 146.781902 ..hi.n
  413. First column
  414. zram's block index.
  415. Second column
  416. access time since the system was booted
  417. Third column
  418. state of the block:
  419. s:
  420. same page
  421. w:
  422. written page to backing store
  423. h:
  424. huge page
  425. i:
  426. idle page
  427. r:
  428. recompressed page (secondary compression algorithm)
  429. n:
  430. none (including secondary) of algorithms could compress it
  431. First line of above example says 300th block is accessed at 75.033841sec
  432. and the block's state is huge so it is written back to the backing
  433. storage. It's a debugging feature so anyone shouldn't rely on it to work
  434. properly.
  435. Nitin Gupta
  436. ngupta@vflare.org