Linux swap

swap文件

Gentoo Chromium 编译对内存要求很高,超出了我的笔记本 16GB,会导致 Linux Out Of Memory ,所以设置swap:

设置8G swap文件
dd if=/dev/zero of=/swapfile bs=1M count=8k status=progress
chmod 0600 /swapfile
mkswap -U clear /swapfile
swapon /swapfile
echo "/swapfile none swap defaults 0 0" >> /etc/fstab

dphys-swapfile

Raspbery Pi OS(Raspbian) 中,现在默认安装可以在 top 输出中看到默认启用了 200M swap。但是,检查 /etc/fstab 可以看到提示,当前系统使用的是 dphys-swapfile 来管理 swap文件

树莓派的 /etc/fstab 注释显示通过 dphys-swapfile 工具管理swap文件
proc            /proc           proc    defaults          0       0
PARTUUID=57a11afa-01  /boot/firmware  vfat    defaults          0       2
PARTUUID=57a11afa-02  /               ext4    defaults,noatime  0       1
# a swapfile is not a swap partition, no line here
#   use  dphys-swapfile swap[on|off]  for that

实际上检查系统 /etc/dphys-swapfile 配置文件就会明白,原来 dphys-swapfile 工具将默认启用200M的swap文件存放在 /var/swap

  • /etc/dphys-swapfile 内容:

dphys-swapfile 默认配置
# /etc/dphys-swapfile - user settings for dphys-swapfile package
# author Neil Franklin, last modification 2010.05.05
# copyright ETH Zuerich Physics Departement
#   use under either modified/non-advertising BSD or GPL license

# this file is sourced with . so full normal sh syntax applies

# the default settings are added as commented out CONF_*=* lines


# where we want the swapfile to be, this is the default
#CONF_SWAPFILE=/var/swap

# set size to absolute value, leaving empty (default) then uses computed value
#   you most likely don't want this, unless you have an special disk situation
CONF_SWAPSIZE=200

# set size to computed value, this times RAM size, dynamically adapts,
#   guarantees that there is enough swap without wasting disk space on excess
#CONF_SWAPFACTOR=2

# restrict size (computed and absolute!) to maximally this limit
#   can be set to empty for no limit, but beware of filled partitions!
#   this is/was a (outdated?) 32bit kernel limit (in MBytes), do not overrun it
#   but is also sensible on 64bit to prevent filling /var or even / partition
#CONF_MAXSWAP=2048

注意 这里 CONF_SWAPSIZE 如果被注释掉,那么 dphys-swapfile 就会动态计算swap,并且受到 CONF_MAXSWAP 的限制。也就是说,实际上会配置2G swap文件

  • 关闭 dphys-swapfile 所使用的swap:

动态关闭 dphys-swapfile
dphys-swapfile swapoff

不过动态关闭是临时的,重启系统还是会按照 /etc/dphys-swapfile 配置启用swap(默认200M)

  • 彻底关闭 dphys-swapfile (持久化配置)

彻底关闭 dphys-swapfile 服务
systemctl disable dphys-swapfile.service

swap分区

在Optane(傲腾)构建swap分区

由于 Intel Optane(傲腾)读写性能 性能和读写寿命都远超常规SSD,所以我在 树莓派Raspberry Pi 5 上采用 Intel Optane(傲腾) M10 来构建swap分区,以便扩展 树莓派Raspberry Pi 5 有限的8G内存:

构建swap分区
# 已经使用fdisk划分好分区
mkswap /dev/nvme1n1p1
swapon /dev/nvme1n1p1

最后在 /etc/fstab 中添加如下配置:

/etc/fstab 添加swap分区配置
# 请根据blkid输出信息填写
PARTUUID=37f5e84b-01 none swap defaults 0 0

参考