swap相关概念

zram

内核文档:Documentation/admin-guide/blockdev/zram.rst

zram: Compressed RAM based block devices
The zram module creates RAM based block devices named /dev/zram
( = 0, 1, …). Pages written to these disks are compressed and stored
in memory itself. These disks allow very fast I/O and compression provides
good amounts of memory savings. Some of the usecases include /tmp storage,
use as swap disks, various caches under /var and maybe many more :)

Statistics for individual zram devices are exported through sysfs nodes at
/sys/block/zram/

ZRAM是Linux的一种内存优化技术,是把物理内存的一部分划分出来,把不是常用的内存数据压缩后放到zram里, 用到的时候把数据解压出来, 相当于牺牲了一些cpu效率,变相“增大”了内存。

内核配置:

+  CONFIG_ZSMALLOC=y
+  CONFIG_ZRAM=y
+  CONFIG_ZRAM_DEBUG=y

使用:
这里只说明相关概念,暂时不讲使用

zswap

内核文档:Documentation/vm/zswap.rst

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.

zswap是一项Linux内核的虚拟内存压缩功能,可为将要交换的页面提供压缩回写缓存。
当内存页将要交换出去时,zswap不将其移动到交换设备,而是对其执行压缩,然后存储到系统RAM内动态分配的内存池中。回写到实际交换设备的动作则会延迟,甚至能完全避免,从而显著减少Linux系统用于交换的I/O;
副作用则是压缩所需的额外CPU周期。zSWAP并不虚拟一个块设备,而是hook到普通的swap代码里,在实际发生写入到磁盘/从磁盘读取的操作前,先利用自己管理的内存进行数据的换出/换入,内存不够用以后再使用传统的swap分区。所以zSWAP适用于本身已经有交换分区的系统,而zRAM更适合Android这样本身不配置交换分区的嵌入式系统

zSwap与zRam

zRam其实有两个很大的问题,就是当内存快填满的时候,zRam本身会试图向内存返回数据,而系统会试图向zRam中填充数据。
zRam的实现是把自己虚拟成一个swap分区。而zSwap则是介入了内核的swap过程,将所有被系统swap出来的数据全部截留,存入自己的存储器中。这种实现方式有个好处,就是能和真正存在于硬盘上的swap分区联合使用。也避免了zRam的两大问题。
因为zSwap在面临内存不足时可以向swap分区写入数据,而不会试图向内存中返回数据。另一方面,如果有大段内存被空闲程序占据,zSwap可以把这些数据填入硬盘中。由于这些内存极少被使用,所以存入较慢的硬盘也不会影响运行速度。
zSwap其实可以工作在和zRam一样的模式下,只要不要设置swap分区即可

swap分区

  • 文件作为swap分区:swap_file

  • 磁盘分区作为swap分区

  • 查看swap分区信息:

    #方式1:
    swapon -s
    #方式2:
    free -m

swsusp

swsusp(swap suspend)是一种STD(Suspend to Disk)/STF(Suspend to Flash)的实现方法
内核相关文档:
Documentation/power/swsusp-and-swap-files.rst
Documentation/power/swsusp.rst

参考