[RFC PATCH 3/6] PM: hibernate: add compress-on-copy snapshot pool

From: Nhat-Trieu Huynh-Pham

Date: Sat Nov 28 2026 - 14:32:04 EST


Hibernation preallocates one uncompressed copy page for every page in the
image. That 1:1 copy is the reason the save path needs about half of RAM
to be free: the original pages and their copies must coexist during the
atomic copy. On resume the boot kernel is small and prepare_image() writes
image pages directly to their original page frames, so the same copy is not
needed there. A memory-constrained system can therefore fail to save an
image that would easily fit on swap once compressed.

Add a compress-on-copy pool under CONFIG_HIBERNATION_COMPRESS_ON_COPY (for
non-HIGHMEM systems). The pool pages are the image pages already marked in
copy_bm; no pointer array and no second pool allocator are introduced.
copy_data_pages() stages 32-page chunks, detects zero pages as before,
compresses the remaining pages with the hibernation codec and appends
compact length-prefixed records to the pool. After create_image() returns
to process context, snapshot_cocopy_finish() reports any pool exhaustion
diagnostic and returns unused tail pages to the allocator before the image
is written.

The pool is entered after the stock 1:1 allocation comes up short. The
pages that allocation did obtain are kept, and if needed the fallback fills
the pool up to the usable-free budget before activation; excess pages above
that budget are trimmed before tasks are frozen. The whole compressed
image must fit in the pool, otherwise hibernation fails with -ENOMEM before
anything is written.

snapshot_read_next() decompresses records into its direct-map reader
buffer for the existing image writers, keeping the on-disk format, the
resume path and the CRC layout unchanged.

Compression runs in copy_data_pages() with interrupts disabled and
secondary CPUs off, so its cost must fit the platform watchdog budget.
The feature is disabled at runtime by default and can be enabled with
hibernate=compress_on_copy.

Signed-off-by: Nhat-Trieu Huynh-Pham <trieu2.huynh@xxxxxxx>
---
.../admin-guide/kernel-parameters.txt | 7 +
Documentation/power/swsusp.rst | 42 ++
kernel/power/Kconfig | 18 +
kernel/power/hibernate.c | 10 +-
kernel/power/power.h | 20 +
kernel/power/snapshot.c | 663 +++++++++++++++++-
6 files changed, 752 insertions(+), 8 deletions(-)

diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index 0e317ce98971..d06449d593c4 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -1992,6 +1992,13 @@ Kernel parameters
noresume Don't check if there's a hibernation image
present during boot.
nocompress Don't compress/decompress hibernation images.
+ compress_on_copy
+ [CONFIG_HIBERNATION_COMPRESS_ON_COPY]
+ Use a pool of compressed image pages when the
+ stock 1:1 copy-page allocation fails. The pool
+ keeps the pages already allocated for the stock
+ copy and fills up to the usable free budget; the
+ whole compressed image must fit in it.
no Disable hibernation and resume.
protect_image Turn on image protection during restoration
(that will set all pages holding image data
diff --git a/Documentation/power/swsusp.rst b/Documentation/power/swsusp.rst
index 8524f079e05c..b6fcf0448f68 100644
--- a/Documentation/power/swsusp.rst
+++ b/Documentation/power/swsusp.rst
@@ -65,6 +65,48 @@ If you want to limit the suspend image size to N bytes, do::

before suspend (it is limited to around 2/5 of available RAM by default).

+Compress-on-copy
+----------------
+
+Hibernation normally preallocates one uncompressed copy page for every page
+in the image. That 1:1 copy is what requires about half of RAM to be free at
+suspend time. The resume kernel boots with little memory in use and
+``prepare_image()`` writes image pages directly to their original page
+frames, so the same copy is not needed on resume.
+
+Compress-on-copy replaces the save-side 1:1 copy with a pool of image pages
+that holds 32-page chunks compressed with the hibernation codec. The pool is
+taken from the copy pages already marked in ``copy_bm``; no pointer array and
+no separate pool allocator are used. ``copy_data_pages()`` compresses each
+chunk while creating the image and ``snapshot_read_next()`` decompresses it
+for the writer. The on-disk image, the resume path and the CRC layout are
+unchanged.
+
+Enable it with ``hibernate=compress_on_copy``. With ``on``, the stock
+copy-page allocation is tried first. If it completes, the stock image is
+used. If it fails, the pages it allocated are kept and the fallback fills
+the pool up to the usable free budget before activating it. That budget
+includes the pages already allocated in the pool; any pool pages above it are
+returned to the allocator before tasks are frozen. The I/O reserve,
+reserved_size and the zone watermarks therefore stay free for the freeze
+callbacks. If no pool page can be obtained, hibernation fails. The whole
+compressed image must fit in the pool; otherwise it fails with ``-ENOMEM``
+before anything is written. The pool is not a streaming writer.
+
+The staging area (about 332 KiB) is reserved before the stock allocation so
+the fallback does not have to vmalloc it after the stock allocation has
+consumed the free pages. It is released when the stock path is kept.
+
+The 2/5 default ``image_size`` and the ``max_size`` calculation are
+unchanged; they still determine the stock 1:1 copy target.
+Compress-on-copy only changes what happens when that target cannot be
+met. The pool pages and the
+original pages still coexist during the atomic copy, and compression runs
+with interrupts disabled, so the codec cost must fit the platform watchdog
+budget. Requires ``CONFIG_HIBERNATION_COMPRESS_ON_COPY`` (not available on
+HIGHMEM kernels). With ``hibernate=nocompress`` the pool is decompressed by
+the stock raw writer.
+
- The resume process checks for the presence of the resume device,
if found, it then checks the contents for the hibernation image signature.
If both are found, it resumes the hibernation image.
diff --git a/kernel/power/Kconfig b/kernel/power/Kconfig
index 71165e7f04f4..aa42b0ffd23b 100644
--- a/kernel/power/Kconfig
+++ b/kernel/power/Kconfig
@@ -93,6 +93,24 @@ config HIBERNATION_SNAPSHOT_DEV

If in doubt, say Y.

+config HIBERNATION_COMPRESS_ON_COPY
+ bool "Compress-on-copy hibernation snapshot pool"
+ depends on HIBERNATION && !HIGHMEM
+ select LZO_COMPRESS
+ select LZO_DECOMPRESS
+ select LZ4_COMPRESS
+ select LZ4_DECOMPRESS
+ default n
+ help
+ Replace the save-side 1:1 copy-page preallocation with a pool of
+ compressed image chunks when free memory is too tight for a full
+ uncompressed copy. The on-disk image format and resume path are
+ unchanged.
+
+ Enable at runtime via hibernate=compress_on_copy.
+
+ If unsure, say N.
+
choice
prompt "Default compressor"
default HIBERNATION_COMP_LZO
diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c
index 535509804f57..bf0e93016477 100644
--- a/kernel/power/hibernate.c
+++ b/kernel/power/hibernate.c
@@ -464,8 +464,13 @@ int hibernation_snapshot(int platform_mode)
*/

/* We may need to release the preallocated image pages here. */
- if (error || !in_suspend)
+ if (error || !in_suspend) {
+ if (error)
+ snapshot_cocopy_finish(error);
swsusp_free();
+ } else {
+ snapshot_cocopy_finish(0);
+ }

msg = in_suspend ? (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE;
dpm_resume(msg);
@@ -1432,6 +1437,9 @@ static int __init hibernate_setup(char *str)
noresume = 1;
} else if (!strncmp(str, "nocompress", 10)) {
nocompress = 1;
+ } else if (!strncmp(str, "compress_on_copy", 16)) {
+ if (snapshot_cocopy_set_enabled(true))
+ pr_warn("hibernate=compress_on_copy is not supported\n");
} else if (!strncmp(str, "no", 2)) {
noresume = 1;
nohibernate = 1;
diff --git a/kernel/power/power.h b/kernel/power/power.h
index 67b3a982950b..a361a8eaa9af 100644
--- a/kernel/power/power.h
+++ b/kernel/power/power.h
@@ -181,6 +181,26 @@ struct snapshot_handle {
extern unsigned int snapshot_additional_pages(struct zone *zone);
extern unsigned long snapshot_get_image_size(void);
extern int snapshot_read_next(struct snapshot_handle *handle);
+
+/* kernel/power/snapshot.c: compress-on-copy pool */
+#ifdef CONFIG_HIBERNATION_COMPRESS_ON_COPY
+bool snapshot_cocopy_enabled(void);
+int snapshot_cocopy_set_enabled(bool enable);
+bool snapshot_cocopy_active(void);
+void snapshot_cocopy_finish(int error);
+void snapshot_cocopy_release(void);
+#else
+static inline bool snapshot_cocopy_enabled(void) { return false; }
+
+static inline int snapshot_cocopy_set_enabled(bool enable)
+{
+ return -EOPNOTSUPP;
+}
+
+static inline bool snapshot_cocopy_active(void) { return false; }
+static inline void snapshot_cocopy_finish(int error) {}
+static inline void snapshot_cocopy_release(void) {}
+#endif
extern int snapshot_write_next(struct snapshot_handle *handle);
int snapshot_write_finalize(struct snapshot_handle *handle);
extern int snapshot_image_loaded(struct snapshot_handle *handle);
diff --git a/kernel/power/snapshot.c b/kernel/power/snapshot.c
index d06a52a7566b..92ba3706366d 100644
--- a/kernel/power/snapshot.c
+++ b/kernel/power/snapshot.c
@@ -31,6 +31,11 @@
#include <linux/compiler.h>
#include <linux/ktime.h>
#include <linux/set_memory.h>
+#ifdef CONFIG_HIBERNATION_COMPRESS_ON_COPY
+#include <linux/lzo.h>
+#include <linux/lz4.h>
+#include <linux/vmalloc.h>
+#endif

#include <linux/uaccess.h>
#include <asm/mmu_context.h>
@@ -1171,6 +1176,8 @@ void free_basic_memory_bitmaps(void)
if (WARN_ON(!(forbidden_pages_map && free_pages_map)))
return;

+ snapshot_cocopy_release();
+
bm1 = forbidden_pages_map;
bm2 = free_pages_map;
forbidden_pages_map = NULL;
@@ -1510,6 +1517,17 @@ static inline int copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
}
#endif /* CONFIG_HIGHMEM */

+#ifdef CONFIG_HIBERNATION_COMPRESS_ON_COPY
+static unsigned long cocopy_copy_data_pages(struct memory_bitmap *orig_bm,
+ struct memory_bitmap *zero_bm);
+#else
+static inline unsigned long cocopy_copy_data_pages(struct memory_bitmap *orig_bm,
+ struct memory_bitmap *zero_bm)
+{
+ return 0;
+}
+#endif
+
/*
* Copy data pages will copy all pages into pages pulled from the copy_bm.
* If a page was entirely filled with zeros it will be marked in the zero_bm.
@@ -1533,6 +1551,9 @@ static unsigned long copy_data_pages(struct memory_bitmap *copy_bm,
if (page_is_saveable(zone, pfn))
memory_bm_set_bit(orig_bm, pfn);
}
+ if (snapshot_cocopy_active())
+ return cocopy_copy_data_pages(orig_bm, zero_bm);
+
memory_bm_position_reset(orig_bm);
memory_bm_position_reset(copy_bm);
copy_pfn = memory_bm_next_pfn(copy_bm);
@@ -1581,6 +1602,488 @@ static struct memory_bitmap copy_bm;
/* Memory bitmap which tracks which saveable pages were zero filled. */
static struct memory_bitmap zero_bm;

+/*
+ * Compress-on-copy pool.
+ *
+ * The pool pages are the image pages already marked in copy_bm. They are
+ * filled in bitmap order with compact length-prefixed records, so neither a
+ * pointer array nor a second allocator is needed. copy_data_pages()
+ * compresses the saveable pages into the pool while the image is being
+ * created.
+ */
+#ifdef CONFIG_HIBERNATION_COMPRESS_ON_COPY
+enum cocopy_codec {
+ COCOPY_LZO,
+ COCOPY_LZ4,
+};
+
+union cocopy_wrkmem {
+ unsigned char lzo[LZO1X_1_MEM_COMPRESS];
+ unsigned char lz4[LZ4_MEM_COMPRESS];
+};
+
+#define COCOPY_BUF_SIZE (UNC_SIZE + CMP_SIZE + sizeof(union cocopy_wrkmem))
+
+struct cocopy_pool {
+ bool active;
+ int err;
+ unsigned int pool_pages;
+ unsigned long pool_bytes;
+ unsigned int records;
+ unsigned long write_pfn;
+ unsigned int write_off;
+ unsigned long read_pfn;
+ unsigned int read_off;
+ unsigned long read_bytes;
+ unsigned int read_chunk_pages;
+ unsigned int read_chunk_pos;
+ bool read_started;
+ enum cocopy_codec codec;
+ void *buf;
+ void *unc;
+ void *cmp;
+ void *wrkmem;
+};
+
+static bool cocopy_enabled;
+static struct cocopy_pool cocopy;
+
+bool snapshot_cocopy_enabled(void)
+{
+ return READ_ONCE(cocopy_enabled);
+}
+
+int snapshot_cocopy_set_enabled(bool enable)
+{
+ WRITE_ONCE(cocopy_enabled, enable);
+ return 0;
+}
+
+bool snapshot_cocopy_active(void)
+{
+ return READ_ONCE(cocopy.active);
+}
+
+static int cocopy_init_codec(void)
+{
+ const char *name = hib_comp_algo[0] ? hib_comp_algo :
+ CONFIG_HIBERNATION_DEF_COMP;
+
+ if (!strcmp(name, COMPRESSION_ALGO_LZO))
+ cocopy.codec = COCOPY_LZO;
+ else if (!strcmp(name, COMPRESSION_ALGO_LZ4))
+ cocopy.codec = COCOPY_LZ4;
+ else
+ return -EOPNOTSUPP;
+
+ return 0;
+}
+
+static int cocopy_compress(const void *src, unsigned int len, u32 *dst_len)
+{
+ void *dst = cocopy.cmp + CMP_HEADER;
+ unsigned int dst_size = CMP_SIZE - CMP_HEADER;
+
+ if (cocopy.codec == COCOPY_LZO) {
+ size_t out = dst_size;
+ int ret;
+
+ ret = lzo1x_1_compress_safe(src, len, dst, &out,
+ cocopy.wrkmem);
+ if (ret != LZO_E_OK)
+ return -EINVAL;
+ *dst_len = out;
+ } else {
+ int out;
+
+ out = LZ4_compress_default(src, dst, len, dst_size,
+ cocopy.wrkmem);
+ if (!out)
+ return -EINVAL;
+ *dst_len = out;
+ }
+
+ return 0;
+}
+
+static int cocopy_decompress(const void *src, unsigned int len, void *dst,
+ unsigned int *dst_len)
+{
+ if (cocopy.codec == COCOPY_LZO) {
+ size_t out = UNC_SIZE;
+ int ret;
+
+ ret = lzo1x_decompress_safe(src, len, dst, &out);
+ if (ret != LZO_E_OK)
+ return -EINVAL;
+ *dst_len = out;
+ } else {
+ int out;
+
+ out = LZ4_decompress_safe(src, dst, len, UNC_SIZE);
+ if (out < 0)
+ return -EINVAL;
+ *dst_len = out;
+ }
+
+ return 0;
+}
+
+static void cocopy_mark_pages(void *addr, unsigned long size, bool mark)
+{
+ while (size) {
+ struct page *page = vmalloc_to_page(addr);
+
+ if (page) {
+ if (mark) {
+ swsusp_set_page_forbidden(page);
+ swsusp_unset_page_free(page);
+ } else {
+ swsusp_unset_page_forbidden(page);
+ }
+ }
+ addr += PAGE_SIZE;
+ size = size > PAGE_SIZE ? size - PAGE_SIZE : 0;
+ }
+}
+
+void snapshot_cocopy_release(void)
+{
+ if (!cocopy.buf)
+ return;
+
+ cocopy_mark_pages(cocopy.buf, COCOPY_BUF_SIZE, false);
+ vfree(cocopy.buf);
+ memset(&cocopy, 0, sizeof(cocopy));
+}
+
+static int cocopy_alloc_buffers(void)
+{
+ if (cocopy.buf)
+ return 0;
+
+ if (cocopy_init_codec())
+ return -EOPNOTSUPP;
+
+ cocopy.buf = __vmalloc(COCOPY_BUF_SIZE, GFP_KERNEL | __GFP_NOWARN);
+ if (!cocopy.buf)
+ return -ENOMEM;
+
+ cocopy.unc = cocopy.buf;
+ cocopy.cmp = cocopy.buf + UNC_SIZE;
+ cocopy.wrkmem = cocopy.buf + UNC_SIZE + CMP_SIZE;
+ cocopy_mark_pages(cocopy.buf, COCOPY_BUF_SIZE, true);
+ return 0;
+}
+
+static int cocopy_activate(void)
+{
+ unsigned int pages = alloc_normal;
+ int ret;
+
+ if (cocopy.active)
+ return 0;
+ if (!pages)
+ return -ENOMEM;
+
+ ret = cocopy_alloc_buffers();
+ if (ret)
+ return ret;
+
+ cocopy.pool_pages = pages;
+ cocopy.pool_bytes = 0;
+ cocopy.records = 0;
+ cocopy.err = 0;
+ cocopy.read_started = false;
+ memory_bm_position_reset(&copy_bm);
+ cocopy.write_pfn = memory_bm_next_pfn(&copy_bm);
+ cocopy.write_off = 0;
+ cocopy.active = true;
+
+ pr_info("Compress-on-copy: pool %u pages, codec %s\n", pages,
+ cocopy.codec == COCOPY_LZO ? COMPRESSION_ALGO_LZO :
+ COMPRESSION_ALGO_LZ4);
+ return 0;
+}
+
+static int cocopy_pool_emit(const void *buf, unsigned int len)
+{
+ while (len) {
+ struct page *page;
+ unsigned int n;
+
+ if (cocopy.write_pfn == BM_END_OF_MAP)
+ return -ENOSPC;
+
+ page = pfn_to_page(cocopy.write_pfn);
+ n = min(len, PAGE_SIZE - cocopy.write_off);
+ memcpy(page_address(page) + cocopy.write_off, buf, n);
+ cocopy.write_off += n;
+ cocopy.pool_bytes += n;
+ buf += n;
+ len -= n;
+
+ if (cocopy.write_off == PAGE_SIZE) {
+ cocopy.write_off = 0;
+ cocopy.write_pfn = memory_bm_next_pfn(&copy_bm);
+ }
+ }
+ return 0;
+}
+
+static bool cocopy_stage_chunk(unsigned int nr_pages)
+{
+ unsigned long remaining;
+ size_t len;
+ u32 cmp_len;
+ int ret;
+
+ if (cocopy.err)
+ return false;
+
+ len = (size_t)nr_pages * PAGE_SIZE;
+ ret = cocopy_compress(cocopy.unc, len, &cmp_len);
+ if (ret || !cmp_len || cmp_len > bytes_worst_compress(len)) {
+ pm_deferred_pr_dbg("Compress-on-copy: compression failed\n");
+ cocopy.err = -EINVAL;
+ return false;
+ }
+
+ remaining = (unsigned long)cocopy.pool_pages * PAGE_SIZE -
+ cocopy.pool_bytes;
+ if (CMP_HEADER + cmp_len > remaining) {
+ pm_deferred_pr_dbg("Compress-on-copy: pool exhausted (%lu of %lu KiB)\n",
+ cocopy.pool_bytes >> 10,
+ (unsigned long)cocopy.pool_pages * PAGE_SIZE >> 10);
+ cocopy.err = -ENOSPC;
+ return false;
+ }
+
+ *(size_t *)cocopy.cmp = cmp_len;
+ ret = cocopy_pool_emit(cocopy.cmp, CMP_HEADER + cmp_len);
+ if (ret) {
+ cocopy.err = ret;
+ return false;
+ }
+ cocopy.records++;
+
+ /* Compression runs with interrupts disabled. */
+ touch_nmi_watchdog();
+ return true;
+}
+
+static unsigned long cocopy_copy_data_pages(struct memory_bitmap *orig_bm,
+ struct memory_bitmap *zero_bm)
+{
+ unsigned long copied_pages = 0;
+ unsigned int staged = 0;
+ unsigned long pfn;
+
+ memory_bm_position_reset(orig_bm);
+ cocopy.write_off = 0;
+ cocopy.pool_bytes = 0;
+ cocopy.records = 0;
+ cocopy.err = 0;
+ memory_bm_position_reset(&copy_bm);
+ cocopy.write_pfn = memory_bm_next_pfn(&copy_bm);
+
+ for (;;) {
+ pfn = memory_bm_next_pfn(orig_bm);
+ if (pfn == BM_END_OF_MAP)
+ break;
+
+ if (safe_copy_page((char *)cocopy.unc + staged * PAGE_SIZE,
+ pfn_to_page(pfn))) {
+ memory_bm_set_bit(zero_bm, pfn);
+ continue;
+ }
+
+ copied_pages++;
+ staged++;
+ if (staged == UNC_PAGES) {
+ if (!cocopy_stage_chunk(staged))
+ return copied_pages;
+ staged = 0;
+ }
+ }
+
+ if (staged && !cocopy_stage_chunk(staged))
+ return copied_pages;
+
+ return copied_pages;
+}
+
+static void cocopy_free_current_page(unsigned long pfn)
+{
+ struct page *page = pfn_to_page(pfn);
+
+ memory_bm_clear_current(&copy_bm);
+ swsusp_unset_page_forbidden(page);
+ swsusp_unset_page_free(page);
+ __free_page(page);
+ alloc_normal--;
+}
+
+/*
+ * Finalize the pool in process context after create_image() returns. Any
+ * exhaustion diagnostic and the return of unused tail pages run here rather
+ * than in the IRQ-disabled swsusp_save() section.
+ */
+void snapshot_cocopy_finish(int error)
+{
+ unsigned int used, capacity, kept = 0;
+ unsigned long pfn;
+
+ if (!cocopy.active)
+ return;
+
+ if (error) {
+ if (cocopy.err == -ENOSPC)
+ pr_err("Compress-on-copy: pool exhausted (%lu of %lu KiB)\n",
+ cocopy.pool_bytes >> 10,
+ (unsigned long)cocopy.pool_pages * PAGE_SIZE >> 10);
+ else if (cocopy.err)
+ pr_err("Compress-on-copy: snapshot compression failed (%d)\n",
+ cocopy.err);
+ return;
+ }
+
+ if (!in_suspend)
+ return;
+
+ capacity = cocopy.pool_pages;
+ used = DIV_ROUND_UP(cocopy.pool_bytes, PAGE_SIZE);
+ /* Records were written sequentially from the start of copy_bm. */
+ memory_bm_position_reset(&copy_bm);
+ pfn = memory_bm_next_pfn(&copy_bm);
+ while (pfn != BM_END_OF_MAP) {
+ if (kept < used)
+ kept++;
+ else
+ cocopy_free_current_page(pfn);
+ pfn = memory_bm_next_pfn(&copy_bm);
+ }
+ cocopy.pool_pages = kept;
+ drain_local_pages(NULL);
+
+ pr_info("Compress-on-copy: %u records, %u of %u pages used (%lu KiB)\n",
+ cocopy.records, cocopy.pool_pages, capacity,
+ cocopy.pool_bytes >> 10);
+}
+
+static int cocopy_pool_read(void *buf, unsigned int len)
+{
+ if (cocopy.read_bytes + len > cocopy.pool_bytes)
+ return -ENODATA;
+
+ while (len) {
+ struct page *page;
+ unsigned int n;
+
+ if (cocopy.read_pfn == BM_END_OF_MAP)
+ return -ENODATA;
+
+ page = pfn_to_page(cocopy.read_pfn);
+ n = min(len, PAGE_SIZE - cocopy.read_off);
+ memcpy(buf, page_address(page) + cocopy.read_off, n);
+ cocopy.read_off += n;
+ cocopy.read_bytes += n;
+ buf += n;
+ len -= n;
+
+ if (cocopy.read_off == PAGE_SIZE) {
+ cocopy.read_off = 0;
+ cocopy.read_pfn = memory_bm_next_pfn(&copy_bm);
+ }
+ }
+ return 0;
+}
+
+static void cocopy_read_reset(void)
+{
+ cocopy.read_started = false;
+}
+
+static void cocopy_read_start(void)
+{
+ memory_bm_position_reset(&copy_bm);
+ cocopy.read_pfn = memory_bm_next_pfn(&copy_bm);
+ cocopy.read_off = 0;
+ cocopy.read_bytes = 0;
+ cocopy.read_chunk_pages = 0;
+ cocopy.read_chunk_pos = 0;
+ cocopy.read_started = true;
+}
+
+static int cocopy_next_record(const void **record, u32 *len)
+{
+ size_t record_len;
+ u32 cmp_len;
+ int ret;
+
+ if (cocopy.read_bytes >= cocopy.pool_bytes)
+ return -ENODATA;
+
+ ret = cocopy_pool_read(&record_len, CMP_HEADER);
+ if (ret)
+ return ret;
+ if (!record_len || record_len > bytes_worst_compress(UNC_SIZE) ||
+ record_len > U32_MAX)
+ return -EINVAL;
+ cmp_len = record_len;
+
+ ret = cocopy_pool_read((char *)cocopy.cmp + CMP_HEADER, cmp_len);
+ if (ret)
+ return ret;
+
+ *(size_t *)cocopy.cmp = record_len;
+ *record = cocopy.cmp;
+ *len = cmp_len;
+ return 0;
+}
+
+static int cocopy_read_next_page(void *dst)
+{
+ const void *record;
+ unsigned int unc_len;
+ u32 len;
+ int error;
+
+ if (!cocopy.read_started)
+ cocopy_read_start();
+
+ if (cocopy.read_chunk_pos >= cocopy.read_chunk_pages) {
+ error = cocopy_next_record(&record, &len);
+ if (error)
+ return error;
+ error = cocopy_decompress(record + CMP_HEADER, len,
+ cocopy.unc, &unc_len);
+ if (error)
+ return error;
+ if (!unc_len || unc_len > UNC_SIZE ||
+ (unc_len & (PAGE_SIZE - 1)))
+ return -EINVAL;
+ cocopy.read_chunk_pages = unc_len / PAGE_SIZE;
+ cocopy.read_chunk_pos = 0;
+ }
+ copy_page(dst, (char *)cocopy.unc + cocopy.read_chunk_pos * PAGE_SIZE);
+ cocopy.read_chunk_pos++;
+ return 0;
+}
+
+static bool cocopy_has_error(void)
+{
+ return cocopy.err != 0;
+}
+#else /* !CONFIG_HIBERNATION_COMPRESS_ON_COPY */
+static inline int cocopy_alloc_buffers(void) { return 0; }
+static inline int cocopy_init_codec(void) { return -EOPNOTSUPP; }
+static inline int cocopy_activate(void) { return -EOPNOTSUPP; }
+static inline bool cocopy_has_error(void) { return false; }
+static inline void cocopy_read_reset(void) {}
+static inline int cocopy_read_next_page(void *dst) { return -EOPNOTSUPP; }
+#endif /* !CONFIG_HIBERNATION_COMPRESS_ON_COPY */
+
/**
* swsusp_free - Free pages allocated for hibernation image.
*
@@ -1631,6 +2134,14 @@ void swsusp_free(void)
alloc_normal = 0;
alloc_highmem = 0;
hibernate_restore_protection_end();
+
+ /*
+ * vfree() cannot run in the GFP_ATOMIC failure paths with interrupts
+ * disabled; free_basic_memory_bitmaps() or the next swsusp_free()
+ * releases the pool in process context.
+ */
+ if (!irqs_disabled() && !in_interrupt())
+ snapshot_cocopy_release();
}

/* Helper functions used for the shrinking of memory. */
@@ -1825,6 +2336,85 @@ static unsigned long zone_usable_free_pages(struct zone *zone)
return free - unusable;
}

+/*
+ * Free pages that a non-movable GFP_IMAGE allocation can use. Highmem and
+ * ZONE_MOVABLE are excluded, as are the pages reserved for high-order atomic
+ * allocations and free CMA pages, matching the accounting used above.
+ */
+#ifdef CONFIG_HIBERNATION_COMPRESS_ON_COPY
+static unsigned long cocopy_usable_free(void)
+{
+ struct zone *zone;
+ unsigned long free = 0;
+
+ for_each_populated_zone(zone) {
+ if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE)
+ continue;
+ free += zone_usable_free_pages(zone);
+ }
+
+ return free;
+}
+
+/*
+ * The pool can reuse the image pages already allocated in copy_bm, so the
+ * target is computed from the current free pages plus alloc_normal. The
+ * reserve is left free for the I/O path, driver freeze callbacks and zone
+ * watermarks; in particular reserved_size is honored after the stock
+ * allocation has already consumed the free pages.
+ */
+static unsigned long cocopy_pool_target(unsigned long saveable)
+{
+ unsigned long free = cocopy_usable_free() + alloc_normal;
+ unsigned long reserve;
+
+ reserve = PAGES_FOR_IO + DIV_ROUND_UP(reserved_size, PAGE_SIZE) +
+ totalreserve_pages;
+ if (free <= reserve)
+ return 0;
+
+ return min(saveable, free - reserve);
+}
+
+/*
+ * Return pool pages above @target to the allocator before freezing tasks.
+ * The compressed image size is not known yet, but keeping pages beyond the
+ * free-memory budget can starve the freeze path.
+ */
+static void cocopy_trim_pool(unsigned long target)
+{
+ unsigned long pfn;
+
+ if (alloc_normal <= target)
+ return;
+
+ memory_bm_position_reset(&copy_bm);
+ while (alloc_normal > target) {
+ pfn = memory_bm_next_pfn(&copy_bm);
+ if (pfn == BM_END_OF_MAP)
+ break;
+
+ cocopy_free_current_page(pfn);
+ }
+ drain_local_pages(NULL);
+}
+
+static unsigned int cocopy_pool_size_pages(void)
+{
+ return cocopy.pool_pages;
+}
+#else /* !CONFIG_HIBERNATION_COMPRESS_ON_COPY */
+static inline unsigned long cocopy_usable_free(void) { return 0; }
+
+static inline unsigned long cocopy_pool_target(unsigned long saveable)
+{
+ return 0;
+}
+
+static inline void cocopy_trim_pool(unsigned long target) {}
+static inline unsigned int cocopy_pool_size_pages(void) { return 0; }
+#endif /* !CONFIG_HIBERNATION_COMPRESS_ON_COPY */
+
/**
* hibernate_preallocate_memory - Preallocate memory for hibernation image.
*
@@ -1880,6 +2470,14 @@ int hibernate_preallocate_memory(void)
alloc_highmem = 0;
nr_zero_pages = 0;

+ /*
+ * Reserve the small staging area before the stock allocation can
+ * consume the free pages. This is what makes the fallback reliable;
+ * it is released with the pool when the stock path is kept.
+ */
+ if (snapshot_cocopy_enabled())
+ cocopy_alloc_buffers();
+
/* Count the number of saveable data pages. */
save_highmem = count_highmem_pages();
saveable = count_data_pages();
@@ -1946,6 +2544,11 @@ int hibernate_preallocate_memory(void)
*/
shrink_all_memory(saveable - size);

+ if (snapshot_cocopy_enabled())
+ pr_info("Compress-on-copy: prealloc start free %lu, stock target %lu, saveable %lu, max %lu\n",
+ cocopy_usable_free(), count - max_size, saveable,
+ max_size);
+
/*
* The number of saveable pages in memory was too high, so apply some
* pressure to decrease it. First, make room for the largest possible
@@ -1966,8 +2569,33 @@ int hibernate_preallocate_memory(void)
pages += pages_highmem;
pages_highmem = preallocate_image_highmem(alloc);
if (pages_highmem < alloc) {
+ unsigned long short_pages = alloc - pages_highmem;
+
+ if (snapshot_cocopy_enabled() && !cocopy_init_codec()) {
+ unsigned long target = cocopy_pool_target(saveable);
+
+ /*
+ * Stock may have allocated nothing at all.
+ * Fill the pool up to the target; if it kept
+ * more than the free-memory budget allows, trim
+ * the tail before freezing tasks.
+ */
+ if (target > alloc_normal)
+ preallocate_image_pages(target - alloc_normal,
+ GFP_IMAGE);
+ if (target < alloc_normal)
+ cocopy_trim_pool(target);
+ pages = alloc_normal;
+
+ if (alloc_normal && !cocopy_activate()) {
+ pr_info("Compress-on-copy: stock short by %lu pages, fallback %u pages, target %lu, free %lu\n",
+ short_pages, alloc_normal, target,
+ cocopy_usable_free());
+ goto out;
+ }
+ }
pr_err("Image allocation is %lu pages short\n",
- alloc - pages_highmem);
+ short_pages);
goto err_out;
}
pages += pages_highmem;
@@ -1999,6 +2627,13 @@ int hibernate_preallocate_memory(void)
pages -= free_unnecessary_pages();

out:
+ if (snapshot_cocopy_enabled()) {
+ pr_info("Compress-on-copy: prealloc done free %lu, alloc_normal %u, pool %u, active %d\n",
+ cocopy_usable_free(), alloc_normal,
+ cocopy_pool_size_pages(), snapshot_cocopy_active());
+ if (!snapshot_cocopy_active())
+ snapshot_cocopy_release();
+ }
stop = ktime_get();
pr_info("Allocated %lu pages for snapshot\n", pages);
swsusp_show_speed(start, stop, pages, "Allocated");
@@ -2006,6 +2641,9 @@ int hibernate_preallocate_memory(void)
return 0;

err_out:
+ if (snapshot_cocopy_enabled())
+ pr_err("Compress-on-copy: prealloc failed free %lu, alloc_normal %u, pages %lu\n",
+ cocopy_usable_free(), alloc_normal, pages);
swsusp_free();
return -ENOMEM;
}
@@ -2146,13 +2784,15 @@ asmlinkage __visible int swsusp_save(void)
nr_highmem = count_highmem_pages();
pm_deferred_pr_dbg("Need to copy %u pages\n", nr_pages + nr_highmem);

- if (!enough_free_mem(nr_pages, nr_highmem)) {
- pm_deferred_pr_dbg("Not enough free memory for image creation\n");
- return -ENOMEM;
- }
+ if (!snapshot_cocopy_active()) {
+ if (!enough_free_mem(nr_pages, nr_highmem)) {
+ pm_deferred_pr_dbg("Not enough free memory for image creation\n");
+ return -ENOMEM;
+ }

- if (swsusp_alloc(&copy_bm, nr_pages, nr_highmem))
- return -ENOMEM;
+ if (swsusp_alloc(&copy_bm, nr_pages, nr_highmem))
+ return -ENOMEM;
+ }

/*
* During allocating of suspend pagedir, new cold pages may appear.
@@ -2160,6 +2800,8 @@ asmlinkage __visible int swsusp_save(void)
*/
drain_local_pages(NULL);
nr_copy_pages = copy_data_pages(&copy_bm, &orig_bm, &zero_bm);
+ if (snapshot_cocopy_active() && cocopy_has_error())
+ return -ENOMEM;

/*
* End of critical section. From now on, we can write to memory,
@@ -2281,9 +2923,16 @@ int snapshot_read_next(struct snapshot_handle *handle)
handle->buffer = buffer;
memory_bm_position_reset(&orig_bm);
memory_bm_position_reset(&copy_bm);
+ cocopy_read_reset();
} else if (handle->cur <= nr_meta_pages) {
clear_page(buffer);
pack_pfns(buffer, &orig_bm, &zero_bm);
+ } else if (snapshot_cocopy_active()) {
+ int error = cocopy_read_next_page(buffer);
+
+ if (error)
+ return error;
+ handle->buffer = buffer;
} else {
struct page *page;

--
2.43.0