Skip to contentSkip to conversation

dm bug: hibernate to swap located on dm-integrity doesn't work (how to get data redundancy for swap?)

PATCH In review Askar Safin 6 participants 27 messages Oct 23, 2025 – Jan 14 1 message not in the archive

Subsystems (9)
lore
Share & tools
lore
#0 lore raw

Hi.

Hibernate to swap located on dm-integrity doesn't work.
Let me first describe why I need this, then I will describe a bug with steps to reproduce (and some speculation on cause of the bug).

I want a personal Linux laptop fully protected from data corruption (cosmic rays, etc). And even if data corruption does happen, I want reliable indication of that, so that I know that I need to restore from backups and replace faulty hardware.

So I did this:
- I bought a laptop with ECC memory: Dell Precision 7780. It seems to be one of the few laptop models in the world with ECC memory. And probably the only model in the world, which DOES HAVE ECC memory, but DOES NOT HAVE nvidia card
- I set up btrfs raid-1

So far, so good. I'm protected from both memory errors and disk errors.

But my swap partition stays unprotected. And yes, I need swap. I have 64 GiB of RAM, but this still is not enough for zillions of Chromium tabs and vscode windows.

And, according to btrfs docs, if I put swapfile to btrfs, it will be exempt from raid-1 guarantees.

It seems that the only solution in this case is to put swap partition on top of dm-integrity.

Note: I don't need error correcting code for my swap. I don't need a self-healing swap. The only thing I need is reliable error detection.

There is discussion on Stack Exchange on exactly the same problem:
https://unix.stackexchange.com/questions/269098/silent-disk-errors-and-reliability-of-linux-swap . I think it reached the same conclusion: the only solution is dm-integrity.

Also, as well as I understand, md raid is not a solution: when reading, it reads from one disk only, and thus doesn't detect all errors. It can detect remaining errors during scrub, which is too late (wrong data may be already consumed by some app).

Also: I don't need encryption.

(Also: there is other solution: "cryptsetup --integrity", but it uses dm-integrity anyway. We will get to it.)

Okay, so I put swap partition to dm-integrity, and it worked!

But then hibernation stopped to work.

And here come steps to reproduce.

Okay, so I have Dell Precision 7780. I bought it year ago, so I don't think my hardware is faulty. Also, I recently updated BIOS.

My OS is Debian Trixie amd64. My kernel is Linux 6.12.48-1 from Debian. I created swap partition so:

integritysetup format --integrity xxhash64 /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 integritysetup open --integrity xxhash64 /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 swap mkswap /dev/mapper/swap
swapon /dev/mapper/swap

When I need to activate swap, I do this:

integritysetup open --integrity xxhash64 /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 swap swapon /dev/mapper/swap

When I need to hibernate, I do "systemctl hibernate".

And hibernate appears to work.

Then, when I need to resume, I boot to my hand-crafted initramfs. That initramfs does this (I slightly simplified this script):

==
busybox mount -t proc proc /proc
busybox mount -t devtmpfs devtmpfs /dev
busybox mount -t sysfs sysfs /sys
modprobe nvme
modprobe dm-integrity
modprobe xxhash64
sleep 1
integritysetup open --integrity xxhash64 "$LOWER_SWAP_DEV" early-swap sleep 1
# The following "blkid" command should detect what is present on /dev/mapper/early-swap TYPE="$(blkid --match-tag TYPE --output value /dev/mapper/early-swap)"
if [ "$TYPE" = 'swsuspend' ]; then
echo "got hibernation image, trying to resume"
echo /dev/mapper/early-swap > /sys/power/resume
elif [ "$TYPE" = 'swap' ]; then
echo 'got normal swap without hibernation image'
integritysetup close early-swap

  # proceed with fresh boot here
fi
==

And this doesn't work. Hibernate works, resume doesn't. :) "blkid" reports swap as "swap" as opposed to "swsuspend".

I suspect this is because hibernation doesn't flush dm-integrity journal.

Also I tried to add "--integrity-bitmap-mode" to "format" and "open". Resume started to work, but when I try to shutdown resumed system, I get errors about corrupted dm-integrity partition. (Of course, I did necessary edits to initramfs script above.)

Also I tried to add "--integrity-no-journal" to "format" and "open". It didn't work, either. (I don't remember what exactly didn't work. I can do this experiment again, if needed.)

Then I tried to do "cryptsetup" instead of "integritysetup". I created swap partition so:

cryptsetup luksFormat --type luks2 /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 /tmp/key cryptsetup open --type luks2 --key-file /tmp/key /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 swap mkswap /dev/mapper/swap
swapon /dev/mapper/swap

And, of course, I did all necessary edits to initramfs.

And this time everything worked. This proves that I didn't do any mistakes in my setup (i. e. I got initramfs right, etc), and this is actual bug in dm-integrity.

Unfortunately, LUKS created such way doesn't have any redundancy. So this is not solution for me.

So I did this:
cryptsetup luksFormat --type luks2 --integrity hmac-sha256 /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 /tmp/key cryptsetup open --type luks2 --key-file /tmp/key /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 swap mkswap /dev/mapper/swap
swapon /dev/mapper/swap

And this time everything stopped to work, again. I don't remember what exactly went wrong. As well as I remember, that "blkid" again returned "swap" instead of "swsuspend". I can run experiment again, if needed.

The commands above use dm-integrity internally. So we clearly see: if dm-integrity is involved, then hibernation doesn't work.

Here is a user with exactly same problem:
https://www.reddit.com/r/archlinux/comments/atg18t/hibernation_wipes_swap_and_my_system_hangs_on_boot/ . I. e. "hibernation doesn't work if swap is on LUKS with integrity protection".

So, please, fix this bug. Or say me how to solve my original problem (i. e. achieving full reliable error reporting). I'm available for testing. Send me experimental patches. I can provide more info, if needed.

There is yet another potential solution: uswsusp ( https://docs.kernel.org/power/userland-swsusp.html ). In short, this is hibernation driven from userspace. I. e. uswsusp allows for finer control of hibernation. Thus, I can write my own userspace util, which will do hibernation, and execute "integritysetup close" after writing image. Assuming that original problem is what I think (i. e. lack of journal flush after writing of image), this may work. The problem is... latest commit to userspace implementation is dated 2012-09-15
( https://git.kernel.org/pub/scm/linux/kernel/git/rafael/suspend-utils.git/ ). Do I really need to use such ancient technology? I didn't test this yet, I will test it in coming days. Even if it works, this will still mean that dm-integrity is buggy with kernel-based hibernation.

Signature · 1 line
Askar Safin
#1 lore raw

Hi,

I am not sure why you cc so many people, most of lists are not relevant here.

Anyway, could you please test one thing below so the problem is better isolated?

On 10/23/25 1:29 PM, Askar Safin wrote:
...

Quoted 3 lines

Also I tried to add "--integrity-no-journal" to "format" and "open". It didn't work, either. (I don't remember what exactly didn't work. I can do this experiment again, if needed.)

Are you sure you used --integrity-no-journal both in activation before hibernation and also in resume? If not, please try it.
This flag activates direct mode and and completely avoids dm-integrity journal. You can verify it with "integritysetup status <device>" - it should say "journal: not active".

And if it does not work, could you try to use -integrity-recovery-mode the same
way (both before hibernation and later in resume)? This will effectively ignore checksums providing no protection, but keeping dm-integrity device still in place.
You can verify it with "integritysetup status <device>" - it should say "mode: read/write recovery". Is the problem still in place with this setting?

You can also try to decrease journal commit time with --journal-commit-time option, but this is not a real solution.

...>

Quoted 8 lines

Then I tried to do "cryptsetup" instead of "integritysetup". I created swap partition so:

cryptsetup luksFormat --type luks2 /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 /tmp/key cryptsetup open --type luks2 --key-file /tmp/key /dev/disk/by-partuuid/c4bbc73d-7909-42ea-8d96-eab82512cbe7 swap mkswap /dev/mapper/swap
swapon /dev/mapper/swap

Quoted 6 lines

And, of course, I did all necessary edits to initramfs.

And this time everything worked. This proves that I didn't do any mistakes in my setup (i. e. I got initramfs right, etc), and this is actual bug in dm-integrity.

Unfortunately, LUKS created such way doesn't have any redundancy. So this is not solution for me.

Redundancy? You mean data integrity protection? There is no redundancy, only additional authentication tag (detecting integrity error but not correcting it).

Thanks,
Milan

#2 lore raw

Milan Broz <[email protected]>:

Quoted 1 line

Hi,

I just wrote script for reproduction of this bug in Qemu:
https://zerobin.net/?4e742925aedbecc6#BX3Tulvp7E3gKhopFKrx/2ZdOelMyYk1qOyitcOr1h8=

Just run it, and you will reproduce this bug, too.

Also, I just reproduced it on current master (43e9ad0c55a3).

Here is output of this script on master:
https://zerobin.net/?68ef6601ab203a11#7zBZ44AaVKmvRq161MJaOXIXY/5Hiv+hRUxWoqyZ7uE=

As you can see, hibernate succeeds, but resume fails so:

+ blkid --match-tag TYPE --output value /dev/mapper/early-swap
+ TYPE=swap
+ echo 'Type: swap'
Type: swap
+ echo /dev/mapper/early-swap

[    0.446545] PM: Image not found (code -22)

Also, I just noticed that the bug sometimes reproduces, and sometimes not. Still it reproduces more than 50% of time.

Also, you will find backtrace in logs above. Disregard it. I think this is just some master bug, which is unrelated to our dm-integrity bug.

I will answer to rest of your letter later.

Also, I saw patch, I will test it later.

Signature · 1 line
Askar Safin
#3 lore raw
Quoted 2 lines · Askar Safin

Also, I saw patch, I will test it later.

Yes, please test it, you can ignore may previous comments as they are irrelevant now. Here is the link to the mentioned patch:
https://lore.kernel.org/dm-devel/[email protected]/T/#u

I think that the issue is clear (as found by Mikulas)
- DM device (dm-integrity here) does not receive the FLUSH command here.

This would explain all issues you see. If the patch works, it should be fixed in stable kernels as it impacts other more complex storage configurations.

Thanks,
Milan

#4 lore raw
In reply to Askar Safin

Askar Safin <[email protected]>:

Quoted 2 lines

Here is output of this script on master:
https://zerobin.net/?68ef6601ab203a11#7zBZ44AaVKmvRq161MJaOXIXY/5Hiv+hRUxWoqyZ7uE=

[...]

Quoted 2 lines

Also, you will find backtrace in logs above. Disregard it. I think this is just some master bug, which is unrelated to our dm-integrity bug.

That WARNING in logs is unrelated bug, which happens always when I hibernate.
I reported it here: https://lore.kernel.org/regressions/[email protected]/

Signature · 1 line
Askar Safin
#5 lore raw
In reply to Milan Broz

Milan Broz <[email protected]>:

Quoted 1 line

Hi,

That patch doesn't fix the problem. I will send more details within some days, hopefully today.

Also, I just found that for reliable reproduction you need to do "swapoff /dev/mapper/swap; cat /dev/mapper/swap > /dev/null" after resume (assuming you were able to resume, of course).

So here is updated script for reproduction in Qemu:

https://zerobin.net/?0aa379bae218cf92#DDVFMvfi6S3ydCQLSrL+us1lHjXQJIZasW55JI7gEfU=

This script is very easy to use!

Try 1-2 times to reproduce.

Here is result of that script:

https://zerobin.net/?3d9447900052f9ce#ng0htJDAdSsvqVunL+BnoLHXszM6ardt9R3wkbO9L28=

This results are on 43e9ad0c55a3, which is current master, without Mikulas Patocka's patch, but with this Mario's patch:
https://lore.kernel.org/linux-pm/[email protected]/ . Mario's patch is needed, otherwise we get WARNING when we try to hibernate.

Again: these logs are without Mikulas Patocka's patch. I will send results of testing his patch later, hopefully today. But don't expect much. As I said, his patch doesn't work.

"log-def-1" is output of first Qemu invocation (i. e. first boot) with default integritysetup options. "log-def-2" is second Qemu invocation (i. e. when we try to resume).

log-bit-{1,2} is same thing, but with "--integrity-bitmap-mode" added to "integritysetup format" and "integritysetup open".

log-no-{1,2} is same, but with "--integrity-no-journal".

log-nodm-{1,2} is same, but without dm-integrity at all, i. e. we create swap directly on partition.

As you can see in logs, hibernate with dm-integrity never works perfectly. We either unable to resume, either we are able to resume, but then get integrity errors when we do "cat /dev/mapper/swap > /dev/null".

Swap directly on partition works.

Again: you may need 1-2 attempts to reproduce using this script.

Also: the bug is reproducible even if we do "echo test_resume > /sys/power/disk".

Quoted 2 lines

Are you sure you used --integrity-no-journal both in activation before hibernation and also in resume? If not, please try it.

I'm totally sure. (You can see script above and "set -x" output in logs.)

Quoted 1 line

You can verify it with "integritysetup status <device>" - it should say "journal: not active".

I just checked. It indeed says so.

Quoted 2 lines

And if it does not work, could you try to use -integrity-recovery-mode the same way (both before hibernation and later in resume)? This will effectively ignore checksums

So I should pass it to both "integritysetup open" invocations, but not to "integritysetup format" invocation. Right? Okay, I did so.

I. e. I did this:

integritysetup format --batch-mode --integrity xxhash64 /dev/sda # when formatting integritysetup open --integrity-recovery-mode --integrity xxhash64 /dev/sda swap # before hibernate integritysetup open --integrity-recovery-mode --integrity xxhash64 /dev/sda early-swap # when resuming

And something completely unexpected happened!
"swapon" failed immediately after "mkswap"!!! I. e. "swapon" was unable to read swap signature right after "mkswap". Here is log:
https://zerobin.net/?ebe34fc9ce94be45#6DWKSXvgUDKIrF4299th0ylhQNEcdqeeBfxzSJjROpA=
This seems like another dm-integrity bug.

Quoted 1 line

You can verify it with "integritysetup status <device>" - it should say "mode: read/write recovery".

Yes, it says so in logs above.

Quoted 1 line

You can also try to decrease journal commit time with --journal-commit-time option,

I just put "--journal-commit-time 1" to format and both opens. I got the same result I get with default options: i. e. blkid returns "swap" instead of "swsuspend", when I try to resume. Here are logs:
https://zerobin.net/?c5f8320eb89b1cfb#drrxRgnGk817oEDUA8idhn+WEQgocWjtbsAYuEHF5rI= .

Quoted 2 lines

Redundancy? You mean data integrity protection? There is no redundancy, only additional authentication tag (detecting integrity error but not correcting it).

Yes, I meant integrity protection.

Signature · 1 line
Askar Safin

A message that is not in the archive (sent off-list or not yet received): [email protected]

maintainer
#7 lore raw

PATCH 1/1 pm-hibernate: flush block device cache when hibernating

Quoted 6 lines · Askar Safin

Hi.

Hibernate to swap located on dm-integrity doesn't work.
Let me first describe why I need this, then I will describe a bug with steps to reproduce
(and some speculation on cause of the bug).

Hi

Does this patch fix it?

Mikulas

From: Mikulas Patocka <[email protected]>

There was reported failure that hibernation doesn't work with dm-integrity. The reason for the failure is that the hibernation code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

This commit fixes the suspend code so that it issues flushes before writing the header and after writing the header.

---
 kernel/power/swap.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/power/swap.c +3 -1
Index: linux-2.6/kernel/power/swap.c
===================================================================
@@ -320,8 +320,10 @@ static int mark_swapfiles(struct swap_ma
 		swsusp_header->flags = flags;
 		if (flags & SF_CRC32_MODE)
 			swsusp_header->crc32 = handle->crc32;
-		error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC,
+		error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH,
 				      swsusp_resume_block, swsusp_header);
+		if (!error)
+			error = blkdev_issue_flush(file_bdev(hib_resume_bdev_file));
 	} else {
 		pr_err("Swap header not found!\n");
 		error = -ENODEV;
#8 lore raw

Re: [PATCH] pm-hibernate: flush block device cache when hibernating

Mikulas Patocka <[email protected]>:

Quoted 7 lines

Hi

Does this patch fix it?

Mikulas

Quoted 6 lines

From: Mikulas Patocka <[email protected]>

There was reported failure that hibernation doesn't work with dm-integrity. The reason for the failure is that the hibernation code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

I tested this patch in Qemu on current master (43e9ad0c55a3). Also I applied Mario's patch
https://lore.kernel.org/linux-pm/[email protected]/ . It is needed, otherwise you get WARNING when you try to hibernate.

The patch doesn't work.

Here is script I used for reproduction:
https://zerobin.net/?66669be7d2404586#xWufhCq7zCoOk3LJcJCj7W4k3vYT3U4vhGutTN3p8m0= . It is the same script as in previous letter. I just added some "integritysetup status /dev/mapper/..." calls.

Here are results:
https://zerobin.net/?2331637d633d20c5#EmyhxiHLDmoZT1jBVbe/q9iJKhDEw4n+Bwr5mAcaOpM= .

File names mean the same as in previous letter, i. e.:

Quoted 11 lines

"log-def-1" is output of first Qemu invocation (i. e. first boot) with default integritysetup options. "log-def-2" is second Qemu invocation (i. e. when we try to resume).

log-bit-{1,2} is same thing, but with "--integrity-bitmap-mode" added to "integritysetup format" and "integritysetup open".

log-no-{1,2} is same, but with "--integrity-no-journal".

log-nodm-{1,2} is same, but without dm-integrity at all, i. e. we create swap directly on partition.

Results are somewhat better than without the patch. Without the patch we don't even try to resume in default mode. "blkid" simply reports "swap" instead of "swsuspend". With patch "blkid" reports "swsuspend", and so we try to resume. But then in the middle of resuming we get this:

[    1.008223] PM: Image loading progress:  70%
[    1.017478] PM: Image loading progress:  80%
[    1.027069] PM: Image loading progress:  90%
[    1.029653] PM: hibernation: Read 36196 kbytes in 0.49 seconds (73.86 MB/s)
[    1.030146] PM: Error -1 resuming
[    1.030322] PM: hibernation: Failed to load image, recovering.

(See link above for full logs.)

Very similar thing happens in "--integrity-no-journal" mode in the middle of resuming:

[    0.531245] device-mapper: integrity: dm-0: Checksum failed at sector 0x6e70
[    0.531600] PM: Error -84 resuming
[    0.531799] PM: hibernation: Failed to load image, recovering.

The patch doesn't change anything in "--integrity-bitmap-mode" mode:
we still are able to resume, but then get integrity errors when we do "cat /dev/mapper/swap > /dev/null".

Signature · 1 line
Askar Safin
maintainer
#9 lore raw

Re: [PATCH] pm-hibernate: flush block device cache when hibernating

Quoted 15 lines · Askar Safin

Mikulas Patocka <[email protected]>:

Quoted 7 lines

Hi

Does this patch fix it?

Mikulas

Quoted 6 lines

From: Mikulas Patocka <[email protected]>

There was reported failure that hibernation doesn't work with dm-integrity. The reason for the failure is that the hibernation code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

Quoted 6 lines

I tested this patch in Qemu on current master (43e9ad0c55a3). Also I applied Mario's patch
https://lore.kernel.org/linux-pm/[email protected]/ . It is needed, otherwise you get WARNING when you try to hibernate.

The patch doesn't work.

Yes, I see - the problem is harder than I thought.

I've created two patches and I tested them that they work. So, you can try them.

Mikulas

maintainer
#10 lore raw

PATCH 1/2 pm-hibernate: flush disk cache when suspending

[PATCH 1/2] pm-hibernate: flush disk cache when suspending

There was reported failure that suspend doesn't work with dm-integrity. The reason for the failure is that the suspend code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

This commit fixes the suspend code so that it issues flushes before writing the header and after writing the header.

Note that the system may lose power during suspend - in this situation, we don't want to attempt to resume with invalid data. So, we flush the cache before writing the header (with REQ_PREFLUSH) and after writing the header (with REQ_FUA).

The call to flush_swap_writer was moved up in swap_writer_finish, so that it writes the data before mark_swapfiles writes the header.

REQ_FUA is also needed on resume, when marking resumed image with the original swap header.

---
 kernel/power/swap.c |    9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
kernel/power/swap.c +5 -4
Index: linux-2.6/kernel/power/swap.c
===================================================================
@@ -320,7 +320,7 @@ static int mark_swapfiles(struct swap_ma
 		swsusp_header->flags = flags;
 		if (flags & SF_CRC32_MODE)
 			swsusp_header->crc32 = handle->crc32;
-		error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC,
+		error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH | REQ_FUA,
 				      swsusp_resume_block, swsusp_header);
 	} else {
 		pr_err("Swap header not found!\n");
@@ -486,11 +486,12 @@ static int flush_swap_writer(struct swap
 static int swap_writer_finish(struct swap_map_handle *handle,
 		unsigned int flags, int error)
 {
+	if (!error)
+		error = flush_swap_writer(handle);
 	if (!error) {
 		pr_info("S");
 		error = mark_swapfiles(handle, flags);
 		pr_cont("|\n");
-		flush_swap_writer(handle);
 	}
 
 	if (error)
@@ -1587,7 +1588,7 @@ int swsusp_check(bool exclusive)
 			memcpy(swsusp_header->sig, swsusp_header->orig_sig, 10);
 			swsusp_header_flags = swsusp_header->flags;
 			/* Reset swap signature now */
-			error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC,
+			error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_FUA,
 						swsusp_resume_block,
 						swsusp_header);
 		} else {
@@ -1641,7 +1642,7 @@ int swsusp_unmark(void)
 	hib_submit_io_sync(REQ_OP_READ, swsusp_resume_block, swsusp_header);
 	if (!memcmp(HIBERNATE_SIG,swsusp_header->sig, 10)) {
 		memcpy(swsusp_header->sig,swsusp_header->orig_sig, 10);
-		error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC,
+		error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_FUA,
 					swsusp_resume_block,
 					swsusp_header);
 	} else {
#11 lore raw

Re: [PATCH 1/2] pm-hibernate: flush disk cache when suspending

Mikulas Patocka <[email protected]>:

Quoted 6 lines

[PATCH 1/2] pm-hibernate: flush disk cache when suspending

There was reported failure that suspend doesn't work with dm-integrity. The reason for the failure is that the suspend code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

Thank you! I hope I will test this within 2 weeks.

Signature · 1 line
Askar Safin
#12 lore raw

Re: [PATCH 1/2] pm-hibernate: flush disk cache when suspending

Quoted 9 lines · Askar Safin

Mikulas Patocka <[email protected]>:

Quoted 6 lines

[PATCH 1/2] pm-hibernate: flush disk cache when suspending

There was reported failure that suspend doesn't work with dm-integrity. The reason for the failure is that the suspend code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

Thank you! I hope I will test this within 2 weeks.

Hello,

Did you manage to test the patches?

This issue should not be forgotten, as dm-integrity corrupts data during suspend.

Thanks,
Milan

#13 lore raw

Re: [PATCH 1/2] pm-hibernate: flush disk cache when suspending

In reply to Mikulas Patocka

Mikulas Patocka <[email protected]>:

Quoted 6 lines

[PATCH 1/2] pm-hibernate: flush disk cache when suspending

There was reported failure that suspend doesn't work with dm-integrity. The reason for the failure is that the suspend code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

Your patchset is impossible to apply using "b4 shazam".

Here is what I get when I try to apply it using "b4 shazam":

d-user@comp:/tmp$ git clone --depth=1 git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
Cloning into 'linux'...
remote: Enumerating objects: 96577, done.
remote: Counting objects: 100% (96577/96577), done.
remote: Compressing objects: 100% (93936/93936), done.
remote: Total 96577 (delta 7530), reused 20945 (delta 1607), pack-reused 0 (from 0)
Receiving objects: 100% (96577/96577), 267.21 MiB | 1.85 MiB/s, done.
Resolving deltas: 100% (7530/7530), done.
Updating files: 100% (91166/91166), done.
d-user@comp:/tmp$ cd linux
d-user@comp:/tmp/linux$ b4 shazam '[email protected]'
Grabbing thread from lore.kernel.org/all/[email protected]/t.mbox.gz
Checking for newer revisions
Grabbing search results from lore.kernel.org
Analyzing 15 messages in the thread
WARNING: duplicate messages found at index 1
   Subject 1: pm-hibernate: flush block device cache when hibernating
   Subject 2: pm-hibernate: flush disk cache when suspending
  2 is not a reply... assume additional patch
WARNING: duplicate messages found at index 2
   Subject 1: swsusp: make it possible to hibernate to device mapper devices
   Subject 2: pm-hibernate: flush disk cache when suspending
  2 is not a reply... assume additional patch
Checking attestation on all messages, may take a moment...
---
  ✓ [PATCH] pm-hibernate: flush block device cache when hibernating
    ✓ Signed: DKIM/redhat.com
  ✓ [PATCH RFC 2/2] swsusp: make it possible to hibernate to device mapper devices
    ✓ Signed: DKIM/redhat.com
  ✓ [PATCH 1/2] pm-hibernate: flush disk cache when suspending
    ✓ Signed: DKIM/redhat.com
  ERROR: missing [4/3]!
---
Total patches: 3
---
WARNING: Thread incomplete!
Applying: pm-hibernate: flush block device cache when hibernating
Applying: swsusp: make it possible to hibernate to device mapper devices
Patch failed at 0002 swsusp: make it possible to hibernate to device mapper devices
error: patch failed: kernel/power/swap.c:1591
error: kernel/power/swap.c: patch does not apply
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config advice.mergeConflict false"

It seems you should send patches not as a reply.

But I will apply your patches anyway, no need to resubmit.

Signature · 1 line
Askar Safin
author Tested-by on v1 1/2
#14 lore raw

Re: [PATCH 1/2] pm-hibernate: flush disk cache when suspending

In reply to Mikulas Patocka

Mikulas Patocka <[email protected]>:

Quoted 6 lines

[PATCH 1/2] pm-hibernate: flush disk cache when suspending

There was reported failure that suspend doesn't work with dm-integrity. The reason for the failure is that the suspend code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

I tested this patchset (in Qemu). It works.

Here is script I used for testing:

https://zerobin.net/?66669be7d2404586#xWufhCq7zCoOk3LJcJCj7W4k3vYT3U4vhGutTN3p8m0=

Here are logs:

https://zerobin.net/?5d4a2abbad751890#WMcQl4FAZC9KqcAuJU3TSVr7wuVnPFwI7dlinA9QHOo=

There was no any reason to wait for me. You could easily test using script above.

Also: Linux shows this scary message when booting in Qemu:

[    0.512581] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA

So, FUA is not supported? Does it mean that this patch is wrong, and works purely by chance?

Signature · 1 line
Askar Safin
maintainer
#15 lore raw

Re: [PATCH 1/2] pm-hibernate: flush disk cache when suspending

Quoted 20 lines · Askar Safin

Mikulas Patocka <[email protected]>:

Quoted 6 lines

[PATCH 1/2] pm-hibernate: flush disk cache when suspending

There was reported failure that suspend doesn't work with dm-integrity. The reason for the failure is that the suspend code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

I tested this patchset (in Qemu). It works.

Here is script I used for testing:

https://zerobin.net/?66669be7d2404586#xWufhCq7zCoOk3LJcJCj7W4k3vYT3U4vhGutTN3p8m0=

Here are logs:

https://zerobin.net/?5d4a2abbad751890#WMcQl4FAZC9KqcAuJU3TSVr7wuVnPFwI7dlinA9QHOo=

Quoted 8 lines

There was no any reason to wait for me. You could easily test using script above.

Also: Linux shows this scary message when booting in Qemu:

[    0.512581] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA

So, FUA is not supported? Does it mean that this patch is wrong, and works purely by chance?

If FUA is not supported by a disk, the kernel would send a flush request after the write request with the FUA flag. There's no problem with that - the cache will be flushed correctly.

Mikulas

Quoted 3 lines
Signature · 1 line
Askar Safin
maintainer
#16 lore raw

RFC PATCH 2/2 swsusp: make it possible to hibernate to device mapper devices

In reply to Mikulas Patocka

Hi

Askar Safin requires swap and hibernation on the dm-integrity device mapper target because he needs to protect his data.

This hits two problems:
1. The kernel doesn't send the flush bio to the hibernation device after writing the image and before powering off - this is easy to fix
2. The dm-integrity target keeps parts of the device in-memory - it keeps a journal and a dm-bufio cache in memory. If we hibernate and resume, the content of memory no longer matches the data on the hibernate partition and that may cause spurious errors - this is hard to fix

We cannot use register_pm_notifier - the problem is that device mapper devices may depend on each other, forming a directed acyclic graph, and we need to suspend them in the order of the graph. PM notifiers have no notion of the graph - they have priority, but mapping the priorities to the device dependency graph would be hard.

So I added a new method "hibernate" to struct block_device_operations. If the method is NULL, the device doesn't need special treatment during hibernation. If the method is non-NULL, the method is called on the swap device where we are suspending - the method will clear in-memory structures (in the case of dm-integrity, it will flush the journal and invalidate the dm-bufio cache), so that when the machine is resumed, the driver won't use stale data. Finally, the "hibernate" method calls itself on subordinate devices, so that complex stack of device mapper devices is handled correctly.

Hibernation is allowed only on targets that have DM_TARGET_HIBERNATE. Hibernation on other targets is rejected because it may cause data corruption. Previously, the kernel would allow hibernation on any DM device, causing potential data corruption if the in-memory metadata doesn't match the content of the swap device.

I am submitting this patch as a request for comment - I'd like to know if you consider this approach correct or not. If you would like to solve the hibernation problem in some other way, let me know.

---
 drivers/md/dm-crypt.c         |    2 -
 drivers/md/dm-integrity.c     |   42 ++++++++++++++++++++++++++++++++++++++-
 drivers/md/dm-linear.c        |    2 -
 drivers/md/dm-stripe.c        |    3 +-
 drivers/md/dm.c               |   45 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/blkdev.h        |   12 +++++++++++
 include/linux/device-mapper.h |    6 +++++
 kernel/power/hibernate.c      |    4 +++
 kernel/power/power.h          |    2 +
 kernel/power/swap.c           |   20 ++++++++++++++++++
 10 files changed, 134 insertions(+), 4 deletions(-)
include/linux/blkdev.h +12 -0
Index: linux-2.6/include/linux/blkdev.h
===================================================================
@@ -1676,6 +1676,11 @@ struct block_device_operations {
 	 * driver.
 	 */
 	int (*alternative_gpt_sector)(struct gendisk *disk, sector_t *sector);
+
+	/*
+	 * This invalidates the device cache when hibernating.
+	 */
+	int (*hibernate)(struct gendisk *disk);
 };
 
 #ifdef CONFIG_COMPAT
@@ -1875,4 +1880,11 @@ static inline int bio_split_rw_at(struct
 
 #define DEFINE_IO_COMP_BATCH(name)	struct io_comp_batch name = { }
 
+static inline int bdev_hibernate(struct block_device *bdev)
+{
+	if (!bdev->bd_disk->fops->hibernate)
+		return 0;
+	return bdev->bd_disk->fops->hibernate(bdev->bd_disk);
+}
+
 #endif /* _LINUX_BLKDEV_H */
drivers/md/dm-integrity.c +41 -1

60 lines not on this page · raw message

drivers/md/dm.c +45 -0

57 lines not on this page · raw message

include/linux/device-mapper.h +6 -0
Index: linux-2.6/include/linux/device-mapper.h
===================================================================
@@ -142,6 +142,8 @@ typedef int (*dm_iterate_devices_fn) (st
 typedef void (*dm_io_hints_fn) (struct dm_target *ti,
 				struct queue_limits *limits);
 
+typedef int (*dm_hibernate_fn) (struct dm_target *ti);
+
 /*
  * Returns:
  *    0: The target can handle the next I/O immediately.
@@ -219,6 +221,7 @@ struct target_type {
 	dm_busy_fn busy;
 	dm_iterate_devices_fn iterate_devices;
 	dm_io_hints_fn io_hints;
+	dm_hibernate_fn hibernate;
 	dm_dax_direct_access_fn direct_access;
 	dm_dax_zero_page_range_fn dax_zero_page_range;
 	dm_dax_recovery_write_fn dax_recovery_write;
@@ -309,6 +312,9 @@ struct target_type {
 #define DM_TARGET_ATOMIC_WRITES		0x00000400
 #define dm_target_supports_atomic_writes(type) ((type)->features & DM_TARGET_ATOMIC_WRITES)
 
+#define DM_TARGET_HIBERNATE		0x00000800
+#define dm_target_supports_hibernate(type) ((type)->features & DM_TARGET_HIBERNATE)
+
 struct dm_target {
 	struct dm_table *table;
 	struct target_type *type;
kernel/power/hibernate.c +4 -0
Index: linux-2.6/kernel/power/hibernate.c
===================================================================
@@ -832,6 +832,10 @@ int hibernate(void)
 	if (error)
 		goto Exit;
 
+	error = notify_swap_device();
+	if (error)
+		goto Thaw;
+
 	lock_device_hotplug();
 	/* Allocate memory management structures */
 	error = create_basic_memory_bitmaps();
kernel/power/power.h +2 -0
Index: linux-2.6/kernel/power/power.h
===================================================================
@@ -68,6 +68,8 @@ extern int hibernation_snapshot(int plat
 extern int hibernation_restore(int platform_mode);
 extern int hibernation_platform_enter(void);
 
+extern int notify_swap_device(void);
+
 #ifdef CONFIG_STRICT_KERNEL_RWX
 /* kernel/power/snapshot.c */
 extern void enable_restore_image_protection(void);
kernel/power/swap.c +20 -0
Index: linux-2.6/kernel/power/swap.c
===================================================================
@@ -1591,6 +1591,9 @@ int swsusp_check(bool exclusive)
 			error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_FUA,
 						swsusp_resume_block,
 						swsusp_header);
+
+			/* Flush device-mapper related metadata */
+			bdev_hibernate(file_bdev(hib_resume_bdev_file));
 		} else {
 			error = -EINVAL;
 		}
@@ -1630,6 +1633,23 @@ void swsusp_close(void)
 	fput(hib_resume_bdev_file);
 }
 
+int notify_swap_device(void)
+{
+	int error;
+
+	error = swsusp_swap_check();
+	if (error)
+		return error;
+
+	error = bdev_hibernate(file_bdev(hib_resume_bdev_file));
+	if (error)
+		pr_err("Swap is on unsupported device\n");
+
+	swsusp_close();
+
+	return error;
+}
+
 /**
  *      swsusp_unmark - Unmark swsusp signature in the resume device
  */
drivers/md/dm-crypt.c +1 -1
Index: linux-2.6/drivers/md/dm-crypt.c
===================================================================
@@ -3770,7 +3770,7 @@ static struct target_type crypt_target =
 	.module = THIS_MODULE,
 	.ctr    = crypt_ctr,
 	.dtr    = crypt_dtr,
-	.features = DM_TARGET_ZONED_HM,
+	.features = DM_TARGET_ZONED_HM | DM_TARGET_HIBERNATE,
 	.report_zones = crypt_report_zones,
 	.map    = crypt_map,
 	.status = crypt_status,
drivers/md/dm-linear.c +1 -1
Index: linux-2.6/drivers/md/dm-linear.c
===================================================================
@@ -204,7 +204,7 @@ static struct target_type linear_target
 	.version = {1, 5, 0},
 	.features = DM_TARGET_PASSES_INTEGRITY | DM_TARGET_NOWAIT |
 		    DM_TARGET_ZONED_HM | DM_TARGET_PASSES_CRYPTO |
-		    DM_TARGET_ATOMIC_WRITES,
+		    DM_TARGET_ATOMIC_WRITES | DM_TARGET_HIBERNATE,
 	.report_zones = linear_report_zones,
 	.module = THIS_MODULE,
 	.ctr    = linear_ctr,
drivers/md/dm-stripe.c +2 -1
Index: linux-2.6/drivers/md/dm-stripe.c
===================================================================
@@ -471,7 +471,8 @@ static struct target_type stripe_target
 	.name   = "striped",
 	.version = {1, 7, 0},
 	.features = DM_TARGET_PASSES_INTEGRITY | DM_TARGET_NOWAIT |
-		    DM_TARGET_ATOMIC_WRITES | DM_TARGET_PASSES_CRYPTO,
+		    DM_TARGET_ATOMIC_WRITES | DM_TARGET_PASSES_CRYPTO |
+		    DM_TARGET_HIBERNATE,
 	.module = THIS_MODULE,
 	.ctr    = stripe_ctr,
 	.dtr    = stripe_dtr,
#17 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

Mikulas Patocka <[email protected]>:
https://lore.kernel.org/linux-pm/[email protected]/ :

Quoted 10 lines

Askar Safin requires swap and hibernation on the dm-integrity device mapper target because he needs to protect his data.

This hits two problems:
1. The kernel doesn't send the flush bio to the hibernation device after writing the image and before powering off - this is easy to fix
2. The dm-integrity target keeps parts of the device in-memory - it keeps a journal and a dm-bufio cache in memory. If we hibernate and resume, the content of memory no longer matches the data on the hibernate partition and that may cause spurious errors - this is hard to fix

Let me add some more info on this patchset.

First of all, I already solved the problem for me personally:
I wrote hackish patch, which fixes the problem. My patch is tested on my real hardware under load. I successfully use it for 2 weeks (I hibernated a lot of times during this period.)
The patch is absolutely rock solid, and I absolutely sure it is correct. Unfortunately, it is not generic, it is tied to my particular configuration, it hard codes paths (!!!), and hence is non-upstreamable.

Here is this patch for your information:
https://zerobin.net/?ad6142bd67df015a#68Az6yBUxHA3AXB7jY1+clSRnR745olFHAByxwPGM08= .

Feel free to use code from it.

So I personally is not in hurry, I already have solution, which works for me. (But I am still available for testing.)

Your patch has a problem: after "notify_swap_device" call, the pages can still be swapped out. "pm_restrict_gfp_mask" call in "hibernation_snapshot" prevents further swapping. Thus "notify_swap_device" should be called after "pm_restrict_gfp_mask" (but read on).

I attempted to create test case, which would expose this problem. And I was unable to do so. Still I believe this is a real problem.

Also, our problem is very similar to reason of introducing "filesystems_freeze" ( https://elixir.bootlin.com/linux/v6.18-rc7/source/kernel/power/hibernate.c#L824 ).

See problem description here:
https://lore.kernel.org/all/0a76e074ef262ca857c61175dd3d0dc06b67ec42.camel@HansenPartnership.com/ .

See also https://lwn.net/Articles/1018341/ .

(See also this huge thread
https://lore.kernel.org/all/[email protected]/ .)

"filesystems_freeze" logic is already implemented in mainline. It is gated behind /sys/power/freeze_filesystems .

As you can see, authors of "filesystems_freeze" attempted to solve similar problem. Thus, we should probably flush buffers in "filesystems_freeze" call. Ideally, flushing of dm-integrity should be correctly ordered with freezing of filesystems to support complex storage hierarchies (i. e. swap on dm-integrity on loop device on some filesystem, etc).

But... call to "filesystems_freeze" happens before "pm_restrict_gfp_mask" call.

So... in this point I gave up, and I don't know what to do (i. e. what the upstream kernel should do).

Feel free to ask any questions.

I changed CCs for further exposure.

Signature · 1 line
Askar Safin
#18 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

In reply to Mikulas Patocka

Mikulas Patocka <[email protected]>:

Quoted 2 lines

Askar Safin requires swap and hibernation on the dm-integrity device mapper target because he needs to protect his data.

Hi, Mikulas, Milan and others.

I'm running swap on dm-integrity for 40 days.

It runs mostly without problems.

But yesterday my screen freezed for 4 minutes. And then continued to work normally.

So, may I ask again a question: is swap on dm-integrity supposed to work at all? (I. e. swap partition on top of dm-integrity partition on top of actual disk partition.) (I'm talking about swap here, not about hibernation.)

Mikulas Patocka said here https://lore.kernel.org/all/[email protected]/ :

Quoted 9 lines

Encrypted swap file is not supposed to work. It uses the loop device that routes the requests to a filesystem and the filesystem needs to allocate memory to process requests.

So, this is what happened to you - the machine runs out of memory, it needs to swap out some pages, dm-crypt encrypts the pages and generates write bios, the write bios are directed to the loop device, the loop device directs them to the filesystem, the filesystem attempts to allocate more memory => deadlock.

Does the same apply to dm-integrity?

I. e. is it possible that write to dm-integrity will lead to allocation?

Signature · 1 line
Askar Safin
#19 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

Quoted 8 lines · Askar Safin

Mikulas Patocka <[email protected]>:

Quoted 2 lines

Askar Safin requires swap and hibernation on the dm-integrity device mapper target because he needs to protect his data.

Hi, Mikulas, Milan and others.

I'm running swap on dm-integrity for 40 days.

Quoted 8 lines

It runs mostly without problems.

But yesterday my screen freezed for 4 minutes. And then continued to work normally.

So, may I ask again a question: is swap on dm-integrity supposed to work at all? (I. e. swap partition on top of dm-integrity partition on top of actual disk partition.) (I'm talking about swap here, not about hibernation.)

Hi,

I am not sure if Mikulas is available; maybe it's better to try again in January...

Anyway, my understanding is that all device-mapper targets use mempools, which should ensure that they can process even under memory pressure.

AFAIK, swap over a device-mapper target (any target!) with a real block device should be ok. The problematic part is stacking over a filesystem (through a loop) as Mikulas mentioned.

If I interpret Mikulas' answer correctly, it is the filesystem that could allocate memory here, and it deadlocks because of it (as it is swap itself). So I believe it can happen with other DM targets too.
(If I am mistaken, please correct me.)

I wish it could work, but I do not understand kernel details anymore here. It seems we are still in "a little walled gardens" communication issues among various kernel subsystems, as one of the former maintainers said :-)

But you asked about a real block device, so it should work. I guess it is just another bug you see...

Milan

Quoted 17 lines

Mikulas Patocka said here https://lore.kernel.org/all/[email protected]/ :

Quoted 9 lines

Encrypted swap file is not supposed to work. It uses the loop device that routes the requests to a filesystem and the filesystem needs to allocate memory to process requests.

So, this is what happened to you - the machine runs out of memory, it needs to swap out some pages, dm-crypt encrypts the pages and generates write bios, the write bios are directed to the loop device, the loop device directs them to the filesystem, the filesystem attempts to allocate more memory => deadlock.

Does the same apply to dm-integrity?

I. e. is it possible that write to dm-integrity will lead to allocation?

#20 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

Milan Broz <[email protected]>:

Quoted 2 lines

Anyway, my understanding is that all device-mapper targets use mempools, which should ensure that they can process even under memory pressure.

Let me give you more details.

Here is output of "free -h":

               total        used        free      shared  buff/cache   available
Mem:            62Gi        47Gi       924Mi       2.4Gi        17Gi        14Gi
Swap:          378Gi        95Gi       282Gi

Swap is located on dm-integrity on real partition.

As you can see, my data does not fit into physical memory, so swap is required here.

But swap is big, so in theory allocations should always work.

I have a lot of Chromium windows opened (nearly 200).

My laptop is Dell Precision 7780. It is high speced expensive laptop. I have 64 GiB ECC physical memory, btrfs raid on two 3.5 TiB partitions. Everything is located on two 4 TiB NVMe SSD physical disks.

Sometimes whole system freezes for several minutes when I open new memory-hungry Chromium tabs. In such cases I see in logs:

https://zerobin.net/?383b5c32b958aca8#yXmgYidkC8pUFixwQKB+v+O3bkbis4RHduz3gji4DxI=

Notice that all backtraces contain shmem_swapin_folio, so swap is involved here.

Hibernation works thanks to my patch
https://zerobin.net/?ad6142bd67df015a#68Az6yBUxHA3AXB7jY1+clSRnR745olFHAByxwPGM08= .

My kernel is 6.12.48 from Debian with my local patches.

Sometimes I see messages "page allocation failure" in my logs. This is very
strange: I already explained above, that there is a plenty of space in swap.

Here is output of "journalctl | grep -B 10 -A 100 'page allocation failure'":

https://zerobin.net/?4170949dd9a8b25c#p5Z73TfGgpem4O4UsiWllrMCLCoHzDEw+KwJ7n8LWPA=

Maybe my swap is fragmented?

I that logs I notice that:
- Allocation failures often happen immidiately after wake up from hibernation or suspend
- We try to alloc page of order 4 (what this means? 2^4 pages?)
- GFP mask is "GFP_KERNEL|__GFP_COMP" or "GFP_NOIO|__GFP_COMP". Failure to allocate in "GFP_NOIO|__GFP_COMP" case is somewhat understandable. But what about "GFP_KERNEL|__GFP_COMP"? As well as I understand, we are allowed to do I/O, so we can drop everything to swap. And swap is big. So why we fail?
- In all backtraces "dell_smbios_call" is involved

Hibernation always works, but takes a lot of time. Usually several minutes. When hibernating, I see in logs this:

Dec 20 10:02:18 comp kernel: PM: hibernation: Allocated 26015132 kbytes in 193.21 seconds (134.64 MB/s)

I. e. 3 minutes to allocate space in memory for hibernation image.

And sometimes even this:

Dec 11 08:34:26 comp kernel: PM: hibernation: Allocated 25942484 kbytes in 348.90 seconds (74.35 MB/s)

Also sometimes I notice that in browser background for one site is replaced with black rectangle. So, I assume that browser failed to allocate something, too, but I unable to find this in logs.

Quoted 2 lines

Anyway, my understanding is that all device-mapper targets use mempools, which should ensure that they can process even under memory pressure.

This seems to be not true. I see a lot of words "alloc" in dm-integrity code:

$ grep alloc drivers/md/dm-integrity.c

And it seems that allocation happens not only in initialization, but also in normal operations (but I didn't looked at code carefully).

Also, I see a lot of mentions of bufio in dm-integrity code.
As well as I understand, this is some cache layer. But, as well as I understand, in my case there should no be any caches, everything should be written directly to partition.

So, how to debug this next?

Maybe there are some ioctls, etc, to avoid this problems or to enable more verbose logging?

I even okay with inserting some printfs to kernel code, just send me patch.

Signature · 1 line
Askar Safin
#21 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

In reply to Milan Broz

Milan Broz <[email protected]>:

Quoted 2 lines

Anyway, my understanding is that all device-mapper targets use mempools, which should ensure that they can process even under memory pressure.

Also, I don't understand how mempools help here.

As well as I understand, allocation from mempool is still real allocation if mempool's own reserve is over.

Signature · 1 line
Askar Safin
#22 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

In reply to Milan Broz

Milan Broz <[email protected]>:

Quoted 2 lines

Anyway, my understanding is that all device-mapper targets use mempools, which should ensure that they can process even under memory pressure.

I used journal mode so far, but, as well as I understand, direct mode is okay for my use case.

Okay, I spent some time carefully reading dm-integrity source code.

I have read v6.12.48, because this is kernel I use.

And I conclude that dm-integrity code never allocate (not even from mempool)... ...in main code paths (as opposed to initialization code paths)... ...in direct ('D') mode...
...if I/O doesn't fail and checksums match.

(As I said in previous letter, mempools are bad, too, as well as I understand.)

I found exactly one place, where we seem to allocate in main code path:
https://elixir.bootlin.com/linux/v6.12.48/source/drivers/md/dm-integrity.c#L1789
(i. e. these two kmalloc's).

But I think this okay, because:
- we pass GFP_NOIO, so, as well as I understand, this should not lead to recursion
- we pass __GFP_NORETRY, so, as well as I understand, we will not block in this kmalloc for too much time
- we gracefully handle possible failure

Other strange place I found is this:
https://elixir.bootlin.com/linux/v6.12.48/source/drivers/md/dm-integrity.c#L1704 .

But I think this is okay, because:
- integrity_recheck is only ever called from here:
https://elixir.bootlin.com/linux/v6.12.48/source/drivers/md/dm-integrity.c#L1857
- that integrity_recheck call is only ever happens if dm_integrity_rw_tag failed
- as well as I understand, dm_integrity_rw_tag can only fail if we got actual I/O error or checksum mismatch

So, this mempool_alloc call is okay for my use case.

So: in 'D' mode everything should be okay for my use case.

Another note: I used very stupid way to search functions, which allocate:
if function has "alloc" in its name, then I consider it allocating. :)

And final note: there is an elephant in a room: bufio.

As well as I understand, when pages are swapped in my use case, they first will get to dm-integrity bufio cache, and only after that, they will actually hit disk.

This, of course, defeats whole purpose of swap.

And possibly can lead to deadlocks.

Is there a way to disable bufio?

Or maybe bufio is used for checksums and metadata only?

Signature · 1 line
Askar Safin
#23 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

In reply to Milan Broz

Milan Broz <[email protected]>:

Quoted 2 lines

Anyway, my understanding is that all device-mapper targets use mempools, which should ensure that they can process even under memory pressure.

Okay, I just read some more code and docs.

dm-integrity fortunately uses bufio for checksums only.

And bufio allocates memory without __GFP_IO (thus allocation should not lead to recursion). And bufio claims that "dm-bufio is resistant to allocation failures":
https://elixir.bootlin.com/linux/v6.19-rc2/source/drivers/md/dm-bufio.c#L1603 .

This still seems to be fragile.

So I will change mode to 'D' and hope for the best. :)

Signature · 1 line
Askar Safin
#24 lore raw

Re: [RFC PATCH 2/2] swsusp: make it possible to hibernate to device mapper devices

In reply to Mikulas Patocka

Mikulas Patocka <[email protected]>:

Quoted 2 lines

Askar Safin requires swap and hibernation on the dm-integrity device mapper target because he needs to protect his data.

Now I see that your approach is valid. (But some small changes are needed.)

[[ TL;DR: you approach is good. I kindly ask you to continue with this patch. Needed changes are in section "Needed changes". ]]

Let me explain why I initially rejected your patch and why now I think it is good.

= Why I rejected =

In your patch "notify_swap_device" call located before "pm_restrict_gfp_mask".

But "pm_restrict_gfp_mask" is call, which forbids further swapping. I. e. we still can swap till "pm_restrict_gfp_mask" call!

Thus "notify_swap_device" should be moved after "pm_restrict_gfp_mask" call.

But then I thought about more complex storage hierarchies. For example, swap on top of some dm device on top of loop device on top of some filesystem on top of some another dm device, etc.

If we have such hierarchy, then hibernating dm devices should be intertwined with freezing of filesystems, which happens in "filesystems_freeze" call.

But "filesystems_freeze" call located before "pm_restrict_gfp_mask" call, so here we got contradiction.

In other words, we should satisfy this 3 things at the same time:

- Hibernating of dm devices should happen inside "filesystems_freeze" call intermixed with freezing of filesystems
- Hibernating of dm devices should happen after "pm_restrict_gfp_mask" call
- "pm_restrict_gfp_mask" is located after "filesystems_freeze" call in current kernel

These 3 points obviously contradict to each other.

So in this point I gave up.

The only remaining solution (as I thought at that time) was to move "filesystems_freeze" after "pm_restrict_gfp_mask" call (or to move "pm_restrict_gfp_mask" before "filesystems_freeze").

But:
- Freezing of filesystem might require memory. It is bad idea to call "filesystems_freeze" after we forbid to swap
- This would be pretty big change to the kernel. I'm not sure that my small use case justifies such change

So in this point I totally gave up.

= Why now I think your patch is good =

But then I found this your email:
https://lore.kernel.org/all/[email protected]/ .

And now I see that complex hierarchies, such as described above, are not supported anyway!

This fully ruins my argument above.

And this means that your patch in fact works!

= Needed changes =

Please, move "notify_swap_device" after "pm_restrict_gfp_mask".

Also: you introduced new operation to target_type: hibernate. I'm not sure we need this operation, we already have presuspend and postsuspend. In my personal hacky patch I simply added "dm_bufio_client_reset" to the end of "dm_integrity_postsuspend", and it worked. But I'm not sure about this point, i. e. if you think that we need "hibernate", then go with it.

Signature · 1 line
Askar Safin
#25 lore raw

Re: [PATCH] pm-hibernate: flush block device cache when hibernating

In reply to Mikulas Patocka
Quoted 21 lines · Mikulas Patocka
Quoted 6 lines · Askar Safin

Hi.

Hibernate to swap located on dm-integrity doesn't work.
Let me first describe why I need this, then I will describe a bug with steps to reproduce
(and some speculation on cause of the bug).

Hi

Does this patch fix it?

Mikulas

From: Mikulas Patocka <[email protected]>

Quoted 7 lines

There was reported failure that hibernation doesn't work with dm-integrity. The reason for the failure is that the hibernation code doesn't issue the FLUSH bio - the data still sits in the dm-integrity cache and they are lost when poweroff happens.

This commit fixes the suspend code so that it issues flushes before writing the header and after writing the header.

Hmm, shouldn't it flush every time it does a sync write, and not just in these two cases?

Quoted 27 lines
---
 kernel/power/swap.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

Index: linux-2.6/kernel/power/swap.c
===================================================================

kernel/power/swap.c 2025-10-24 12:01:32.000000000 +0200 renamed from kernel/power/swap.c 2025-10-13 21:42:48.000000000 +0200 +3 -1
@@ -320,8 +320,10 @@ static int mark_swapfiles(struct swap_ma
                swsusp_header->flags = flags;
                if (flags & SF_CRC32_MODE)
                        swsusp_header->crc32 = handle->crc32;
-               error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC,
+               error = hib_submit_io_sync(REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH,
                                      swsusp_resume_block, swsusp_header);
+               if (!error)
+                       error = blkdev_issue_flush(file_bdev(hib_resume_bdev_file));
        } else {
                pr_err("Swap header not found!\n");
                error = -ENODEV;
#26 lore raw

Re: [PATCH] pm-hibernate: flush block device cache when hibernating

Quoted 5 lines · Rafael J. Wysocki
Quoted 2 lines

This commit fixes the suspend code so that it issues flushes before writing the header and after writing the header.

Hmm, shouldn't it flush every time it does a sync write, and not just in these two cases?

It certainly should not use the PREFLUSH flag that flushes before writing, as the cache will be dirty again after that.

I'd expect a single blkdev_issue_flush after all writing is done, under the assumption that the swsusp swap writing doesn't have transaction integrity for individual writes anyway.

maintainer
#27 lore raw

Re: [PATCH] pm-hibernate: flush block device cache when hibernating

Quoted 7 lines · Christoph Hellwig
Quoted 5 lines · Rafael J. Wysocki
Quoted 2 lines

This commit fixes the suspend code so that it issues flushes before writing the header and after writing the header.

Hmm, shouldn't it flush every time it does a sync write, and not just in these two cases?

Quoted 6 lines

It certainly should not use the PREFLUSH flag that flushes before writing, as the cache will be dirty again after that.

I'd expect a single blkdev_issue_flush after all writing is done, under the assumption that the swsusp swap writing doesn't have transaction integrity for individual writes anyway.

I think that we should use two flushes - one before writing the header and the other after writing the header. Otherwise, it could be possible that the header is written and some of the data is not written, if the system loses power during hibernation.

Mikulas