文档指出 zRAM 写回功能仅支持交换分区,因为它是backing_dev
.但我也成功地使用了交换文件,将其附加到循环设备
losetup /dev/loop0 /swapfile
cd /sys/block/zram0
echo /dev/loop0 > backing_dev
echo 8G > disksize
mkswap /dev/zram0
swapon /dev/zram0
之后,swapon -s
显示 zRAM 设备已启用,cat /sys/block/zram0/backing_dev
返回/dev/loop0
并echo huge > /sys/block/zram0/writeback
正常工作,并cat /sys/block/zram0/bd_stats
确认写入确实成功
这个可以用吗,或者这个方法有一些令人讨厌的缺点吗?
答案1
这可以。在 Android 上,使用环回文件启用写回功能:
static bool PrepareZramBackingDevice(off64_t size) {
constexpr const char* file_path = "/data/per_boot/zram_swap";
if (size == 0) return true;
// Prepare target path
unique_fd target_fd(TEMP_FAILURE_RETRY(open(file_path, O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
if (target_fd.get() == -1) {
PERROR << "Cannot open target path: " << file_path;
return false;
}
if (fallocate(target_fd.get(), 0, 0, size) < 0) {
PERROR << "Cannot truncate target path: " << file_path;
return false;
}
// Allocate loop device and attach it to file_path.
LoopControl loop_control;
std::string loop_device;
if (!loop_control.Attach(target_fd.get(), 5s, &loop_device)) {
return false;
}
ConfigureIoScheduler(loop_device);
ConfigureQueueDepth(loop_device, "/");
// set block size & direct IO
unique_fd loop_fd(TEMP_FAILURE_RETRY(open(loop_device.c_str(), O_RDWR | O_CLOEXEC)));
if (loop_fd.get() == -1) {
PERROR << "Cannot open " << loop_device;
return false;
}
if (!LoopControl::EnableDirectIo(loop_fd.get())) {
return false;
}
return InstallZramDevice(loop_device);
}