zram.rst 20 KB

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