All of lore.kernel.org
 help / color / mirror / Atom feed
* [RFC PATCH v5 0/4] zram/zsmalloc: multi-page compression for large folios
@ 2026-12-05  2:17 Nanzhe Zhao
  2026-12-05  2:18 ` [PATCH 1/4] mm: zsmalloc: support objects compressed based on multiple pages Nanzhe Zhao
                   ` (3 more replies)
  0 siblings, 4 replies; 8+ messages in thread
From: Nanzhe Zhao @ 2026-12-05  2:17 UTC (permalink / raw)
  To: Andrew Morton
  Cc: Nanzhe Zhao, linux-mm, linux-block, linux-kernel, Jens Axboe,
	Sergey Senozhatsky, Minchan Kim, Kairui Song, Johannes Weiner,
	Nhat Pham, Usama Arif, Yosry Ahmed, Chengming Zhou, Chris Li,
	David Hildenbrand, Ying Huang, Suren Baghdasaryan, Ryan Roberts,
	Kanchana P Sridhar, Wajdi K Feghali, Bala Seshasayee,
	Nick Terrell, Barry Song, Tangquan Zheng, Bo Zhang

When large folios are compressed at a larger granularity, we observe
a notable reduction in CPU usage and a significant improvement in
compression ratios.

mTHP's ability to be swapped out without splitting and swapped back in
as a whole allows compression and decompression at larger granularities.

This patchset enhances zsmalloc and zram by adding support for dividing
large folios into multi-page blocks, typically configured with a
2-order granularity. Without this patchset, a large folio is always
divided into nr_pages 4KiB blocks.

The granularity can be set using the ZSMALLOC_MULTI_PAGES_ORDER
setting, where the default of 2 allows all anonymous THP to benefit.

Examples include:
* A 16KiB large folio will be compressed and stored as a single 16KiB
  block.
* A 64KiB large folio will be compressed and stored as four 16KiB
  blocks.

We captured anonymous pages from four Android applications on a Pixel 6.
To evaluate throughput, we allocate a buffer via mmap(MAP_PRIVATE |
MAP_ANONYMOUS), populate it with the captured pages, and invoke
madvise(MADV_PAGEOUT) to swap the buffer out to zram, measuring the
pageout duration. We then sequentially touch every 4 KiB page to fault
them back in from zram, measuring the swapin duration.

For example, testing the 143 MiB WeChat corpus (times in seconds;
w/o: without the patch, w/: with the patch):

Algorithm  pageout w/o (s)  pageout w/            swapin w/o (s)  swapin w/
lz4        0.247            0.210 (-14.8%)        0.137           0.113 (-17.6%)
lzo-rle    0.240            0.207 (-13.7%)        0.149           0.123 (-17.5%)
zstd       0.567            0.452 (-20.4%)        0.258           0.192 (-25.6%)

In v4 [2], we discussed and tested the two design issues left from v3:

The first issue is internal fragmentation in zsmalloc. Multi-page
compression increases the class gap between adjacent size classes,
and unused memory in partially filled zspages grows by ~1.8 to 2.4 MiB
across our tested apps. However, because the object count drops by
~74%, combined with better compression ratios, total memory
consumption actually decreases. For a synthetic extreme case
constructed to maximize class padding, memory overhead can increase
by up to 5.0% under the default chain size.

The second issue is partial read. When order-2 swapin allocation fails
under memory pressure, falling back to order-0 requires decompressing
the entire 16 KiB block for a single 4 KiB fault. Allowing direct
reclaim (__GFP_RECLAIM) for order-2 swapin eliminated over 99.9% of
partial decompressions (from 235k down to 218 in our stress test),
speeding up swapin by 8.3% without observable stall regression.

In v5, we would like to further discuss the compatibility of multi-page
compression with zram recompression and backing-device writeback.
Currently, zram recompression and backing-device writeback assume that
every slot corresponds to an independent PAGE_SIZE object. In v5, we
temporarily enforce mutual exclusion via Kconfig. We would like to
discuss the preferred architectural direction for full compatibility.

Regarding architecture support, on MIPS with D-cache aliasing,
flush_dcache_page() only flushes a single page. However, MIPS does not
support THP_SWAP, so multi-page swap-in cannot occur there. Non-swap
multi-page block I/O is left out of scope for now.

Changes since v4:
* Rebased onto akpm/mm-new (7.4-rc4).
* Patch 1 (zsmalloc):
  - Clamped the last base size class to PAGE_SIZE and offset multi-page
    classes by 1 to prevent class index collisions on 16K/64K kernels.
  - Converted obj_write() cross-page copying to kmap_local_zpdesc().
  - Updated set_first_obj_offset() assertion to check ZS_MAX_ALLOC_SIZE.
  - Added 'depends on 64BIT' to avoid handle index overflow on 32-bit LPAE.
* Patch 2 (zram):
  - Adopted the aligned head slot lock model: all slot operations (read,
    write, discard, notify) serialize on the head slot lock of the
    multi-page slots group.
  - slot_free() frees the multi-page object through the head slot, and also
    frees any single-page objects left behind on tail slots by failed
    zram_slot_free_notify trylocks to prevent leaks.
  - Fixed partial write RMW concurrency: recheck the multi-page flags under
    the head slot lock; if the multi-page slot was concurrently freed,
    return -EAGAIN to let the caller retry through the single-page path.
  - Corrected zram_bio_discard() to compute slot-relative offsets and
    re-lock the single-page slot if the multi-page slot was concurrently freed.
    Note that this series only supports swap-generated discard, which is
    issued in full swap-cluster units under CLUSTER_FLAG_DISCARD. Direct
    block-layer discard is currently not supported.
  - Enforced Kconfig mutual exclusion with ZRAM_WRITEBACK and ZRAM_MULTI_COMP.
* Patch 4 (swap):
  - Added __GFP_NORETRY to order-2 swapin direct reclaim to prevent premature
    OOM invocations on allocation failure.

[1] v3: https://lore.kernel.org/all/20241121222521.83458-1-21cnbao@gmail.com/
[2] v4: https://lore.kernel.org/all/20261115024455.1465726-1-zhaonanzhe@xiaomi.com/

Barry Song (1):
  zram: backend_zstd: use multi-page size for zstd parameter setup

Nanzhe Zhao (1):
  mm: swap: allow direct reclaim for synchronous multi-page swapin

Tangquan Zheng (2):
  mm: zsmalloc: support objects compressed based on multiple pages
  zram: support compression at the granularity of multi-pages

 Documentation/ABI/testing/sysfs-block-zram  |  13 +
 Documentation/admin-guide/blockdev/zram.rst |   3 +
 Documentation/mm/zsmalloc.rst               |  51 +-
 drivers/block/zram/Kconfig                  |  10 +
 drivers/block/zram/backend_zstd.c           |   4 +-
 drivers/block/zram/zcomp.c                  |  36 +-
 drivers/block/zram/zcomp.h                  |  18 +-
 drivers/block/zram/zram_drv.c               | 705 +++++++++++++++++---
 drivers/block/zram/zram_drv.h               |  43 ++
 include/linux/zsmalloc.h                    |  10 +-
 mm/Kconfig                                  |  41 +-
 mm/swap_state.c                             |   7 +
 mm/zsmalloc.c                               | 259 ++++---
 13 files changed, 1009 insertions(+), 191 deletions(-)

-- 
2.43.0



^ permalink raw reply	[flat|nested] 8+ messages in thread

* [PATCH 1/4] mm: zsmalloc: support objects compressed based on multiple pages
  2026-12-05  2:17 [RFC PATCH v5 0/4] zram/zsmalloc: multi-page compression for large folios Nanzhe Zhao
@ 2026-12-05  2:18 ` Nanzhe Zhao
  2026-12-06  2:20   ` sashiko-bot
  2026-12-05  2:18 ` [PATCH 2/4] zram: support compression at the granularity of multi-pages Nanzhe Zhao
                   ` (2 subsequent siblings)
  3 siblings, 1 reply; 8+ messages in thread
From: Nanzhe Zhao @ 2026-12-05  2:18 UTC (permalink / raw)
  To: Andrew Morton
  Cc: Nanzhe Zhao, linux-mm, linux-block, linux-kernel, Jens Axboe,
	Sergey Senozhatsky, Minchan Kim, Kairui Song, Johannes Weiner,
	Nhat Pham, Usama Arif, Yosry Ahmed, Chengming Zhou, Chris Li,
	David Hildenbrand, Ying Huang, Suren Baghdasaryan, Ryan Roberts,
	Kanchana P Sridhar, Wajdi K Feghali, Bala Seshasayee,
	Nick Terrell, Barry Song, Tangquan Zheng, Bo Zhang

From: Tangquan Zheng <zhengtangquan@oppo.com>

This patch introduces support for zsmalloc to store compressed objects
based on multi-pages. Previously, a large folio with nr_pages subpages
would undergo compression one by one, each at the granularity of
PAGE_SIZE. However, by compressing them at a larger granularity, we
can conserve both memory and CPU resources.

We define the granularity with a configuration option called
ZSMALLOC_MULTI_PAGES_ORDER, set to a default value of 2, which matches
the minimum order of anonymous mTHP. As a result, a large folio with
8 subpages will now be split into 2 parts instead of 8.

The introduction of the multi-pages feature necessitates the creation
of new size classes to accommodate it.

Signed-off-by: Tangquan Zheng <zhengtangquan@oppo.com>
Co-developed-by: Barry Song <baohua@kernel.org>
Signed-off-by: Barry Song <baohua@kernel.org>
Co-developed-by: Nanzhe Zhao <zhaonanzhe@xiaomi.com>
Signed-off-by: Nanzhe Zhao <zhaonanzhe@xiaomi.com>
---
 Documentation/mm/zsmalloc.rst |  51 +++++--
 drivers/block/zram/zram_drv.c |   3 +-
 include/linux/zsmalloc.h      |  10 +-
 mm/Kconfig                    |  41 +++++-
 mm/zsmalloc.c                 | 259 +++++++++++++++++++++++-----------
 5 files changed, 265 insertions(+), 99 deletions(-)

diff --git a/Documentation/mm/zsmalloc.rst b/Documentation/mm/zsmalloc.rst
index 8132cd70a61f..283d22cb8aba 100644
--- a/Documentation/mm/zsmalloc.rst
+++ b/Documentation/mm/zsmalloc.rst
@@ -16,11 +16,21 @@ pages act as a single higher-order page i.e. an object can span 0-order
 page boundaries. The code refers to these linked pages as a single entity
 called zspage.
 
-For simplicity, zsmalloc can only allocate objects of size up to PAGE_SIZE
-since this satisfies the requirements of all its current users (in the
-worst case, page is incompressible and is thus stored "as-is" i.e. in
-uncompressed form). For allocation requests larger than this size, failure
-is returned (see zs_store).
+By default, zsmalloc allocates objects of size up to PAGE_SIZE, since this
+satisfies the requirements of single-page compression (in the worst case,
+a page is incompressible and is thus stored "as-is", i.e. in uncompressed form).
+
+When CONFIG_ZSMALLOC_MULTI_PAGES is enabled, zsmalloc extends this limit up
+to ZS_MAX_ALLOC_SIZE (PAGE_SIZE << CONFIG_ZSMALLOC_MULTI_PAGES_ORDER).
+CONFIG_ZSMALLOC_MULTI_PAGES_ORDER is the configuration option that specifies
+the allocation order for multi-page objects, currently supported up to order 3
+(PAGE_ALLOC_COSTLY_ORDER). This allows callers such as zram to compress
+mTHP folios as a whole during swapout, rather than splitting them into
+individual PAGE_SIZE chunks and compressing them iteratively, improving both
+compression ratio and throughput.
+
+For allocation requests larger than ZS_MAX_ALLOC_SIZE, failure is returned
+(see zs_store).
 
 Additionally, zs_store() does not return a pointer; instead, it returns 0
 (or a negative error code) and stores the encoded location of the allocated
@@ -42,12 +52,12 @@ With CONFIG_DEBUG_FS, we could see zsmalloc internal information via
 
  # cat /sys/kernel/debug/zsmalloc/zram0/classes
 
- class  size       10%       20%       30%       40%       50%       60%       70%       80%       90%       99%      100% obj_allocated   obj_used pages_used pages_per_zspage freeable
+ class  size  order       10%       20%       30%       40%       50%       60%       70%       80%       90%       99%      100% obj_allocated   obj_used pages_used pages_per_zspage objs_per_zspage freeable
     ...
     ...
-    30   512         0        12         4         1         0         1         0         0         1         0       414          3464       3346        433                1       14
-    31   528         2         7         2         2         1         0         1         0         0         2       117          4154       3793        536                4       44
-    32   544         6         3         4         1         2         1         0         0         0         1       260          4170       3965        556                2       26
+    30   512      0         0        12         4         1         0         1         0         0         1         0       414          3464       3346        433                1               8       14
+    31   528      0         2         7         2         2         1         0         1         0         0         2       117          4154       3793        536                4              31       44
+    32   544      0         6         3         4         1         2         1         0         0         0         1       260          4170       3965        556                2              15       26
     ...
     ...
 
@@ -56,6 +66,9 @@ class
 	index
 size
 	object size zspage stores
+order
+	page order of the underlying allocation for this class (0 for
+	base classes, or CONFIG_ZSMALLOC_MULTI_PAGES_ORDER for multi-page classes)
 10%
 	the number of zspages with usage ratio less than 10% (see below)
 20%
@@ -85,7 +98,9 @@ obj_used
 pages_used
 	the number of pages allocated for the class
 pages_per_zspage
-	the number of 0-order pages to make a zspage
+	the number of pages (or higher-order allocation units) to make a zspage
+objs_per_zspage
+	the total number of objects that a single zspage of this class can hold
 freeable
 	the approximate number of pages class compaction can free
 
@@ -98,11 +113,17 @@ closer the inuse counter is to objs_per_zspage, the better.
 Internals
 =========
 
-zsmalloc has 255 size classes, each of which can hold a number of zspages.
-Each zspage can contain up to ZSMALLOC_CHAIN_SIZE physical (0-order) pages.
+zsmalloc groups objects into size classes. For single-page allocations, there
+are up to 255 base size classes (on 4KB page systems), where each zspage
+contains up to ZSMALLOC_CHAIN_SIZE physical (0-order) pages.
 The optimal zspage chain size for each size class is calculated during the
 creation of the zsmalloc pool (see calculate_zspage_chain_size()).
 
+When CONFIG_ZSMALLOC_MULTI_PAGES is enabled, an additional set of multi-page
+size classes is appended after the base classes to cover sizes up to
+ZS_MAX_ALLOC_SIZE. Each multi-page zspage consists of higher-order pages of
+order CONFIG_ZSMALLOC_MULTI_PAGES_ORDER.
+
 As an optimization, zsmalloc merges size classes that have similar
 characteristics in terms of the number of pages per zspage and the number
 of objects that each zspage can store.
@@ -161,6 +182,10 @@ per zspage. Any object larger than 3264 bytes is considered huge and belongs
 to size class #254, which stores each object in its own physical page (objects
 in huge classes do not share pages).
 
+Similarly, when CONFIG_ZSMALLOC_MULTI_PAGES is enabled, multi-page size classes
+have their own huge class watermark and huge class index, storing incompressible
+multi-page blocks across their respective higher-order pages.
+
 Increasing the size of the chain of zspages also results in a higher watermark
 for the huge size class and fewer huge classes overall. This allows for more
 efficient storage of large objects.
@@ -205,7 +230,7 @@ For zspage chain size of 16, huge class watermark becomes 3840 bytes:::
     254  4096         0   ..         0             0          0          0                1        0
   ...
 
-Overall the combined zspage chain size effect on zsmalloc pool configuration:::
+Overall the combined zspage chain size effect on zsmalloc pool configuration (for base 0-order classes):::
 
   pages per zspage   number of size classes (clusters)   huge size class watermark
          4                        69                               3264
diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c
index cadce71c2d2a..95cec8b34239 100644
--- a/drivers/block/zram/zram_drv.c
+++ b/drivers/block/zram/zram_drv.c
@@ -2070,7 +2070,8 @@ static bool zram_meta_alloc(struct zram *zram, u64 disksize)
 	}
 
 	if (!huge_class_size)
-		huge_class_size = zs_huge_class_size(zram->mem_pool);
+		huge_class_size = zs_huge_class_size(zram->mem_pool,
+						ZSMALLOC_TYPE_BASEPAGE);
 
 	lockdep_register_key(&zram->table_lock_key);
 	lockdep_init_map(&zram->table_lock_map, "zram->table[index].lock",
diff --git a/include/linux/zsmalloc.h b/include/linux/zsmalloc.h
index 8971eef333ba..738260358a9a 100644
--- a/include/linux/zsmalloc.h
+++ b/include/linux/zsmalloc.h
@@ -17,6 +17,14 @@
 #include <linux/compiler.h>
 #include <linux/types.h>
 
+enum zsmalloc_type {
+	ZSMALLOC_TYPE_BASEPAGE,
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+	ZSMALLOC_TYPE_MULTI_PAGES,
+#endif
+	ZSMALLOC_TYPE_MAX,
+};
+
 struct zs_pool_stats {
 	/* How many pages were migrated (freed) */
 	atomic_long_t pages_compacted;
@@ -55,7 +63,7 @@ void zs_free(struct zs_pool *pool, struct zs_handle *handle);
 void zs_rebind_handle(struct zs_pool *pool, struct zs_handle *dst,
 		      struct zs_handle *src);
 
-size_t zs_huge_class_size(struct zs_pool *pool);
+size_t zs_huge_class_size(struct zs_pool *pool, enum zsmalloc_type type);
 
 unsigned long zs_get_total_pages(struct zs_pool *pool);
 unsigned long zs_compact(struct zs_pool *pool);
diff --git a/mm/Kconfig b/mm/Kconfig
index 18925ccb4adc..0fb6b73c4189 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -131,14 +131,15 @@ menu "Zsmalloc allocator options"
 comment "Zsmalloc is a common backend allocator for zswap & zram"
 
 config ZSMALLOC_CHAIN_SIZE
-	int "Maximum number of physical pages per-zspage"
+	int "Maximum number of chain elements per-zspage"
 	default 8
 	range 4 16
 	help
-	  This option sets the upper limit on the number of physical pages
-	  that a zmalloc page (zspage) can consist of. The optimal zspage
-	  chain size is calculated for each size class during the
-	  initialization of the pool.
+	  This option sets the upper limit on the number of chain elements
+	  that a zsmalloc page (zspage) can consist of. Each element is a
+	  single page, or a multi-page allocation when ZSMALLOC_MULTI_PAGES
+	  is enabled. The optimal zspage chain size is calculated for each
+	  size class during the initialization of the pool.
 
 	  Changing this option can alter the characteristics of size classes,
 	  such as the number of pages per zspage and the number of objects
@@ -148,6 +149,36 @@ config ZSMALLOC_CHAIN_SIZE
 
 	  For more information, see zsmalloc documentation.
 
+config ZSMALLOC_MULTI_PAGES
+	bool "support zsmalloc multiple pages"
+	depends on ZSMALLOC && !HIGHMEM && 64BIT
+	help
+	  This option configures zsmalloc to support allocations larger than
+	  PAGE_SIZE, enabling compression across multiple pages. The size of
+	  these multiple pages is determined by the configured
+	  ZSMALLOC_MULTI_PAGES_ORDER.
+
+	  Multi-page size classes can hold more objects per zspage than the
+	  single-page ones.  On 32-bit architectures whose physical address
+	  width leaves only a few bits for the object index in the zsmalloc
+	  handle, such a class no longer fits, so this option is limited to
+	  64-bit.
+
+config ZSMALLOC_MULTI_PAGES_ORDER
+	int "zsmalloc multiple pages order"
+	default 2
+	range 1 3
+	depends on ZSMALLOC_MULTI_PAGES
+	help
+	  This option is used to configure zsmalloc to support the compression
+	  of multiple pages.  A multi-page object occupies
+	  PAGE_SIZE << ZSMALLOC_MULTI_PAGES_ORDER bytes.
+
+	  The order is capped at PAGE_ALLOC_COSTLY_ORDER (3): past that
+	  point the buddy allocator treats the allocation as costly, and the
+	  reclaim and fragmentation cost outweighs the benefit of compressing
+	  larger blocks.
+
 endmenu
 
 menu "Slab allocator options"
diff --git a/mm/zsmalloc.c b/mm/zsmalloc.c
index f263bd2b8d46..171cb787fe6b 100644
--- a/mm/zsmalloc.c
+++ b/mm/zsmalloc.c
@@ -49,6 +49,12 @@
 
 #define ZSPAGE_MAGIC	0x58
 
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+#define ZSMALLOC_MULTI_PAGES_ORDER	(_AC(CONFIG_ZSMALLOC_MULTI_PAGES_ORDER, UL))
+#define ZSMALLOC_MULTI_PAGES_NR		(1 << ZSMALLOC_MULTI_PAGES_ORDER)
+#define ZSMALLOC_MULTI_PAGES_SIZE	(PAGE_SIZE * ZSMALLOC_MULTI_PAGES_NR)
+#endif
+
 /*
  * This must be power of 2 and greater than or equal to sizeof(link_free).
  * These two conditions ensure that any 'struct link_free' itself doesn't
@@ -115,7 +121,7 @@
 
 #define HUGE_BITS	1
 #define FULLNESS_BITS	4
-#define CLASS_BITS	8
+#define CLASS_BITS	9
 #define MAGIC_VAL_BITS	8
 
 #define ZS_MAX_PAGES_PER_ZSPAGE	(_AC(CONFIG_ZSMALLOC_CHAIN_SIZE, UL))
@@ -173,7 +179,11 @@ static_assert(ZS_OBJ_IDX_BITS >= ZS_PAGES_PER_ZSPAGE_BITS,
 	      "zsmalloc: ZS_MIN_ALLOC_SIZE would exceed ZS_MAX_ALLOC_SIZE");
 
 /* each chunk includes extra space to keep handle */
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+#define ZS_MAX_ALLOC_SIZE	ZSMALLOC_MULTI_PAGES_SIZE
+#else
 #define ZS_MAX_ALLOC_SIZE	PAGE_SIZE
+#endif
 
 /*
  * On systems with 4K page size, this gives 255 size classes! There is a
@@ -188,14 +198,45 @@ static_assert(ZS_OBJ_IDX_BITS >= ZS_PAGES_PER_ZSPAGE_BITS,
  *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
  *  (reason above)
  */
-#define ZS_SIZE_CLASS_DELTA	(PAGE_SIZE >> CLASS_BITS)
+#define ZS_SIZE_CLASS_DELTA	(PAGE_SIZE >> (CLASS_BITS - 1))
 #define _ZS_MIN_ALLOC_RAW \
 	DIV_ROUND_UP(ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT, ZS_OBJ_IDX_MASK)
 #define ZS_MIN_ALLOC_SIZE \
 	MIN(ZS_MAX_ALLOC_SIZE, \
 	    MAX(32UL, ALIGN(_ZS_MIN_ALLOC_RAW, ZS_ALIGN)))
-#define ZS_SIZE_CLASSES	(DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
-				      ZS_SIZE_CLASS_DELTA) + 1)
+
+#define ZS_PAGE_SIZE_CLASSES	(DIV_ROUND_UP(PAGE_SIZE - ZS_MIN_ALLOC_SIZE, \
+					    ZS_SIZE_CLASS_DELTA) + 1)
+
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+#define ZS_MULTI_PAGES_SIZE_CLASS_DELTA	(ZSMALLOC_MULTI_PAGES_SIZE >> (CLASS_BITS - 1))
+#define ZS_MULTI_PAGES_SIZE_CLASSES	(DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - PAGE_SIZE, \
+					      ZS_MULTI_PAGES_SIZE_CLASS_DELTA))
+#define ZS_SIZE_CLASSES		(ZS_PAGE_SIZE_CLASSES + ZS_MULTI_PAGES_SIZE_CLASSES)
+#else
+#define ZS_SIZE_CLASSES		(DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
+					      ZS_SIZE_CLASS_DELTA) + 1)
+#endif
+
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+static inline unsigned int class_size_to_zs_order(unsigned long size)
+{
+	if (size > PAGE_SIZE)
+		return ZSMALLOC_MULTI_PAGES_ORDER;
+
+	return 0;
+}
+#else
+static inline unsigned int class_size_to_zs_order(unsigned long size)
+{
+	return 0;
+}
+#endif
+
+static inline unsigned long class_size_to_zs_size(unsigned long size)
+{
+	return PAGE_SIZE * (1 << class_size_to_zs_order(size));
+}
 
 /*
  * Pages are distinguished by the ratio of used memory (that is the ratio
@@ -229,7 +270,7 @@ struct zs_size_stat {
 
 static struct dentry *zs_stat_root;
 
-static size_t huge_class_size;
+static size_t huge_class_size[ZSMALLOC_TYPE_MAX];
 
 struct size_class {
 	spinlock_t lock;
@@ -240,13 +281,20 @@ struct size_class {
 	 */
 	int size;
 	int objs_per_zspage;
-	/* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
-	int pages_per_zspage;
+	/* Number of zpdescs to combine to form a 'zspage' */
+	int zpdescs_per_zspage;
 
 	unsigned int index;
 	struct zs_size_stat stats;
 };
 
+/* Number of physical pages in a zspage */
+static inline unsigned long class_pages_per_zspage(const struct size_class *class)
+{
+	return (unsigned long)class->zpdescs_per_zspage <<
+	       class_size_to_zs_order(class->size);
+}
+
 /*
  * Placed within free objects to form a singly linked list.
  * For every zspage, zspage->freeobj gives head of this list.
@@ -292,27 +340,28 @@ struct zs_pool {
 
 static inline void zpdesc_inc_zone_page_state(struct zpdesc *zpdesc)
 {
-	inc_zone_page_state(zpdesc_page(zpdesc), NR_ZSPAGES);
+	zone_stat_add_folio(zpdesc_folio(zpdesc), NR_ZSPAGES);
 }
 
 static inline void zpdesc_dec_zone_page_state(struct zpdesc *zpdesc)
 {
-	dec_zone_page_state(zpdesc_page(zpdesc), NR_ZSPAGES);
+	zone_stat_sub_folio(zpdesc_folio(zpdesc), NR_ZSPAGES);
 }
 
-static inline struct zpdesc *alloc_zpdesc(gfp_t gfp, const int nid)
+static inline struct zpdesc *alloc_zpdesc(gfp_t gfp, const int nid,
+					  unsigned int order)
 {
-	struct page *page = alloc_pages_node(nid, gfp, 0);
+	struct page *page = alloc_pages_node(nid, gfp | __GFP_COMP, order);
 
 	return page_zpdesc(page);
 }
 
-static inline void free_zpdesc(struct zpdesc *zpdesc)
+static inline void free_zpdesc(struct zpdesc *zpdesc, unsigned int order)
 {
 	struct page *page = zpdesc_page(zpdesc);
 
 	/* PageZsmalloc is sticky until the page is freed to the buddy. */
-	__free_page(page);
+	__free_pages(page, order);
 }
 
 #define ZS_PAGE_UNLOCKED	0
@@ -417,7 +466,7 @@ static void zspage_write_unlock(struct zspage *zspage)
 	spin_unlock(&zsl->lock);
 }
 
-/* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
+/* huge object: zpdescs_per_zspage == 1 && maxobj_per_zspage == 1 */
 static void SetZsHugePage(struct zspage *zspage)
 {
 	zspage->huge = 1;
@@ -498,7 +547,7 @@ static inline unsigned int get_first_obj_offset(struct zpdesc *zpdesc)
 static inline void set_first_obj_offset(struct zpdesc *zpdesc, unsigned int offset)
 {
 	/* With 24 bits available, we can support offsets into 16 MiB pages. */
-	BUILD_BUG_ON(PAGE_SIZE > SZ_16M);
+	BUILD_BUG_ON(ZS_MAX_ALLOC_SIZE > SZ_16M);
 	VM_WARN_ON_ONCE(!PageZsmalloc(zpdesc_page(zpdesc)));
 	VM_WARN_ON_ONCE(offset & ~FIRST_OBJ_PAGE_TYPE_MASK);
 	zpdesc->first_obj_offset &= ~FIRST_OBJ_PAGE_TYPE_MASK;
@@ -532,11 +581,20 @@ static int get_size_class_index(int size)
 {
 	int idx = 0;
 
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+	if (size > PAGE_SIZE + ZS_HANDLE_SIZE) {
+		idx = ZS_PAGE_SIZE_CLASSES;
+		idx += DIV_ROUND_UP(size - PAGE_SIZE,
+				    ZS_MULTI_PAGES_SIZE_CLASS_DELTA) - 1;
+		return min_t(int, ZS_SIZE_CLASSES - 1, idx);
+	}
+#endif
+
 	if (likely(size > ZS_MIN_ALLOC_SIZE))
 		idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
 				ZS_SIZE_CLASS_DELTA);
 
-	return min_t(int, ZS_SIZE_CLASSES - 1, idx);
+	return min_t(int, ZS_PAGE_SIZE_CLASSES - 1, idx);
 }
 
 static struct size_class *lookup_size_class(struct zs_pool *pool, size_t size)
@@ -587,11 +645,11 @@ static int zs_stats_size_show(struct seq_file *s, void *v)
 	unsigned long total_freeable = 0;
 	unsigned long inuse_totals[NR_FULLNESS_GROUPS] = {0, };
 
-	seq_printf(s, " %5s %5s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %13s %10s %10s %16s %8s\n",
-			"class", "size", "10%", "20%", "30%", "40%",
+	seq_printf(s, " %5s %5s %5s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %13s %10s %10s %16s %16s %8s\n",
+			"class", "size", "order", "10%", "20%", "30%", "40%",
 			"50%", "60%", "70%", "80%", "90%", "99%", "100%",
 			"obj_allocated", "obj_used", "pages_used",
-			"pages_per_zspage", "freeable");
+			"pages_per_zspage", "objs_per_zspage", "freeable");
 
 	for (i = 0; i < ZS_SIZE_CLASSES; i++) {
 
@@ -602,7 +660,8 @@ static int zs_stats_size_show(struct seq_file *s, void *v)
 
 		spin_lock(&class->lock);
 
-		seq_printf(s, " %5u %5u ", i, class->size);
+		seq_printf(s, " %5u %5u %5u ", i, class->size,
+			   class_size_to_zs_order(class->size));
 		for (fg = ZS_INUSE_RATIO_10; fg < NR_FULLNESS_GROUPS; fg++) {
 			inuse_totals[fg] += class_stat_read(class, fg);
 			seq_printf(s, "%9lu ", class_stat_read(class, fg));
@@ -615,11 +674,12 @@ static int zs_stats_size_show(struct seq_file *s, void *v)
 
 		objs_per_zspage = class->objs_per_zspage;
 		pages_used = obj_allocated / objs_per_zspage *
-				class->pages_per_zspage;
+				class_pages_per_zspage(class);
 
-		seq_printf(s, "%13lu %10lu %10lu %16d %8lu\n",
+		seq_printf(s, "%13lu %10lu %10lu %16lu %16d %8lu\n",
 			   obj_allocated, obj_used, pages_used,
-			   class->pages_per_zspage, freeable);
+			   class_pages_per_zspage(class), objs_per_zspage,
+			   freeable);
 
 		total_objs += obj_allocated;
 		total_used_objs += obj_used;
@@ -627,13 +687,13 @@ static int zs_stats_size_show(struct seq_file *s, void *v)
 		total_freeable += freeable;
 	}
 
-	seq_printf(s, "\n %5s %5s ", "Total", "");
+	seq_printf(s, "\n %5s %5s %5s ", "Total", "", "");
 
 	for (fg = ZS_INUSE_RATIO_10; fg < NR_FULLNESS_GROUPS; fg++)
 		seq_printf(s, "%9lu ", inuse_totals[fg]);
 
-	seq_printf(s, "%13lu %10lu %10lu %16s %8lu\n",
-		   total_objs, total_used_objs, total_pages, "",
+	seq_printf(s, "%13lu %10lu %10lu %16s %16s %8lu\n",
+		   total_objs, total_used_objs, total_pages, "", "",
 		   total_freeable);
 
 	return 0;
@@ -872,7 +932,7 @@ static noinline void free_page_chain(struct zpdesc *zpdesc)
 			zone = zpdesc_zone(zpdesc);
 			nr = 0;
 		}
-		nr++;
+		nr += folio_nr_pages(zpdesc_folio(zpdesc));
 
 		folio_batch_add(&fbatch, zpdesc_folio(zpdesc));
 		zpdesc = next;
@@ -926,7 +986,7 @@ static void __free_zspage(struct zs_pool *pool, struct size_class *class,
 	assert_spin_locked(&class->lock);
 	__free_zspage_lockless(zspage);
 	class_stat_sub(class, ZS_OBJS_ALLOCATED, class->objs_per_zspage);
-	atomic_long_sub(class->pages_per_zspage, &pool->pages_allocated);
+	atomic_long_sub(class_pages_per_zspage(class), &pool->pages_allocated);
 }
 
 static void free_zspage(struct zs_pool *pool, struct size_class *class,
@@ -954,6 +1014,7 @@ static void init_zspage(struct size_class *class, struct zspage *zspage)
 {
 	unsigned int freeobj = 1;
 	unsigned long off = 0;
+	unsigned long page_size = class_size_to_zs_size(class->size);
 	struct zpdesc *zpdesc = get_first_zpdesc(zspage);
 
 	while (zpdesc) {
@@ -966,7 +1027,7 @@ static void init_zspage(struct size_class *class, struct zspage *zspage)
 		vaddr = kmap_local_zpdesc(zpdesc);
 		link = (struct link_free *)vaddr + off / sizeof(*link);
 
-		while ((off += class->size) < PAGE_SIZE) {
+		while ((off += class->size) < page_size) {
 			link->next = freeobj++ << OBJ_TAG_BITS;
 			link += class->size / sizeof(*link);
 		}
@@ -988,7 +1049,7 @@ static void init_zspage(struct size_class *class, struct zspage *zspage)
 		}
 		kunmap_local(vaddr);
 		zpdesc = next_zpdesc;
-		off %= PAGE_SIZE;
+		off %= page_size;
 	}
 
 	set_freeobj(zspage, 0);
@@ -1000,7 +1061,7 @@ static void create_page_chain(struct size_class *class, struct zspage *zspage,
 	int i;
 	struct zpdesc *zpdesc;
 	struct zpdesc *prev_zpdesc = NULL;
-	int nr_zpdescs = class->pages_per_zspage;
+	int nr_zpdescs = class->zpdescs_per_zspage;
 
 	/*
 	 * Allocate individual pages and link them together as:
@@ -1017,7 +1078,7 @@ static void create_page_chain(struct size_class *class, struct zspage *zspage,
 		if (i == 0) {
 			zspage->first_zpdesc = zpdesc;
 			if (unlikely(class->objs_per_zspage == 1 &&
-					class->pages_per_zspage == 1))
+					class->zpdescs_per_zspage == 1))
 				SetZsHugePage(zspage);
 		} else {
 			prev_zpdesc->next = zpdesc;
@@ -1034,6 +1095,7 @@ static struct zspage *alloc_zspage(struct zs_pool *pool,
 				   gfp_t gfp, const int nid)
 {
 	int i;
+	unsigned int order = class_size_to_zs_order(class->size);
 	struct zpdesc *zpdescs[ZS_MAX_PAGES_PER_ZSPAGE];
 	struct zspage *zspage = cache_alloc_zspage(gfp);
 
@@ -1043,19 +1105,24 @@ static struct zspage *alloc_zspage(struct zs_pool *pool,
 	if (!IS_ENABLED(CONFIG_COMPACTION))
 		gfp &= ~__GFP_MOVABLE;
 
+	/*
+	 * Multi-page zspages are not movable, keep them out of ZONE_MOVABLE.
+	 */
+	if (order)
+		gfp &= ~__GFP_MOVABLE;
+
 	zspage->magic = ZSPAGE_MAGIC;
 	zspage->pool = pool;
 	zspage->class = class->index;
 	zspage_lock_init(zspage);
 
-	for (i = 0; i < class->pages_per_zspage; i++) {
-		struct zpdesc *zpdesc;
+	for (i = 0; i < class->zpdescs_per_zspage; i++) {
+		struct zpdesc *zpdesc = alloc_zpdesc(gfp, nid, order);
 
-		zpdesc = alloc_zpdesc(gfp, nid);
 		if (!zpdesc) {
 			while (--i >= 0) {
 				zpdesc_dec_zone_page_state(zpdescs[i]);
-				free_zpdesc(zpdescs[i]);
+				free_zpdesc(zpdescs[i], order);
 			}
 			cache_free_zspage(zspage);
 			return NULL;
@@ -1087,10 +1154,10 @@ static struct zspage *find_get_zspage(struct size_class *class)
 	return zspage;
 }
 
-static bool can_merge(struct size_class *prev, int pages_per_zspage,
+static bool can_merge(struct size_class *prev, int zpdescs_per_zspage,
 					int objs_per_zspage)
 {
-	if (prev->pages_per_zspage == pages_per_zspage &&
+	if (prev->zpdescs_per_zspage == zpdescs_per_zspage &&
 		prev->objs_per_zspage == objs_per_zspage)
 		return true;
 
@@ -1139,7 +1206,7 @@ void zs_obj_read_sg_begin(struct zs_pool *pool, const struct zs_handle *handle,
 {
 	struct zspage *zspage;
 	struct zpdesc *zpdesc;
-	unsigned long obj, off;
+	unsigned long obj, off, page_size;
 	unsigned int obj_idx;
 	struct size_class *class;
 
@@ -1154,12 +1221,13 @@ void zs_obj_read_sg_begin(struct zs_pool *pool, const struct zs_handle *handle,
 	read_unlock(&pool->lock);
 
 	class = zspage_class(pool, zspage);
-	off = offset_in_page(class->size * obj_idx);
+	page_size = class_size_to_zs_size(class->size);
+	off = (class->size * obj_idx) & (page_size - 1);
 
 	if (!ZsHugePage(zspage))
 		off += ZS_HANDLE_SIZE;
 
-	if (off + mem_len <= PAGE_SIZE) {
+	if (off + mem_len <= page_size) {
 		/* this object is contained entirely within a page */
 		sg_init_table(sg, 1);
 		sg_set_page(sg, zpdesc_page(zpdesc), mem_len, off);
@@ -1167,7 +1235,7 @@ void zs_obj_read_sg_begin(struct zs_pool *pool, const struct zs_handle *handle,
 		size_t sizes[2];
 
 		/* this object spans two pages */
-		sizes[0] = PAGE_SIZE - off;
+		sizes[0] = page_size - off;
 		sizes[1] = mem_len - sizes[0];
 
 		sg_init_table(sg, 2);
@@ -1200,16 +1268,17 @@ static void obj_write(struct size_class *class, struct zspage *zspage,
 		      unsigned long obj, const void *src, size_t size)
 {
 	struct zpdesc *zpdesc;
+	unsigned long page_size = class_size_to_zs_size(class->size);
 	unsigned long off;
 	unsigned int obj_idx;
 
 	obj_to_location(obj, &zpdesc, &obj_idx);
-	off = offset_in_page(class->size * obj_idx);
+	off = (class->size * obj_idx) & (page_size - 1);
 
 	if (!ZsHugePage(zspage))
 		off += ZS_HANDLE_SIZE;
 
-	if (off + size <= PAGE_SIZE) {
+	if (off + size <= page_size) {
 		/* this object is contained entirely within a page */
 		void *dst = kmap_local_zpdesc(zpdesc);
 
@@ -1218,13 +1287,18 @@ static void obj_write(struct size_class *class, struct zspage *zspage,
 	} else {
 		/* this object spans two pages */
 		size_t sizes[2];
+		void *dst;
 
-		sizes[0] = PAGE_SIZE - off;
+		sizes[0] = page_size - off;
 		sizes[1] = size - sizes[0];
 
-		memcpy_to_page(zpdesc_page(zpdesc), off, src, sizes[0]);
+		dst = kmap_local_zpdesc(zpdesc);
+		memcpy(dst + off, src, sizes[0]);
+		kunmap_local(dst);
 		zpdesc = get_next_zpdesc(zpdesc);
-		memcpy_to_page(zpdesc_page(zpdesc), 0, src + sizes[0], sizes[1]);
+		dst = kmap_local_zpdesc(zpdesc);
+		memcpy(dst, src + sizes[0], sizes[1]);
+		kunmap_local(dst);
 	}
 }
 
@@ -1232,6 +1306,7 @@ static void obj_write(struct size_class *class, struct zspage *zspage,
  * zs_huge_class_size() - Returns the size (in bytes) of the first huge
  *                        zsmalloc &size_class.
  * @pool: zsmalloc pool to use
+ * @type: zsmalloc type (base page or multi-page)
  *
  * The function returns the size of the first huge class - any object of equal
  * or bigger size will be stored in zspage consisting of a single physical
@@ -1241,9 +1316,9 @@ static void obj_write(struct size_class *class, struct zspage *zspage,
  *
  * Return: the size (in bytes) of the first huge zsmalloc &size_class.
  */
-size_t zs_huge_class_size(struct zs_pool *pool)
+size_t zs_huge_class_size(struct zs_pool *pool, enum zsmalloc_type type)
 {
-	return huge_class_size;
+	return huge_class_size[type];
 }
 EXPORT_SYMBOL_GPL(zs_huge_class_size);
 
@@ -1256,15 +1331,17 @@ static unsigned long obj_malloc(struct zs_pool *pool,
 	struct size_class *class;
 
 	struct zpdesc *m_zpdesc;
-	unsigned long m_offset;
+	unsigned long m_offset, page_size, page_shift;
 	void *vaddr;
 
 	class = pool->size_class[zspage->class];
 	obj = get_freeobj(zspage);
 
+	page_size = class_size_to_zs_size(class->size);
+	page_shift = PAGE_SHIFT + class_size_to_zs_order(class->size);
 	offset = obj * class->size;
-	nr_zpdesc = offset >> PAGE_SHIFT;
-	m_offset = offset_in_page(offset);
+	nr_zpdesc = offset >> page_shift;
+	m_offset = offset & (page_size - 1);
 	m_zpdesc = get_first_zpdesc(zspage);
 
 	for (i = 0; i < nr_zpdesc; i++)
@@ -1359,12 +1436,13 @@ int zs_store(struct zs_pool *pool, struct zs_handle *handle, const void *src,
 	spin_lock(&class->lock);
 	newfg = get_fullness_group(class, zspage);
 	insert_zspage(class, zspage, newfg);
-	atomic_long_add(class->pages_per_zspage, &pool->pages_allocated);
+	atomic_long_add(class_pages_per_zspage(class), &pool->pages_allocated);
 	class_stat_add(class, ZS_OBJS_ALLOCATED, class->objs_per_zspage);
 	class_stat_add(class, ZS_OBJS_INUSE, 1);
 
 	/* We completely set up zspage so mark them as movable */
-	SetZsPageMovable(pool, zspage);
+	if (class_size_to_zs_order(class->size) == 0)
+		SetZsPageMovable(pool, zspage);
 	spin_unlock(&class->lock);
 
 	return 0;
@@ -1376,13 +1454,15 @@ static void obj_free(int class_size, unsigned long obj)
 	struct link_free *link;
 	struct zspage *zspage;
 	struct zpdesc *f_zpdesc;
-	unsigned long f_offset;
+	unsigned long f_offset, page_size, page_mask;
 	unsigned int f_objidx;
 	void *vaddr;
 
 
 	obj_to_location(obj, &f_zpdesc, &f_objidx);
-	f_offset = offset_in_page(class_size * f_objidx);
+	page_size = class_size_to_zs_size(class_size);
+	page_mask = ~(page_size - 1);
+	f_offset = (class_size * f_objidx) & ~page_mask;
 	zspage = get_zspage(f_zpdesc);
 
 	vaddr = kmap_local_zpdesc(f_zpdesc);
@@ -1493,7 +1573,7 @@ void zs_free(struct zs_pool *pool, struct zs_handle *handle)
 
 	if (zspage_to_free) {
 		__free_zspage_lockless(zspage_to_free);
-		atomic_long_sub(class->pages_per_zspage, &pool->pages_allocated);
+		atomic_long_sub(class_pages_per_zspage(class), &pool->pages_allocated);
 	}
 }
 EXPORT_SYMBOL_GPL(zs_free);
@@ -1551,6 +1631,8 @@ static void zs_object_copy(struct size_class *class, unsigned long dst,
 	struct zpdesc *s_zpdesc, *d_zpdesc;
 	unsigned int s_objidx, d_objidx;
 	unsigned long s_off, d_off;
+	unsigned long page_size = class_size_to_zs_size(class->size);
+	unsigned long page_mask = ~(page_size - 1);
 	void *s_addr, *d_addr;
 	int s_size, d_size, size;
 	int written = 0;
@@ -1560,14 +1642,14 @@ static void zs_object_copy(struct size_class *class, unsigned long dst,
 	obj_to_location(src, &s_zpdesc, &s_objidx);
 	obj_to_location(dst, &d_zpdesc, &d_objidx);
 
-	s_off = offset_in_page(class->size * s_objidx);
-	d_off = offset_in_page(class->size * d_objidx);
+	s_off = (class->size * s_objidx) & ~page_mask;
+	d_off = (class->size * d_objidx) & ~page_mask;
 
-	if (s_off + class->size > PAGE_SIZE)
-		s_size = PAGE_SIZE - s_off;
+	if (s_off + class->size > page_size)
+		s_size = page_size - s_off;
 
-	if (d_off + class->size > PAGE_SIZE)
-		d_size = PAGE_SIZE - d_off;
+	if (d_off + class->size > page_size)
+		d_size = page_size - d_off;
 
 	s_addr = kmap_local_zpdesc(s_zpdesc);
 	d_addr = kmap_local_zpdesc(d_zpdesc);
@@ -1592,7 +1674,7 @@ static void zs_object_copy(struct size_class *class, unsigned long dst,
 		 * kunmap_local(d_addr). For more details see
 		 * Documentation/mm/highmem.rst.
 		 */
-		if (s_off >= PAGE_SIZE) {
+		if (s_off >= page_size) {
 			kunmap_local(d_addr);
 			kunmap_local(s_addr);
 			s_zpdesc = get_next_zpdesc(s_zpdesc);
@@ -1602,7 +1684,7 @@ static void zs_object_copy(struct size_class *class, unsigned long dst,
 			s_off = 0;
 		}
 
-		if (d_off >= PAGE_SIZE) {
+		if (d_off >= page_size) {
 			kunmap_local(d_addr);
 			d_zpdesc = get_next_zpdesc(d_zpdesc);
 			d_addr = kmap_local_zpdesc(d_zpdesc);
@@ -1626,11 +1708,12 @@ static struct zs_handle *find_alloced_obj(struct size_class *class,
 	int index = *obj_idx;
 	struct zs_handle *handle = NULL;
 	void *addr = kmap_local_zpdesc(zpdesc);
+	unsigned long page_size = class_size_to_zs_size(class->size);
 
 	offset = get_first_obj_offset(zpdesc);
 	offset += class->size * index;
 
-	while (offset < PAGE_SIZE) {
+	while (offset < page_size) {
 		handle = obj_allocated(zpdesc, addr + offset);
 		if (handle)
 			break;
@@ -2013,7 +2096,7 @@ static unsigned long zs_can_compact(struct size_class *class)
 	obj_wasted = obj_allocated - obj_used;
 	obj_wasted /= class->objs_per_zspage;
 
-	return obj_wasted * class->pages_per_zspage;
+	return obj_wasted * class_pages_per_zspage(class);
 }
 
 static unsigned long __zs_compact(struct zs_pool *pool,
@@ -2052,7 +2135,7 @@ static unsigned long __zs_compact(struct zs_pool *pool,
 		fg = putback_zspage(class, src_zspage);
 		if (fg == ZS_INUSE_RATIO_0) {
 			free_zspage(pool, class, src_zspage);
-			pages_freed += class->pages_per_zspage;
+			pages_freed += class_pages_per_zspage(class);
 		}
 		src_zspage = NULL;
 
@@ -2175,6 +2258,7 @@ static int calculate_zspage_chain_size(int class_size)
 {
 	int i, min_waste = INT_MAX;
 	int chain_size = 1;
+	unsigned long page_size = class_size_to_zs_size(class_size);
 
 	if (is_power_of_2(class_size))
 		return chain_size;
@@ -2182,7 +2266,7 @@ static int calculate_zspage_chain_size(int class_size)
 	for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
 		int waste;
 
-		waste = (i * PAGE_SIZE) % class_size;
+		waste = (i * page_size) % class_size;
 		if (waste < min_waste) {
 			min_waste = waste;
 			chain_size = i;
@@ -2226,16 +2310,33 @@ struct zs_pool *zs_create_pool(const char *name)
 	 */
 	for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
 		int size;
-		int pages_per_zspage;
+		int zpdescs_per_zspage;
 		int objs_per_zspage;
 		struct size_class *class;
 		int fullness;
+		int idx = ZSMALLOC_TYPE_BASEPAGE;
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+		int order = 0;
+#endif
 
-		size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
+		if (i < ZS_PAGE_SIZE_CLASSES)
+			size = min_t(int, ZS_MIN_ALLOC_SIZE +
+				     i * ZS_SIZE_CLASS_DELTA, PAGE_SIZE);
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+		if (i >= ZS_PAGE_SIZE_CLASSES)
+			size = PAGE_SIZE + (i - ZS_PAGE_SIZE_CLASSES + 1) *
+			       ZS_MULTI_PAGES_SIZE_CLASS_DELTA;
+#endif
 		if (size > ZS_MAX_ALLOC_SIZE)
 			size = ZS_MAX_ALLOC_SIZE;
-		pages_per_zspage = calculate_zspage_chain_size(size);
-		objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
+#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
+		order = class_size_to_zs_order(size);
+		if (order == ZSMALLOC_MULTI_PAGES_ORDER)
+			idx = ZSMALLOC_TYPE_MULTI_PAGES;
+#endif
+		zpdescs_per_zspage = calculate_zspage_chain_size(size);
+		objs_per_zspage = zpdescs_per_zspage *
+				  class_size_to_zs_size(size) / size;
 
 		/*
 		 * We iterate from biggest down to smallest classes,
@@ -2243,9 +2344,9 @@ struct zs_pool *zs_create_pool(const char *name)
 		 * class. Any object bigger than or equal to that will
 		 * endup in the huge class.
 		 */
-		if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
-				!huge_class_size) {
-			huge_class_size = size;
+		if (zpdescs_per_zspage != 1 && objs_per_zspage != 1 &&
+				!huge_class_size[idx]) {
+			huge_class_size[idx] = size;
 			/*
 			 * The object uses ZS_HANDLE_SIZE bytes to store the
 			 * handle. We need to subtract it, because zs_store()
@@ -2255,7 +2356,7 @@ struct zs_pool *zs_create_pool(const char *name)
 			 * class because it grows by ZS_HANDLE_SIZE extra bytes
 			 * right before class lookup.
 			 */
-			huge_class_size -= (ZS_HANDLE_SIZE - 1);
+			huge_class_size[idx] -= (ZS_HANDLE_SIZE - 1);
 		}
 
 		/*
@@ -2268,7 +2369,7 @@ struct zs_pool *zs_create_pool(const char *name)
 		 * previous size_class if possible.
 		 */
 		if (prev_class) {
-			if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
+			if (can_merge(prev_class, zpdescs_per_zspage, objs_per_zspage)) {
 				pool->size_class[i] = prev_class;
 				continue;
 			}
@@ -2280,7 +2381,7 @@ struct zs_pool *zs_create_pool(const char *name)
 
 		class->size = size;
 		class->index = i;
-		class->pages_per_zspage = pages_per_zspage;
+		class->zpdescs_per_zspage = zpdescs_per_zspage;
 		class->objs_per_zspage = objs_per_zspage;
 		spin_lock_init(&class->lock);
 		pool->size_class[i] = class;
-- 
2.43.0



^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH 2/4] zram: support compression at the granularity of multi-pages
  2026-12-05  2:17 [RFC PATCH v5 0/4] zram/zsmalloc: multi-page compression for large folios Nanzhe Zhao
  2026-12-05  2:18 ` [PATCH 1/4] mm: zsmalloc: support objects compressed based on multiple pages Nanzhe Zhao
@ 2026-12-05  2:18 ` Nanzhe Zhao
  2026-12-06  2:20   ` sashiko-bot
  2026-12-05  2:18 ` [PATCH 3/4] zram: backend_zstd: use multi-page size for zstd parameter setup Nanzhe Zhao
  2026-12-05  2:18 ` [PATCH 4/4] mm: swap: allow direct reclaim for synchronous multi-page swapin Nanzhe Zhao
  3 siblings, 1 reply; 8+ messages in thread
From: Nanzhe Zhao @ 2026-12-05  2:18 UTC (permalink / raw)
  To: Andrew Morton
  Cc: Nanzhe Zhao, linux-mm, linux-block, linux-kernel, Jens Axboe,
	Sergey Senozhatsky, Minchan Kim, Kairui Song, Johannes Weiner,
	Nhat Pham, Usama Arif, Yosry Ahmed, Chengming Zhou, Chris Li,
	David Hildenbrand, Ying Huang, Suren Baghdasaryan, Ryan Roberts,
	Kanchana P Sridhar, Wajdi K Feghali, Bala Seshasayee,
	Nick Terrell, Barry Song, Tangquan Zheng, Bo Zhang

From: Tangquan Zheng <zhengtangquan@oppo.com>

Currently, when a large folio with nr_pages is submitted to zram, it is
divided into nr_pages parts for compression and storage individually.
By transitioning to a higher granularity, we can notably enhance
compression rates while simultaneously reducing CPU consumption.

This patch introduces the capability for large folios to be divided
based on the granularity specified by ZSMALLOC_MULTI_PAGES_ORDER, which
defaults to 2. For instance, for folios sized at 128KiB, compression
will occur in eight 16KiB multi-pages.

Analogous to struct folio, we define the concept of a head slot to
manage the lifetime and serialization of multi-page slots.  For a
multi-page slot, the head slot is the entry whose index is naturally
aligned to (1 << ZCOMP_MULTI_PAGES_ORDER).  For a single-page slot, the
head slot is simply the slot itself.

Multi-page slot (order 2, 4 slots):
+-------------+-------------+-------------+-------------+
|   slot 0    |   slot 1    |   slot 2    |   slot 3    |
|  [ head ]   |  [ tail ]   |  [ tail ]   |  [ tail ]   |
+-------------+-------------+-------------+-------------+
       |
       +-- owns the bit-lock and the multi-page object handle

Single-page slot (1 slot):
+-------------+
|   slot N    |
|  [ head ]   | (head is itself)
+-------------+
       |
       +-- owns its own bit-lock and handle

Operations on multi-page slots, including slot_free() and
zram_slot_free_notify(), serialize on the bit-lock of the head slot.
The head slot stores the handle to the compressed multi-page object
in zsmalloc, while tail slots carry the ZRAM_COMP_MULTI_PAGES flag.
When the last live slot releases its flag, slot_free() releases the
entire multi-page object through the head slot.

This modification will notably reduce CPU consumption and enhance
compression ratios.

Note on MIPS D-cache aliasing: flush_dcache_page() on MIPS only flushes
a single page, but MIPS does not support THP_SWAP, so multi-page swap-in
is unreachable there. Non-swap multi-page block I/O is outside the scope
of this patch.

Signed-off-by: Tangquan Zheng <zhengtangquan@oppo.com>
Co-developed-by: Barry Song <baohua@kernel.org>
Signed-off-by: Barry Song <baohua@kernel.org>
Co-developed-by: Nanzhe Zhao <zhaonanzhe@xiaomi.com>
Signed-off-by: Nanzhe Zhao <zhaonanzhe@xiaomi.com>
---
 Documentation/ABI/testing/sysfs-block-zram  |  13 +
 Documentation/admin-guide/blockdev/zram.rst |   3 +
 drivers/block/zram/Kconfig                  |  10 +
 drivers/block/zram/zcomp.c                  |  36 +-
 drivers/block/zram/zcomp.h                  |  18 +-
 drivers/block/zram/zram_drv.c               | 706 +++++++++++++++++---
 drivers/block/zram/zram_drv.h               |  43 ++
 7 files changed, 737 insertions(+), 92 deletions(-)

diff --git a/Documentation/ABI/testing/sysfs-block-zram b/Documentation/ABI/testing/sysfs-block-zram
index 1ea9018a627f..fda6844dc53e 100644
--- a/Documentation/ABI/testing/sysfs-block-zram
+++ b/Documentation/ABI/testing/sysfs-block-zram
@@ -5,6 +5,9 @@ Description:
 		The disksize file is read-write and specifies the disk size
 		which represents the limit on the *uncompressed* worth of data
 		that can be stored in this disk.
+		The value is rounded up to the compression granularity
+		(PAGE_SIZE by default, or PAGE_SIZE << CONFIG_ZSMALLOC_MULTI_PAGES_ORDER
+		when CONFIG_ZRAM_MULTI_PAGES is enabled).
 		Unit: bytes
 
 What:		/sys/block/zram<id>/initstate
@@ -83,6 +86,16 @@ Description:
 		format is not documented intentionally and may change
 		anytime without any notice.
 
+What:		/sys/block/zram<id>/multi_pages_debug_stat
+Date:		September 2026
+Contact:	Tangquan Zheng <zhengtangquan@oppo.com>
+Description:
+		The multi_pages_debug_stat file is read-only and represents
+		debugging statistics for multi-page compression and
+		decompression when CONFIG_ZRAM_MULTI_PAGES is enabled. Its
+		format is not documented intentionally and may change anytime
+		without any notice.
+
 What:		/sys/block/zram<id>/backing_dev
 Date:		June 2017
 Contact:	Minchan Kim <minchan@kernel.org>
diff --git a/Documentation/admin-guide/blockdev/zram.rst b/Documentation/admin-guide/blockdev/zram.rst
index db256c53b127..fd393a79f729 100644
--- a/Documentation/admin-guide/blockdev/zram.rst
+++ b/Documentation/admin-guide/blockdev/zram.rst
@@ -161,6 +161,8 @@ Set Disksize
 
 Set disk size by writing the value to sysfs node 'disksize'.
 The value can be either in bytes or you can use mem suffixes.
+When CONFIG_ZRAM_MULTI_PAGES is enabled, the disksize is rounded up to the
+multi-page compression granularity (PAGE_SIZE << CONFIG_ZSMALLOC_MULTI_PAGES_ORDER).
 Examples::
 
 	# Initialize /dev/zram0 with 50MB disksize
@@ -255,6 +257,7 @@ comp_algorithm    	RW	show and change the compression algorithm
 algorithm_params	WO	setup compression algorithm parameters
 compact           	WO	trigger memory compaction
 debug_stat        	RO	this file is used for zram debugging purposes
+multi_pages_debug_stat	RO	debugging info for multi-page compression
 backing_dev	  	RW	set up backend storage for zram to write out
 idle		  	WO	mark allocated slot as idle
 ======================  ======  ===============================================
diff --git a/drivers/block/zram/Kconfig b/drivers/block/zram/Kconfig
index 402b7b175863..33f8c55b3119 100644
--- a/drivers/block/zram/Kconfig
+++ b/drivers/block/zram/Kconfig
@@ -145,3 +145,13 @@ config ZRAM_MULTI_COMP
 	  re-compress pages using a potentially slower but more effective
 	  compression algorithm. Note, that IDLE page recompression
 	  requires ZRAM_TRACK_ENTRY_ACTIME.
+
+config ZRAM_MULTI_PAGES
+	bool "Enable multiple pages compression and decompression"
+	depends on ZRAM && ZSMALLOC_MULTI_PAGES
+	depends on !ZRAM_WRITEBACK && !ZRAM_MULTI_COMP
+	help
+	  Initially, zram divided large folios into blocks of nr_pages, each sized
+	  equal to PAGE_SIZE, for compression. This option fine-tunes zram to
+	  improve compression granularity by dividing large folios into larger
+	  parts defined by the configuration option ZSMALLOC_MULTI_PAGES_ORDER.
diff --git a/drivers/block/zram/zcomp.c b/drivers/block/zram/zcomp.c
index adf6d368ae6c..568dfad3c01c 100644
--- a/drivers/block/zram/zcomp.c
+++ b/drivers/block/zram/zcomp.c
@@ -85,6 +85,10 @@ static void zcomp_dstrm_ctx_free(struct zcomp *comp, struct zcomp_dstrm *zstrm)
 static void zcomp_dstrm_free(struct zcomp *comp, struct zcomp_dstrm *zstrm)
 {
 	zcomp_dstrm_ctx_free(comp, zstrm);
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	vfree(zstrm->decomp_buf);
+	zstrm->decomp_buf = NULL;
+#endif
 	vfree(zstrm->local_copy);
 	zstrm->local_copy = NULL;
 }
@@ -252,13 +256,13 @@ void zcomp_dstrm_put(struct zcomp *comp, struct zcomp_dstrm *zstrm,
 }
 
 int zcomp_compress(struct zcomp *comp, struct zcomp_cstrm *zstrm,
-		   const void *src, unsigned int *dst_len)
+		   const void *src, unsigned int src_len, unsigned int *dst_len)
 {
 	struct zcomp_req req = {
 		.src = src,
 		.dst = zstrm->buffer,
-		.src_len = PAGE_SIZE,
-		.dst_len = 2 * PAGE_SIZE,
+		.src_len = src_len,
+		.dst_len = 2 * src_len,
 	};
 	int ret;
 
@@ -279,12 +283,13 @@ static int zcomp_decompress_buf(struct zcomp *comp, struct zcomp_dstrm *zstrm,
 }
 
 int zcomp_decompress(struct zcomp *comp, struct zcomp_dstrm *zstrm,
-		     struct scatterlist *sg, unsigned int src_len, void *dst)
+		     struct scatterlist *sg, unsigned int src_len, void *dst,
+		     unsigned int dst_len)
 {
 	struct zcomp_req req = {
 		.dst = dst,
 		.src_len = src_len,
-		.dst_len = PAGE_SIZE,
+		.dst_len = dst_len,
 	};
 	void *src;
 	int ret;
@@ -331,6 +336,9 @@ int zcomp_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
 	struct zcomp_cstrm *cstrm = NULL;
 	struct zcomp_dstrm *dstrm;
 	void *buffer = NULL, *local_copy;
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	void *decomp_buf = NULL;
+#endif
 	int ret;
 
 	/*
@@ -352,7 +360,7 @@ int zcomp_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
 		 * the case when compressed size is larger than the original
 		 * one
 		 */
-		buffer = vzalloc(2 * PAGE_SIZE);
+		buffer = vzalloc(2 * ZCOMP_MULTI_PAGES_SIZE);
 		if (!buffer) {
 			zcomp_cstrm_ctx_free(comp, cstrm);
 			return -ENOMEM;
@@ -366,13 +374,24 @@ int zcomp_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
 		goto err;
 	}
 
-	local_copy = vzalloc(PAGE_SIZE);
+	local_copy = vzalloc(ZCOMP_MULTI_PAGES_SIZE);
 	if (!local_copy) {
 		zcomp_dstrm_ctx_free(comp, dstrm);
 		ret = -ENOMEM;
 		goto err;
 	}
 
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	/* Scratch buffer for partial multi-page reads (swapin path). */
+	decomp_buf = vzalloc(ZCOMP_MULTI_PAGES_SIZE);
+	if (!decomp_buf) {
+		vfree(local_copy);
+		zcomp_dstrm_ctx_free(comp, dstrm);
+		ret = -ENOMEM;
+		goto err;
+	}
+#endif
+
 	/*
 	 * Publish under the stream locks to serialize with tasks that may
 	 * hold a stale pointer to this CPU's stream across an offline/online
@@ -386,6 +405,9 @@ int zcomp_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
 
 	down_write(&dstrm->lock);
 	dstrm->local_copy = local_copy;
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	dstrm->decomp_buf = decomp_buf;
+#endif
 	up_write(&dstrm->lock);
 
 	return 0;
diff --git a/drivers/block/zram/zcomp.h b/drivers/block/zram/zcomp.h
index b9a2b57a649b..b8288658520e 100644
--- a/drivers/block/zram/zcomp.h
+++ b/drivers/block/zram/zcomp.h
@@ -47,6 +47,15 @@ struct zcomp_ctx {
 	void *context;
 };
 
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+#define ZCOMP_MULTI_PAGES_ORDER	(_AC(CONFIG_ZSMALLOC_MULTI_PAGES_ORDER, UL))
+#define ZCOMP_MULTI_PAGES_NR	(1 << ZCOMP_MULTI_PAGES_ORDER)
+#define ZCOMP_MULTI_PAGES_SIZE	(PAGE_SIZE * ZCOMP_MULTI_PAGES_NR)
+#define MULTI_PAGE_SHIFT (ZCOMP_MULTI_PAGES_ORDER + PAGE_SHIFT)
+#else
+#define ZCOMP_MULTI_PAGES_SIZE	PAGE_SIZE
+#endif
+
 struct zcomp_cstrm {
 	struct mutex lock;
 	/* compression buffer */
@@ -65,6 +74,10 @@ struct zcomp_dstrm {
 	struct mutex excl_lock;
 	/* local copy of handle memory */
 	void *local_copy;
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	/* Temporary buffer for partial multi-page decompression */
+	void *decomp_buf;
+#endif
 	struct zcomp_ctx ctx;
 };
 
@@ -124,8 +137,9 @@ void zcomp_dstrm_put(struct zcomp *comp, struct zcomp_dstrm *zstrm,
 		     enum zcomp_dstrm_mode mode);
 
 int zcomp_compress(struct zcomp *comp, struct zcomp_cstrm *zstrm,
-		   const void *src, unsigned int *dst_len);
+		   const void *src, unsigned int src_len, unsigned int *dst_len);
 int zcomp_decompress(struct zcomp *comp, struct zcomp_dstrm *zstrm,
-		     struct scatterlist *sg, unsigned int src_len, void *dst);
+		     struct scatterlist *sg, unsigned int src_len, void *dst,
+		     unsigned int dst_len);
 
 #endif /* _ZCOMP_H_ */
diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c
index 95cec8b34239..f2476ce6afa8 100644
--- a/drivers/block/zram/zram_drv.c
+++ b/drivers/block/zram/zram_drv.c
@@ -53,11 +53,12 @@ static unsigned int num_devices = 1;
  * Pages that compress to sizes equals or greater than this are stored
  * uncompressed in memory.
  */
-static size_t huge_class_size;
+static size_t huge_class_size[ZSMALLOC_TYPE_MAX];
 
 static const struct block_device_operations zram_devops;
 
 static void slot_free(struct zram *zram, unsigned long index);
+static void __slot_free(struct zram *zram, unsigned long index, int nr_pages);
 
 /*
  * entry locking rules:
@@ -353,11 +354,12 @@ static inline void zram_fill_page(void *ptr, unsigned long len,
 	memset_l(ptr, value, len / sizeof(unsigned long));
 }
 
-static bool page_same_filled(void *ptr, unsigned long *element)
+static bool page_same_filled(void *ptr, unsigned long *element,
+			     unsigned int page_size)
 {
 	unsigned long *page;
 	unsigned long val;
-	unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
+	unsigned int pos, last_pos = page_size / sizeof(*page) - 1;
 
 	page = (unsigned long *)ptr;
 	val = page[0];
@@ -514,7 +516,7 @@ static ssize_t idle_store(struct device *dev, struct device_attribute *attr,
 static int read_from_zspool_raw(struct zram *zram, struct page *page,
 				unsigned long index);
 static int read_from_zspool(struct zram *zram, struct page *page,
-			    unsigned long index);
+			    unsigned long index, unsigned long page_size);
 
 struct zram_wb_ctl {
 	/* idle list is accessed only by the writeback task, no concurency */
@@ -1123,7 +1125,7 @@ static int zram_writeback_slots(struct zram *zram,
 		if (zram->compressed_wb)
 			err = read_from_zspool_raw(zram, req->page, index);
 		else
-			err = read_from_zspool(zram, req->page, index);
+			err = read_from_zspool(zram, req->page, index, PAGE_SIZE);
 		if (err)
 			goto next;
 		slot_unlock(zram, index);
@@ -1415,7 +1417,7 @@ static int decompress_bdev_page(struct zram *zram, struct page *page,
 
 	zstrm = zcomp_dstrm_get(zram->comps[prio], ZCOMP_DSTRM_EXCLUSIVE);
 	ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size,
-			       zstrm->local_copy);
+			       zstrm->local_copy, PAGE_SIZE);
 	if (!ret) {
 		void *dst = kmap_local_page(page);
 
@@ -2035,6 +2037,31 @@ static ssize_t debug_stat_show(struct device *dev,
 	return ret;
 }
 
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+static ssize_t multi_pages_debug_stat_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	struct zram *zram = dev_to_zram(dev);
+	ssize_t ret;
+
+	guard(rwsem_read)(&zram->dev_lock);
+	ret = sysfs_emit(buf,
+			"zram_bio write/read multi_pages count:%8llu %8llu\n"
+			"zram_bio failed write/read multi_pages count: %8llu %8llu\n"
+			"zram_bio partial write/read multi_pages count: %8llu %8llu\n"
+			"multi_pages_miss_free: %8llu\n",
+			(u64)atomic64_read(&zram->stats.zram_bio_write_multi_pages_count),
+			(u64)atomic64_read(&zram->stats.zram_bio_read_multi_pages_count),
+			(u64)atomic64_read(&zram->stats.multi_pages_failed_writes),
+			(u64)atomic64_read(&zram->stats.multi_pages_failed_reads),
+			(u64)atomic64_read(&zram->stats.zram_bio_write_multi_pages_partial_count),
+			(u64)atomic64_read(&zram->stats.zram_bio_read_multi_pages_partial_count),
+			(u64)atomic64_read(&zram->stats.multi_pages_miss_free));
+
+	return ret;
+}
+#endif
+
 static void zram_meta_free(struct zram *zram, u64 disksize)
 {
 	unsigned long num_pages = disksize >> PAGE_SHIFT;
@@ -2056,6 +2083,7 @@ static void zram_meta_free(struct zram *zram, u64 disksize)
 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
 {
 	unsigned long num_pages;
+	int i;
 
 	num_pages = disksize >> PAGE_SHIFT;
 	zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
@@ -2069,9 +2097,10 @@ static bool zram_meta_alloc(struct zram *zram, u64 disksize)
 		return false;
 	}
 
-	if (!huge_class_size)
-		huge_class_size = zs_huge_class_size(zram->mem_pool,
-						ZSMALLOC_TYPE_BASEPAGE);
+	for (i = 0; i < ZSMALLOC_TYPE_MAX; i++) {
+		if (!huge_class_size[i])
+			huge_class_size[i] = zs_huge_class_size(zram->mem_pool, i);
+	}
 
 	lockdep_register_key(&zram->table_lock_key);
 	lockdep_init_map(&zram->table_lock_map, "zram->table[index].lock",
@@ -2080,7 +2109,83 @@ static bool zram_meta_alloc(struct zram *zram, u64 disksize)
 	return true;
 }
 
-static void slot_free(struct zram *zram, unsigned long index)
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+
+static inline unsigned long zram_multi_pages_head_index(unsigned long index)
+{
+	return index & ~((unsigned long)ZCOMP_MULTI_PAGES_NR - 1);
+}
+
+/*
+ * Count how many slots in the window of ZCOMP_MULTI_PAGES_NR slots at
+ * @index's aligned head carry ZRAM_COMP_MULTI_PAGES.
+ *
+ * The flags are changed under the head slot's lock.
+ */
+static inline int __test_multi_pages_comp(struct zram *zram,
+					 unsigned long index)
+{
+	unsigned long head = zram_multi_pages_head_index(index);
+	int i, count = 0;
+
+	for (i = 0; i < ZCOMP_MULTI_PAGES_NR; i++) {
+		/*
+		 * Check the slot's multi-page flag without lock as a hint.
+		 * Callers will recheck while holding the head slot lock.
+		 */
+		if (data_race(READ_ONCE(zram->table[head + i].attr.flags)) &
+		    BIT(ZRAM_COMP_MULTI_PAGES))
+			count++;
+	}
+
+	return count;
+}
+
+static void set_slots_multi_pages(struct zram *zram, unsigned long index,
+				  int nr_pages)
+{
+	int i;
+
+	for (i = 0; i < nr_pages; i++)
+		set_slot_flag(zram, index + i, ZRAM_COMP_MULTI_PAGES);
+}
+
+#endif
+
+/*
+ * Return the head slot index of @index.  For a multi-page slot this is
+ * the aligned first slot.  For a single-page slot it is @index itself.
+ */
+static unsigned long zram_slot_head_index(struct zram *zram, unsigned long index)
+{
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	if (__test_multi_pages_comp(zram, index))
+		return zram_multi_pages_head_index(index);
+#endif
+
+	return index;
+}
+
+static unsigned int zram_slot_page_size(struct zram *zram, unsigned long index)
+{
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	if (__test_multi_pages_comp(zram, zram_multi_pages_head_index(index)))
+		return ZCOMP_MULTI_PAGES_SIZE;
+#endif
+
+	return PAGE_SIZE;
+}
+
+static int zram_slot_nr_pages(struct zram *zram, unsigned long index)
+{
+	return zram_slot_page_size(zram, index) >> PAGE_SHIFT;
+}
+
+/*
+ * Release the object at @index and subtract @nr_pages from pages_stored.
+ * @nr_pages must match what was accounted when the object was stored.
+ */
+static void __slot_free(struct zram *zram, unsigned long index, int nr_pages)
 {
 	struct zs_handle *handle;
 
@@ -2115,7 +2220,7 @@ static void slot_free(struct zram *zram, unsigned long index)
 	 */
 	if (test_slot_flag(zram, index, ZRAM_SAME)) {
 		clear_slot_flag(zram, index, ZRAM_SAME);
-		zram_stat_sub(zram, ZRAM_STAT_SAME_PAGES, 1);
+		zram_stat_sub(zram, ZRAM_STAT_SAME_PAGES, nr_pages);
 		goto out;
 	}
 
@@ -2128,44 +2233,76 @@ static void slot_free(struct zram *zram, unsigned long index)
 	zram_stat_sub(zram, ZRAM_STAT_COMPR_DATA_SIZE,
 		      get_slot_size(zram, index));
 out:
-	zram_stat_sub(zram, ZRAM_STAT_PAGES_STORED, 1);
+	zram_stat_sub(zram, ZRAM_STAT_PAGES_STORED, nr_pages);
 	zram->table[index].element = 0;
 	set_slot_size(zram, index, 0);
 }
 
+static void slot_free(struct zram *zram, unsigned long index)
+{
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	unsigned long head = zram_multi_pages_head_index(index);
+	int nr_pages = 1;
+	int i;
+
+	/* Clear all slots' MULTI flags first. */
+	if (__test_multi_pages_comp(zram, head)) {
+		index = head;
+		nr_pages = ZCOMP_MULTI_PAGES_NR;
+		for (i = 0; i < nr_pages; i++)
+			clear_slot_flag(zram, head + i, ZRAM_COMP_MULTI_PAGES);
+	}
+
+	/*
+	 * Then release the whole multi-page slot (by releasing the head
+	 * slot's handle).
+	 */
+	__slot_free(zram, index, nr_pages);
+
+	/*
+	 * Drop single-page objects left behind by a failed
+	 * zram_slot_free_notify trylock.
+	 */
+	for (i = 1; i < nr_pages; i++)
+		__slot_free(zram, index + i, 1);
+#else
+	__slot_free(zram, index, 1);
+#endif
+}
+
 static int read_same_filled_page(struct zram *zram, struct page *page,
-				 unsigned long index)
+				 unsigned long index, unsigned long page_size)
 {
 	void *mem;
 
 	mem = kmap_local_page(page);
-	zram_fill_page(mem, PAGE_SIZE, zram->table[index].element);
+	zram_fill_page(mem, page_size, zram->table[index].element);
 	kunmap_local(mem);
 	return 0;
 }
 
 static int read_incompressible_page(struct zram *zram, struct page *page,
-				    unsigned long index)
+				    unsigned long index,
+				    unsigned long page_size)
 {
 	struct scatterlist sg[2];
 	struct zs_handle *handle;
-	void *src, *dst;
+	void *dst;
 
 	handle = &zram->table[index].handle;
-	zs_obj_read_sg_begin(zram->mem_pool, handle, sg, PAGE_SIZE);
+	zs_obj_read_sg_begin(zram->mem_pool, handle, sg, page_size);
 	/* an incompressible object never spans two pages */
-	src = kmap_local_page(sg_page(sg));
 	dst = kmap_local_page(page);
-	copy_page(dst, src);
+	sg_copy_to_buffer(sg, sg_nents(sg), dst, page_size);
 	kunmap_local(dst);
-	kunmap_local(src);
 	zs_obj_read_sg_end(zram->mem_pool, handle);
 
 	return 0;
 }
 
 static int read_compressed_page(struct zram *zram, struct page *page,
-				unsigned long index)
+				unsigned long index,
+				unsigned long page_size)
 {
 	enum zcomp_dstrm_mode mode = ZCOMP_DSTRM_EXCLUSIVE;
 	struct zcomp_dstrm *zstrm;
@@ -2185,7 +2322,8 @@ static int read_compressed_page(struct zram *zram, struct page *page,
 
 	zstrm = zcomp_dstrm_get(zram->comps[prio], mode);
 	dst = kmap_local_page(page);
-	ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size, dst);
+	ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size, dst,
+			       page_size);
 	kunmap_local(dst);
 	zcomp_dstrm_put(zram->comps[prio], zstrm, mode);
 	zs_obj_read_sg_end(zram->mem_pool, handle);
@@ -2226,20 +2364,21 @@ static int read_from_zspool_raw(struct zram *zram, struct page *page,
  * Corresponding ZRAM slot should be locked.
  */
 static int read_from_zspool(struct zram *zram, struct page *page,
-			    unsigned long index)
+			    unsigned long index, unsigned long page_size)
 {
 	if (test_slot_flag(zram, index, ZRAM_SAME) ||
 	    !zs_handle_is_allocated(&zram->table[index].handle))
-		return read_same_filled_page(zram, page, index);
+		return read_same_filled_page(zram, page, index, page_size);
 
 	if (!test_slot_flag(zram, index, ZRAM_HUGE))
-		return read_compressed_page(zram, page, index);
+		return read_compressed_page(zram, page, index, page_size);
 	else
-		return read_incompressible_page(zram, page, index);
+		return read_incompressible_page(zram, page, index, page_size);
 }
 
-static int zram_read_page(struct zram *zram, struct page *page,
-			  unsigned long index, struct bio *parent)
+static int zram_read_page_size(struct zram *zram, struct page *page,
+			       unsigned long index, struct bio *parent,
+			       unsigned long page_size)
 {
 	int ret;
 
@@ -2247,7 +2386,7 @@ static int zram_read_page(struct zram *zram, struct page *page,
 	mark_slot_accessed(zram, index);
 	if (!test_slot_flag(zram, index, ZRAM_WB)) {
 		/* Slot should be locked through out the function call */
-		ret = read_from_zspool(zram, page, index);
+		ret = read_from_zspool(zram, page, index, page_size);
 		slot_unlock(zram, index);
 	} else {
 		unsigned long blk_idx = zram->table[index].blk_idx;
@@ -2263,6 +2402,12 @@ static int zram_read_page(struct zram *zram, struct page *page,
 	return ret;
 }
 
+static int zram_read_page(struct zram *zram, struct page *page,
+			  unsigned long index, struct bio *parent)
+{
+	return zram_read_page_size(zram, page, index, parent, PAGE_SIZE);
+}
+
 /*
  * Use a temporary buffer to decompress the page, as the decompressor
  * always expects a full page for the output.
@@ -2291,56 +2436,51 @@ static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
 }
 
 static int write_same_filled_page(struct zram *zram, unsigned long fill,
-				  unsigned long index)
+				  unsigned long index, int nr_pages)
 {
-	slot_lock(zram, index);
-	slot_free(zram, index);
+	__slot_free(zram, index, zram_slot_nr_pages(zram, index));
 	set_slot_flag(zram, index, ZRAM_SAME);
 	zram->table[index].element = fill;
 	mark_slot_accessed(zram, index);
-	slot_unlock(zram, index);
 
-	zram_stat_add(zram, ZRAM_STAT_SAME_PAGES, 1);
-	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, 1);
+	zram_stat_add(zram, ZRAM_STAT_SAME_PAGES, nr_pages);
+	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, nr_pages);
 
 	return 0;
 }
 
 static int write_incompressible_page(struct zram *zram, struct page *page,
-				     unsigned long index)
+				     unsigned long index, unsigned int page_size,
+				     int nr_pages)
 {
 	void *src;
 	int ret;
 
-	slot_lock(zram, index);
-	slot_free(zram, index);
+	__slot_free(zram, index, zram_slot_nr_pages(zram, index));
 	src = kmap_local_page(page);
 	ret = zs_store(zram->mem_pool, &zram->table[index].handle, src,
-		       PAGE_SIZE, GFP_NOIO | __GFP_NOWARN |
+		       page_size, GFP_NOIO | __GFP_NOWARN |
 		       __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page));
 	kunmap_local(src);
-	if (ret) {
-		slot_unlock(zram, index);
+	if (ret)
 		return ret;
-	}
 
 	update_used_max(zram);
 
 	set_slot_flag(zram, index, ZRAM_HUGE);
-	set_slot_size(zram, index, PAGE_SIZE);
+	set_slot_size(zram, index, page_size);
 	mark_slot_accessed(zram, index);
-	slot_unlock(zram, index);
 
-	zram_stat_add(zram, ZRAM_STAT_COMPR_DATA_SIZE, PAGE_SIZE);
+	zram_stat_add(zram, ZRAM_STAT_COMPR_DATA_SIZE, page_size);
 	zram_stat_add(zram, ZRAM_STAT_HUGE_PAGES, 1);
 	zram_stat_add(zram, ZRAM_STAT_HUGE_PAGES_SINCE, 1);
-	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, 1);
+	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, nr_pages);
 
 	return 0;
 }
 
-static int zram_write_page(struct zram *zram, struct page *page,
-			   unsigned long index)
+static int __zram_write_page(struct zram *zram, struct page *page,
+			    unsigned long index, unsigned int page_size)
 {
 	int ret = 0;
 	unsigned int comp_len;
@@ -2348,12 +2488,19 @@ static int zram_write_page(struct zram *zram, struct page *page,
 	struct zcomp_cstrm *zstrm;
 	unsigned long element;
 	bool same_filled;
+	int huge_class_idx = ZSMALLOC_TYPE_BASEPAGE;
+	int nr_pages = page_size >> PAGE_SHIFT;
+
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	if (page_size > PAGE_SIZE)
+		huge_class_idx = ZSMALLOC_TYPE_MULTI_PAGES;
+#endif
 
 	mem = kmap_local_page(page);
-	same_filled = page_same_filled(mem, &element);
+	same_filled = page_same_filled(mem, &element, page_size);
 	kunmap_local(mem);
 	if (same_filled)
-		return write_same_filled_page(zram, element, index);
+		return write_same_filled_page(zram, element, index, nr_pages);
 
 	if (!zram_can_store_page(zram))
 		return -ENOMEM;
@@ -2361,7 +2508,7 @@ static int zram_write_page(struct zram *zram, struct page *page,
 	zstrm = zcomp_cstrm_get(zram->comps[ZRAM_PRIMARY_COMP]);
 	mem = kmap_local_page(page);
 	ret = zcomp_compress(zram->comps[ZRAM_PRIMARY_COMP], zstrm,
-			     mem, &comp_len);
+			     mem, page_size, &comp_len);
 	kunmap_local(mem);
 
 	if (unlikely(ret)) {
@@ -2370,36 +2517,49 @@ static int zram_write_page(struct zram *zram, struct page *page,
 		return ret;
 	}
 
-	if (comp_len >= huge_class_size) {
+	if (comp_len >= huge_class_size[huge_class_idx]) {
 		zcomp_cstrm_put(zstrm);
-		return write_incompressible_page(zram, page, index);
+		return write_incompressible_page(zram, page, index, page_size,
+						 nr_pages);
 	}
 
-	slot_lock(zram, index);
-	slot_free(zram, index);
+	__slot_free(zram, index, zram_slot_nr_pages(zram, index));
 	ret = zs_store(zram->mem_pool, &zram->table[index].handle,
 		       zstrm->buffer, comp_len,
 		       GFP_NOIO | __GFP_NOWARN |
 		       __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page));
 	zcomp_cstrm_put(zstrm);
-	if (ret) {
-		slot_unlock(zram, index);
+	if (ret)
 		return ret;
-	}
 
 	update_used_max(zram);
 
 	set_slot_size(zram, index, comp_len);
 	mark_slot_accessed(zram, index);
-	slot_unlock(zram, index);
 
 	/* Update stats */
-	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, 1);
+	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, nr_pages);
 	zram_stat_add(zram, ZRAM_STAT_COMPR_DATA_SIZE, comp_len);
 
 	return ret;
 }
 
+static int zram_write_page(struct zram *zram, struct page *page,
+			   unsigned long index, unsigned int page_size)
+{
+	int ret;
+
+	slot_lock(zram, index);
+	ret = __zram_write_page(zram, page, index, page_size);
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	if (!ret && page_size > PAGE_SIZE)
+		set_slots_multi_pages(zram, index, page_size >> PAGE_SHIFT);
+#endif
+	slot_unlock(zram, index);
+
+	return ret;
+}
+
 /*
  * This is a partial IO. Read the full page before writing the changes.
  */
@@ -2415,7 +2575,7 @@ static int zram_bvec_write_partial(struct zram *zram, struct bio_vec *bvec,
 	ret = zram_read_page(zram, page, index, NULL);
 	if (!ret) {
 		memcpy_from_bvec(page_address(page) + offset, bvec);
-		ret = zram_write_page(zram, page, index);
+		ret = zram_write_page(zram, page, index, PAGE_SIZE);
 	}
 	__free_page(page);
 	return ret;
@@ -2426,7 +2586,7 @@ static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
 {
 	if (is_partial_io(bvec))
 		return zram_bvec_write_partial(zram, bvec, index, offset);
-	return zram_write_page(zram, bvec->bv_page, index);
+	return zram_write_page(zram, bvec->bv_page, index, PAGE_SIZE);
 }
 
 #ifdef CONFIG_ZRAM_MULTI_COMP
@@ -2514,7 +2674,7 @@ static int recompress_slot(struct zram *zram, unsigned long index,
 	if (comp_len_old < threshold)
 		return 0;
 
-	ret = read_from_zspool(zram, page, index);
+	ret = read_from_zspool(zram, page, index, PAGE_SIZE);
 	if (ret)
 		return ret;
 
@@ -2527,7 +2687,8 @@ static int recompress_slot(struct zram *zram, unsigned long index,
 
 	zstrm = zcomp_cstrm_get(zram->comps[prio]);
 	src = kmap_local_page(page);
-	ret = zcomp_compress(zram->comps[prio], zstrm, src, &comp_len_new);
+	ret = zcomp_compress(zram->comps[prio], zstrm, src, PAGE_SIZE,
+			      &comp_len_new);
 	kunmap_local(src);
 
 	/*
@@ -2667,7 +2828,7 @@ static ssize_t recompress_store(struct device *dev,
 		}
 	}
 
-	if (threshold >= huge_class_size)
+	if (threshold >= huge_class_size[ZSMALLOC_TYPE_BASEPAGE])
 		return -EINVAL;
 
 	guard(rwsem_write)(&zram->dev_lock);
@@ -2741,8 +2902,11 @@ static void zram_bio_discard(struct zram *zram, struct bio *bio)
 {
 	size_t n = bio->bi_iter.bi_size;
 	unsigned long index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
-	u32 offset = (bio->bi_iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
+	unsigned long head = zram_slot_head_index(zram, index);
+	u32 page_offset = (bio->bi_iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
 			SECTOR_SHIFT;
+	unsigned int page_size;
+	u32 offset;
 
 	/*
 	 * zram manages data in physical block size units. Because logical block
@@ -2753,30 +2917,353 @@ static void zram_bio_discard(struct zram *zram, struct bio *bio)
 	 * and re-compressing and then re-storing it, this isn't reasonable
 	 * because our intent with a discard request is to save memory.  So
 	 * skipping this logical block is appropriate here.
+	 *
+	 * For a multi-page slot, the offset can be inside a
+	 * ZCOMP_MULTI_PAGES_SIZE object.  We also do not want to read part of
+	 * the object and re-compress it, so skip the whole multi-page slot.
 	 */
+	slot_lock(zram, head);
+	page_size = zram_slot_page_size(zram, head);
+
+	/*
+	 * The multi-page slot may have been released.  @index is then a
+	 * single-page slot.  Lock it and read its size again.
+	 */
+	if (index != head && page_size == PAGE_SIZE) {
+		slot_unlock(zram, head);
+		head = index;
+		slot_lock(zram, head);
+		page_size = zram_slot_page_size(zram, head);
+	}
+
+	offset = page_offset + ((index - head) << PAGE_SHIFT);
 	if (offset) {
-		if (n <= (PAGE_SIZE - offset))
+		if (n <= page_size - offset) {
+			slot_unlock(zram, head);
 			goto end_bio;
-
-		n -= (PAGE_SIZE - offset);
-		index++;
+		}
+		n -= page_size - offset;
+		index = head + (page_size >> PAGE_SHIFT);
 	}
+	slot_unlock(zram, head);
 
 	while (n >= PAGE_SIZE) {
-		slot_lock(zram, index);
+		unsigned long head = zram_slot_head_index(zram, index);
+		unsigned int page_size;
+
+		slot_lock(zram, head);
+		page_size = zram_slot_page_size(zram, head);
+		if (n < page_size) {
+			/* the request ends inside this slot, leave it alone */
+			slot_unlock(zram, head);
+			break;
+		}
 		slot_free(zram, index);
-		slot_unlock(zram, index);
+		slot_unlock(zram, head);
 		zram_stat_add(zram, ZRAM_STAT_NOTIFY_FREE, 1);
-		index++;
-		n -= PAGE_SIZE;
+		index = head + (page_size >> PAGE_SHIFT);
+		n -= page_size;
 	}
 
 end_bio:
 	bio_endio(bio);
 }
 
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+
+static inline bool want_multi_pages_comp(struct zram *zram, struct bio *bio)
+{
+	unsigned long index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
+
+	/*
+	 * For a synchronous device such as zram, swap submits one bio with a
+	 * single bvec that carries one folio.  Bios with more than one bvec
+	 * are not supported.
+	 */
+	WARN_ON_ONCE(bio->bi_vcnt != 1);
+
+	if (bio->bi_io_vec->bv_len >= ZCOMP_MULTI_PAGES_SIZE)
+		return true;
+
+	return !!__test_multi_pages_comp(zram, index);
+}
+
+static inline bool test_multi_pages_comp(struct zram *zram, struct bio *bio)
+{
+	unsigned long index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
+
+	return !!__test_multi_pages_comp(zram, index);
+}
+
+static inline bool is_multi_pages_partial_io(struct bio_vec *bvec)
+{
+	return bvec->bv_len != ZCOMP_MULTI_PAGES_SIZE;
+}
+
+static int zram_read_partial_from_zspool(struct zram *zram, struct bio_vec *bvec,
+					unsigned long index, int offset)
+{
+	struct zs_handle *handle = &zram->table[index].handle;
+	struct zcomp_dstrm *zstrm;
+	struct scatterlist sg[2];
+	unsigned int size;
+	void *src, *dst;
+	u32 prio;
+	int ret;
+	unsigned long page_size = ZCOMP_MULTI_PAGES_SIZE;
+
+	if (test_slot_flag(zram, index, ZRAM_SAME) ||
+	    !zs_handle_is_allocated(handle)) {
+		void *mem;
+
+		mem = kmap_local_page(bvec->bv_page);
+		zram_fill_page(mem + bvec->bv_offset, bvec->bv_len,
+			       zram->table[index].element);
+		kunmap_local(mem);
+		return 0;
+	}
+
+	size = get_slot_size(zram, index);
+	zs_obj_read_sg_begin(zram->mem_pool, handle, sg, size);
+
+	if (size == page_size) {
+		src = kmap_local_page(sg_page(sg));
+		dst = kmap_local_page(bvec->bv_page);
+		memcpy(dst + bvec->bv_offset, src + offset, bvec->bv_len);
+		kunmap_local(dst);
+		kunmap_local(src);
+		ret = 0;
+	} else {
+		prio = get_slot_comp_priority(zram, index);
+		zstrm = zcomp_dstrm_get(zram->comps[prio],
+					ZCOMP_DSTRM_EXCLUSIVE);
+		ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size,
+				       zstrm->decomp_buf, page_size);
+		if (!ret) {
+			dst = kmap_local_page(bvec->bv_page);
+			memcpy(dst + bvec->bv_offset,
+			       zstrm->decomp_buf + offset, bvec->bv_len);
+			kunmap_local(dst);
+		}
+		zcomp_dstrm_put(zram->comps[prio], zstrm,
+				ZCOMP_DSTRM_EXCLUSIVE);
+	}
+	zs_obj_read_sg_end(zram->mem_pool, handle);
+
+	return ret;
+}
+
+static int zram_bvec_read_multi_pages_partial(struct zram *zram,
+					      struct bio_vec *bvec,
+					      unsigned long index, int offset,
+					      struct bio *bio)
+{
+	int ret;
+
+	slot_lock(zram, index);
+	if (!test_slot_flag(zram, index, ZRAM_WB)) {
+		ret = zram_read_partial_from_zspool(zram, bvec, index, offset);
+		slot_unlock(zram, index);
+	} else {
+		unsigned long blk_idx = zram->table[index].blk_idx;
+
+		slot_unlock(zram, index);
+		ret = read_from_bdev(zram, bvec->bv_page, index, blk_idx, bio);
+	}
+
+	if (WARN_ON(ret < 0))
+		pr_err("Decompression failed! err=%d, page=%lu offset=%d\n",
+		       ret, index, offset);
+	if (!ret)
+		atomic64_inc(&zram->stats.zram_bio_read_multi_pages_partial_count);
+
+	return ret;
+}
+
+static int zram_bvec_read_multi_pages(struct zram *zram, struct bio_vec *bvec,
+				      unsigned long index, int offset,
+				      struct bio *bio)
+{
+	if (is_multi_pages_partial_io(bvec))
+		return zram_bvec_read_multi_pages_partial(zram, bvec, index,
+							  offset, bio);
+
+	return zram_read_page_size(zram, bvec->bv_page, index, bio,
+				   ZCOMP_MULTI_PAGES_SIZE);
+}
+
+static int zram_bvec_write_multi_pages_partial(struct zram *zram,
+					       struct bio_vec *bvec,
+					       unsigned long index, int offset,
+					       struct bio *bio)
+{
+	struct page *page;
+	void *src, *dst;
+	unsigned int first, last, i;
+	int ret;
+
+	/*
+	 * Recheck the MULTI flags under the slot lock.  The multi-page slot
+	 * may have been released since the hint.  If so, let the caller
+	 * retry the whole bio through the single-page path.
+	 */
+	slot_lock(zram, index);
+	if (!__test_multi_pages_comp(zram, index)) {
+		slot_unlock(zram, index);
+		return -EAGAIN;
+	}
+	mark_slot_accessed(zram, index);
+
+	page = alloc_pages(GFP_NOIO | __GFP_COMP, ZCOMP_MULTI_PAGES_ORDER);
+	if (!page) {
+		slot_unlock(zram, index);
+		return -ENOMEM;
+	}
+
+	ret = read_from_zspool(zram, page, index, ZCOMP_MULTI_PAGES_SIZE);
+	if (!ret) {
+		src = kmap_local_page(bvec->bv_page);
+		dst = kmap_local_page(page);
+		memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
+		kunmap_local(dst);
+		kunmap_local(src);
+
+		atomic64_inc(&zram->stats.zram_bio_write_multi_pages_partial_count);
+		ret = __zram_write_page(zram, page, index,
+					ZCOMP_MULTI_PAGES_SIZE);
+		if (!ret) {
+			first = offset >> PAGE_SHIFT;
+			last = (offset + bvec->bv_len - 1) >> PAGE_SHIFT;
+			for (i = first; i <= last; i++)
+				set_slot_flag(zram, index + i,
+					      ZRAM_COMP_MULTI_PAGES);
+		}
+	}
+	slot_unlock(zram, index);
+
+	__free_pages(page, ZCOMP_MULTI_PAGES_ORDER);
+	return ret;
+}
+
+static int zram_bvec_write_multi_pages(struct zram *zram, struct bio_vec *bvec,
+				       unsigned long index, int offset,
+				       struct bio *bio)
+{
+	if (is_multi_pages_partial_io(bvec))
+		return zram_bvec_write_multi_pages_partial(zram, bvec, index,
+							   offset, bio);
+
+	return zram_write_page(zram, bvec->bv_page, index,
+			       ZCOMP_MULTI_PAGES_SIZE);
+}
+
+static void zram_bio_read_multi_pages(struct zram *zram, struct bio *bio)
+{
+	unsigned long start_time = bio_start_io_acct(bio);
+	struct bvec_iter iter = bio->bi_iter;
+
+	do {
+		unsigned long index = zram_multi_pages_head_index(
+			iter.bi_sector >> SECTORS_PER_PAGE_SHIFT);
+		u32 offset = (iter.bi_sector & (SECTORS_PER_MULTI_PAGE - 1)) <<
+			     SECTOR_SHIFT;
+		struct bio_vec bv = multi_pages_bio_iter_iovec(bio, iter);
+
+		atomic64_inc(&zram->stats.zram_bio_read_multi_pages_count);
+		bv.bv_len = min_t(u32, bv.bv_len,
+				  ZCOMP_MULTI_PAGES_SIZE - offset);
+
+		if (zram_bvec_read_multi_pages(zram, &bv, index, offset, bio) < 0) {
+			atomic64_inc(&zram->stats.multi_pages_failed_reads);
+			bio->bi_status = BLK_STS_IOERR;
+			break;
+		}
+		flush_dcache_page(bv.bv_page);
+
+		slot_lock(zram, index);
+		mark_slot_accessed(zram, index);
+		slot_unlock(zram, index);
+
+		bio_advance_iter_single(bio, &iter, bv.bv_len);
+	} while (iter.bi_size);
+
+	bio_end_io_acct(bio, start_time);
+	bio_endio(bio);
+}
+
+static int zram_bio_write_multi_pages(struct zram *zram, struct bio *bio)
+{
+	struct bvec_iter iter = bio->bi_iter;
+	int ret;
+
+	if (bio->bi_iter.bi_size >= ZCOMP_MULTI_PAGES_SIZE) {
+		unsigned long start =
+			bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
+
+		/*
+		 * Swapout of a large folio always starts at a slot index
+		 * naturally aligned to the folio.  We do not support
+		 * multi-page compression that starts at a misaligned slot
+		 * index.  On the swap path that cannot happen.
+		 */
+		WARN_ON_ONCE(start != zram_multi_pages_head_index(start));
+	}
+
+	do {
+		unsigned long index = zram_multi_pages_head_index(
+			iter.bi_sector >> SECTORS_PER_PAGE_SHIFT);
+		u32 offset = (iter.bi_sector & (SECTORS_PER_MULTI_PAGE - 1)) <<
+			     SECTOR_SHIFT;
+		struct bio_vec bv = multi_pages_bio_iter_iovec(bio, iter);
+
+		bv.bv_len = min_t(u32, bv.bv_len,
+				  ZCOMP_MULTI_PAGES_SIZE - offset);
+
+		atomic64_inc(&zram->stats.zram_bio_write_multi_pages_count);
+		ret = zram_bvec_write_multi_pages(zram, &bv, index, offset, bio);
+		if (ret == -EAGAIN)
+			return -EAGAIN;
+		if (ret < 0) {
+			atomic64_inc(&zram->stats.multi_pages_failed_writes);
+			return -EIO;
+		}
+
+		slot_lock(zram, index);
+		mark_slot_accessed(zram, index);
+		slot_unlock(zram, index);
+
+		bio_advance_iter_single(bio, &iter, bv.bv_len);
+	} while (iter.bi_size);
+
+	return 0;
+}
+#else /* CONFIG_ZRAM_MULTI_PAGES */
+static inline bool test_multi_pages_comp(struct zram *zram, struct bio *bio)
+{
+	return false;
+}
+
+static inline bool want_multi_pages_comp(struct zram *zram, struct bio *bio)
+{
+	return false;
+}
+
+static inline void zram_bio_read_multi_pages(struct zram *zram,
+					     struct bio *bio) { }
+static inline int zram_bio_write_multi_pages(struct zram *zram,
+					     struct bio *bio)
+{
+	return -EOPNOTSUPP;
+}
+#endif
+
 static void zram_bio_read(struct zram *zram, struct bio *bio)
 {
+	if (test_multi_pages_comp(zram, bio)) {
+		zram_bio_read_multi_pages(zram, bio);
+		return;
+	}
+
 	unsigned long start_time = bio_start_io_acct(bio);
 	struct bvec_iter iter = bio->bi_iter;
 
@@ -2802,9 +3289,8 @@ static void zram_bio_read(struct zram *zram, struct bio *bio)
 	bio_endio(bio);
 }
 
-static void zram_bio_write(struct zram *zram, struct bio *bio)
+static int zram_bio_write_page(struct zram *zram, struct bio *bio)
 {
-	unsigned long start_time = bio_start_io_acct(bio);
 	struct bvec_iter iter = bio->bi_iter;
 
 	do {
@@ -2817,13 +3303,33 @@ static void zram_bio_write(struct zram *zram, struct bio *bio)
 
 		if (zram_bvec_write(zram, &bv, index, offset) < 0) {
 			atomic64_inc(&zram->stats.failed_writes);
-			bio->bi_status = BLK_STS_IOERR;
-			break;
+			return -EIO;
 		}
 
 		bio_advance_iter_single(bio, &iter, bv.bv_len);
 	} while (iter.bi_size);
 
+	return 0;
+}
+
+static void zram_bio_write(struct zram *zram, struct bio *bio)
+{
+	unsigned long start_time = bio_start_io_acct(bio);
+	int ret = -EAGAIN;
+
+	if (want_multi_pages_comp(zram, bio))
+		ret = zram_bio_write_multi_pages(zram, bio);
+
+	/*
+	 * If the multi-page slot has been freed, fall back to the single-page
+	 * path.
+	 */
+	if (ret == -EAGAIN)
+		ret = zram_bio_write_page(zram, bio);
+
+	if (ret < 0)
+		bio->bi_status = BLK_STS_IOERR;
+
 	bio_end_io_acct(bio, start_time);
 	bio_endio(bio);
 }
@@ -2855,18 +3361,46 @@ static void zram_submit_bio(struct bio *bio)
 static void zram_slot_free_notify(struct block_device *bdev,
 				unsigned long index)
 {
-	struct zram *zram;
-
-	zram = bdev->bd_disk->private_data;
+	struct zram *zram = bdev->bd_disk->private_data;
 
 	zram_stat_add(zram, ZRAM_STAT_NOTIFY_FREE, 1);
+
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	{
+		unsigned long head = zram_slot_head_index(zram, index);
+
+		/*
+		 * Try to lock the head slot to serialize with concurrent
+		 * slot_free().  On failure, skip this free, same as the
+		 * single-page path.
+		 */
+		if (!slot_trylock(zram, head)) {
+			atomic64_inc(&zram->stats.miss_free);
+			atomic64_inc(&zram->stats.multi_pages_miss_free);
+			return;
+		}
+
+		if (__test_multi_pages_comp(zram, head) > 1) {
+			clear_slot_flag(zram, index, ZRAM_COMP_MULTI_PAGES);
+			slot_unlock(zram, head);
+			return;
+		}
+
+		/*
+		 * Free the whole multi-page slot if this is the last slot
+		 * holding the MULTI_PAGE flag.
+		 */
+		slot_free(zram, index);
+		slot_unlock(zram, head);
+	}
+#else
 	if (!slot_trylock(zram, index)) {
 		atomic64_inc(&zram->stats.miss_free);
 		return;
 	}
-
 	slot_free(zram, index);
 	slot_unlock(zram, index);
+#endif
 }
 
 static void zram_comp_params_reset(struct zram *zram)
@@ -2946,7 +3480,7 @@ static ssize_t disksize_store(struct device *dev, struct device_attribute *attr,
 		return -EBUSY;
 	}
 
-	disksize = PAGE_ALIGN(disksize);
+	disksize = ALIGN(disksize, ZCOMP_MULTI_PAGES_SIZE);
 	num_pages = disksize >> PAGE_SHIFT;
 	/* Slots are addressed by an unsigned long index */
 	if (!num_pages || ((u64)num_pages << PAGE_SHIFT) != disksize)
@@ -3044,6 +3578,9 @@ static const struct block_device_operations zram_devops = {
 static DEVICE_ATTR_RO(io_stat);
 static DEVICE_ATTR_RO(mm_stat);
 static DEVICE_ATTR_RO(debug_stat);
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+static DEVICE_ATTR_RO(multi_pages_debug_stat);
+#endif
 static DEVICE_ATTR_WO(compact);
 static DEVICE_ATTR_RW(disksize);
 static DEVICE_ATTR_RO(initstate);
@@ -3088,6 +3625,9 @@ static struct attribute *zram_disk_attrs[] = {
 	&dev_attr_io_stat.attr,
 	&dev_attr_mm_stat.attr,
 	&dev_attr_debug_stat.attr,
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	&dev_attr_multi_pages_debug_stat.attr,
+#endif
 #ifdef CONFIG_ZRAM_MULTI_COMP
 	&dev_attr_recomp_algorithm.attr,
 	&dev_attr_recompress.attr,
diff --git a/drivers/block/zram/zram_drv.h b/drivers/block/zram/zram_drv.h
index 1fbb00dc2c29..596961912992 100644
--- a/drivers/block/zram/zram_drv.h
+++ b/drivers/block/zram/zram_drv.h
@@ -29,6 +29,11 @@
 #define ZRAM_SECTOR_PER_LOGICAL_BLOCK	\
 	(1 << (ZRAM_LOGICAL_BLOCK_SHIFT - SECTOR_SHIFT))
 
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+#define SECTORS_PER_MULTI_PAGE_SHIFT	(MULTI_PAGE_SHIFT - SECTOR_SHIFT)
+#define SECTORS_PER_MULTI_PAGE		(1 << SECTORS_PER_MULTI_PAGE_SHIFT)
+#endif
+
 /*
  * ZRAM is mainly used for memory efficiency so we want to keep memory
  * footprint small and thus squeeze size and zram pageflags into a flags
@@ -38,7 +43,12 @@
  *
  * We use BUILD_BUG_ON() to make sure that zram pageflags don't overflow.
  */
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+#define ZRAM_FLAG_SHIFT (PAGE_SHIFT + CONFIG_ZSMALLOC_MULTI_PAGES_ORDER + 1)
+#else
 #define ZRAM_FLAG_SHIFT (PAGE_SHIFT + 1)
+#endif
+
 
 /* Only 2 bits are allowed for comp priority index */
 #define ZRAM_COMP_PRIORITY_MASK	0x3
@@ -56,6 +66,10 @@ enum zram_pageflags {
 	ZRAM_COMP_PRIORITY_BIT1, /* First bit of comp priority index */
 	ZRAM_COMP_PRIORITY_BIT2, /* Second bit of comp priority index */
 
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	ZRAM_COMP_MULTI_PAGES,	/* Compressed by multi-pages */
+#endif
+
 	__NR_ZRAM_PAGEFLAGS,
 };
 
@@ -123,6 +137,15 @@ struct zram_stats {
 	atomic64_t bd_reads;		/* no. of reads from backing device */
 	atomic64_t bd_writes;		/* no. of writes from backing device */
 #endif
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+	atomic64_t zram_bio_write_multi_pages_count;
+	atomic64_t zram_bio_read_multi_pages_count;
+	atomic64_t multi_pages_failed_writes;
+	atomic64_t multi_pages_failed_reads;
+	atomic64_t zram_bio_write_multi_pages_partial_count;
+	atomic64_t zram_bio_read_multi_pages_partial_count;
+	atomic64_t multi_pages_miss_free;
+#endif
 };
 
 #ifdef CONFIG_ZRAM_MULTI_COMP
@@ -181,4 +204,24 @@ struct zram {
 	struct dentry *debugfs_dir;
 #endif
 };
+
+#ifdef CONFIG_ZRAM_MULTI_PAGES
+#define multi_pages_bvec_iter_offset(bvec, iter)				\
+	(mp_bvec_iter_offset((bvec), (iter)) % ZCOMP_MULTI_PAGES_SIZE)
+
+#define multi_pages_bvec_iter_len(bvec, iter)				\
+	min_t(unsigned int, mp_bvec_iter_len((bvec), (iter)),		\
+	      ZCOMP_MULTI_PAGES_SIZE -					\
+	      multi_pages_bvec_iter_offset((bvec), (iter)))
+
+#define multi_pages_bvec_iter_bvec(bvec, iter)				\
+((struct bio_vec) {							\
+	.bv_page	= bvec_iter_page((bvec), (iter)),		\
+	.bv_len		= multi_pages_bvec_iter_len((bvec), (iter)),	\
+	.bv_offset	= bvec_iter_offset((bvec), (iter)),		\
+})
+
+#define multi_pages_bio_iter_iovec(bio, iter)				\
+	multi_pages_bvec_iter_bvec((bio)->bi_io_vec, (iter))
+#endif
 #endif
-- 
2.43.0



^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH 3/4] zram: backend_zstd: use multi-page size for zstd parameter setup
  2026-12-05  2:17 [RFC PATCH v5 0/4] zram/zsmalloc: multi-page compression for large folios Nanzhe Zhao
  2026-12-05  2:18 ` [PATCH 1/4] mm: zsmalloc: support objects compressed based on multiple pages Nanzhe Zhao
  2026-12-05  2:18 ` [PATCH 2/4] zram: support compression at the granularity of multi-pages Nanzhe Zhao
@ 2026-12-05  2:18 ` Nanzhe Zhao
  2026-12-05  2:18 ` [PATCH 4/4] mm: swap: allow direct reclaim for synchronous multi-page swapin Nanzhe Zhao
  3 siblings, 0 replies; 8+ messages in thread
From: Nanzhe Zhao @ 2026-12-05  2:18 UTC (permalink / raw)
  To: Andrew Morton
  Cc: Nanzhe Zhao, linux-mm, linux-block, linux-kernel, Jens Axboe,
	Sergey Senozhatsky, Minchan Kim, Kairui Song, Johannes Weiner,
	Nhat Pham, Usama Arif, Yosry Ahmed, Chengming Zhou, Chris Li,
	David Hildenbrand, Ying Huang, Suren Baghdasaryan, Ryan Roberts,
	Kanchana P Sridhar, Wajdi K Feghali, Bala Seshasayee,
	Nick Terrell, Barry Song, Tangquan Zheng, Bo Zhang

From: Barry Song <baohua@kernel.org>

zstd_setup_params() passes PAGE_SIZE to zstd_get_params() and
zstd_get_cparams() as the source size hint. When multi-page compression
is enabled, compressing 16 KiB blocks with 4 KiB-tuned parameters limits
zstd's match window to a single page and prevents it from finding
cross-page redundancy.

Pass ZCOMP_MULTI_PAGES_SIZE instead of PAGE_SIZE so that zstd configures
its parameters for the multi-page block size.

Signed-off-by: Barry Song <baohua@kernel.org>
Co-developed-by: Nanzhe Zhao <zhaonanzhe@xiaomi.com>
Signed-off-by: Nanzhe Zhao <zhaonanzhe@xiaomi.com>
---
 drivers/block/zram/backend_zstd.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/drivers/block/zram/backend_zstd.c b/drivers/block/zram/backend_zstd.c
index 824174815ddf..63f133fcb4b3 100644
--- a/drivers/block/zram/backend_zstd.c
+++ b/drivers/block/zram/backend_zstd.c
@@ -73,7 +73,7 @@ static int zstd_setup_params(struct zcomp_params *params)
 		return -ENOMEM;
 
 	params->drv_data = zp;
-	zp->cprm = zstd_get_params(params->level, PAGE_SIZE);
+	zp->cprm = zstd_get_params(params->level, ZCOMP_MULTI_PAGES_SIZE);
 
 	zp->custom_mem.customAlloc = zstd_custom_alloc;
 	zp->custom_mem.customFree = zstd_custom_free;
@@ -81,7 +81,7 @@ static int zstd_setup_params(struct zcomp_params *params)
 	if (!params->dict || !params->dict_sz)
 		return 0;
 
-	prm = zstd_get_cparams(params->level, PAGE_SIZE,
+	prm = zstd_get_cparams(params->level, ZCOMP_MULTI_PAGES_SIZE,
 			       params->dict_sz);
 	zp->cdict = zstd_create_cdict_byreference(params->dict,
 						  params->dict_sz,
-- 
2.43.0



^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH 4/4] mm: swap: allow direct reclaim for synchronous multi-page swapin
  2026-12-05  2:17 [RFC PATCH v5 0/4] zram/zsmalloc: multi-page compression for large folios Nanzhe Zhao
                   ` (2 preceding siblings ...)
  2026-12-05  2:18 ` [PATCH 3/4] zram: backend_zstd: use multi-page size for zstd parameter setup Nanzhe Zhao
@ 2026-12-05  2:18 ` Nanzhe Zhao
  2026-12-06  2:20   ` sashiko-bot
  3 siblings, 1 reply; 8+ messages in thread
From: Nanzhe Zhao @ 2026-12-05  2:18 UTC (permalink / raw)
  To: Andrew Morton
  Cc: Nanzhe Zhao, linux-mm, linux-block, linux-kernel, Jens Axboe,
	Sergey Senozhatsky, Minchan Kim, Kairui Song, Johannes Weiner,
	Nhat Pham, Usama Arif, Yosry Ahmed, Chengming Zhou, Chris Li,
	David Hildenbrand, Ying Huang, Suren Baghdasaryan, Ryan Roberts,
	Kanchana P Sridhar, Wajdi K Feghali, Bala Seshasayee,
	Nick Terrell, Barry Song, Tangquan Zheng, Bo Zhang

Synchronous swap devices such as zram complete swap I/O in the faulting
context. With multi-page compression enabled, a 16 KiB block is
stored and decompressed as a single object.

The swapin allocation inherits the VMA's THP gfp mask, which drops
__GFP_DIRECT_RECLAIM for VMAs without MADV_HUGEPAGE. Under memory
pressure, the order-2 allocation fails and falls back to order-0,
requiring the entire 16 KiB block to be decompressed just to swap in
an order-0 page.

Allow direct reclaim for order-2 swapin allocation to improve the
allocation success rate and avoid partial reads.

Signed-off-by: Nanzhe Zhao <zhaonanzhe@xiaomi.com>
---
 mm/swap_state.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/mm/swap_state.c b/mm/swap_state.c
index da65d75ceead..0e703dcc4210 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -462,6 +462,13 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
 	if (mpol || !vmf) {
 		folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id());
 	} else {
+		/*
+		 * zsmalloc uses order-2 pages to store compressed data.
+		 * Allow direct reclaim to improve allocation success and
+		 * avoid partial reads.
+		 */
+		if (order == 2)
+			gfp |= __GFP_RECLAIM | __GFP_NORETRY;
 		address = round_down(vmf->address, PAGE_SIZE << order);
 		folio = vma_alloc_folio(gfp, order, vmf->vma, address);
 	}
-- 
2.43.0



^ permalink raw reply related	[flat|nested] 8+ messages in thread

* Re: [PATCH 1/4] mm: zsmalloc: support objects compressed based on multiple pages
  2026-12-05  2:18 ` [PATCH 1/4] mm: zsmalloc: support objects compressed based on multiple pages Nanzhe Zhao
@ 2026-12-06  2:20   ` sashiko-bot
  0 siblings, 0 replies; 8+ messages in thread
From: sashiko-bot @ 2026-12-06  2:20 UTC (permalink / raw)
  To: Nanzhe Zhao, Andrew Morton
  Cc: linux-mm, Jens Axboe, Sergey Senozhatsky, Minchan Kim,
	Kairui Song, Johannes Weiner, Nhat Pham, Usama Arif, Yosry Ahmed,
	Chengming Zhou, Chris Li, David Hildenbrand, Ying Huang,
	Suren Baghdasaryan, Ryan Roberts, Kanchana P Sridhar,
	Wajdi K Feghali, Bala Seshasayee, Nick Terrell, Barry Song,
	Tangquan Zheng, Bo Zhang

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] mm: zsmalloc: zs_rebind_handle() uses offset_in_page() on
  multi-page zpdescs
- [Medium] mm: zsmalloc: CLASS_BITS bump expands ZS_OBJ_CLASS_BITS to 10
  bits
- [Medium] mm: zsmalloc: __zs_compact() write-locks pool for empty
  multi-page classes
- [Low] mm: zsmalloc: pages_per_zspage doc mismatches
  zs_stats_size_show() output
--

commit 2914fdff611ccc07d7896b5a0cd7f8a5cb3a06ab
Author: Tangquan Zheng <zhengtangquan@oppo.com>

mm: zsmalloc: support objects compressed based on multiple pages

This patch adds CONFIG_ZSMALLOC_MULTI_PAGES support to zsmalloc so it can
allocate and store compressed objects larger than PAGE_SIZE (up to
PAGE_SIZE << CONFIG_ZSMALLOC_MULTI_PAGES_ORDER) using higher-order
compound pages and additional multi-page size classes.

> diff --git a/Documentation/mm/zsmalloc.rst b/Documentation/mm/zsmalloc.rst
> index 8132cd70a61f2..283d22cb8abac 100644
> --- a/Documentation/mm/zsmalloc.rst
> +++ b/Documentation/mm/zsmalloc.rst

[ ... ]

> @@ -85,7 +98,9 @@ obj_used
>  pages_used
>  	the number of pages allocated for the class
>  pages_per_zspage
> -	the number of 0-order pages to make a zspage
> +	the number of pages (or higher-order allocation units) to make a zspage
> +objs_per_zspage
> +	the total number of objects that a single zspage of this class can hold
>  freeable
>  	the approximate number of pages class compaction can free

[Severity: Low]
Does this description of pages_per_zspage match what zs_stats_size_show()
prints?

zs_stats_size_show() outputs class_pages_per_zspage(class), which shifts
zpdescs_per_zspage by the class order and reports the total number of base
order-0 physical pages in a zspage rather than the count of higher-order
allocation units.

[ ... ]

> diff --git a/mm/zsmalloc.c b/mm/zsmalloc.c
> index f263bd2b8d468..171cb787fe6b5 100644
> --- a/mm/zsmalloc.c
> +++ b/mm/zsmalloc.c

[ ... ]

> @@ -115,7 +121,7 @@
>  
>  #define HUGE_BITS	1
>  #define FULLNESS_BITS	4
> -#define CLASS_BITS	8
> +#define CLASS_BITS	9
>  #define MAGIC_VAL_BITS	8

[Severity: Medium]
Does raising CLASS_BITS to 9 unnecessarily expand ZS_OBJ_CLASS_BITS to 10
bits and regress riscv64?

ZS_SIZE_CLASSES is at most 481 even with CONFIG_ZSMALLOC_MULTI_PAGES
enabled at order 3, which already fits in the existing 9-bit
CLASS_BITS + 1 field.  Unconditionally bumping CLASS_BITS to 9 increases
ZS_OBJ_CLASS_BITS to 10 bits even when CONFIG_ZSMALLOC_MULTI_PAGES is
disabled.

On riscv64 (56-bit physical addresses, 4 KiB pages, ZS_OBJ_PFN_SHIFT = 20),
this folds ZS_OBJ_CLASS_BITS to 0 for CONFIG_ZSMALLOC_CHAIN_SIZE in 9..16,
disabling the lockless class lookup in obj_class_get_and_lock() and forcing
every zs_free() and zs_rebind_handle() onto read_lock(&pool->lock).  With
the default chain size of 8, it shrinks ZS_OBJ_IDX_BITS from 11 to 10 and
inflates ZS_MIN_ALLOC_SIZE from 32 to 40 bytes.

[ ... ]

> +#ifdef CONFIG_ZSMALLOC_MULTI_PAGES
> +#define ZS_MULTI_PAGES_SIZE_CLASS_DELTA	(ZSMALLOC_MULTI_PAGES_SIZE >> (CLASS_BITS - 1))
> +#define ZS_MULTI_PAGES_SIZE_CLASSES	(DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - PAGE_SIZE, \
> +					      ZS_MULTI_PAGES_SIZE_CLASS_DELTA))
> +#define ZS_SIZE_CLASSES		(ZS_PAGE_SIZE_CLASSES + ZS_MULTI_PAGES_SIZE_CLASSES)
> +#else

[Severity: Medium]
Can appending these multi-page size classes cause zs_compact() to
repeatedly stall concurrent readers on empty classes?

zs_compact() iterates over all ZS_SIZE_CLASSES and calls __zs_compact()
for every distinct class, where __zs_compact() acquires
write_lock(&pool->lock) and spin_lock(&class->lock) before checking
zs_can_compact(class).  With CONFIG_ZSMALLOC_MULTI_PAGES enabled, every
pool (including zswap and 4 KiB-only zram pools) now takes
write_lock(&pool->lock) for each empty multi-page class, blocking
concurrent zs_obj_read_sg_begin() readers during reclaim or compaction.

Pre-checking zs_can_compact(class) before taking write_lock(&pool->lock),
as zs_shrinker_count() already does, would avoid these stalls.

[ ... ]

> @@ -1551,6 +1631,8 @@ static void zs_object_copy(struct size_class *class, unsigned long dst,
>  	struct zpdesc *s_zpdesc, *d_zpdesc;
>  	unsigned int s_objidx, d_objidx;
>  	unsigned long s_off, d_off;
> +	unsigned long page_size = class_size_to_zs_size(class->size);
> +	unsigned long page_mask = ~(page_size - 1);
>  	void *s_addr, *d_addr;
>  	int s_size, d_size, size;
>  	int written = 0;

[Severity: High]
Was zs_rebind_handle() missed when updating object offset calculations for
multi-page zpdescs?

mm/zsmalloc.c:zs_rebind_handle() {
    ...
	if (likely(!ZsHugePage(zspage))) {
		obj_to_location(obj, &zpdesc, &obj_idx);
		off = offset_in_page(class->size * obj_idx);
		vaddr = kmap_local_zpdesc(zpdesc);
		link = (struct link_free *)(vaddr + off);
		link->handle = (unsigned long)dst | OBJ_ALLOCATED_TAG;
		kunmap_local(vaddr);
	}
    ...
}

For any non-huge multi-page object whose offset within its compound zpdesc
is at least PAGE_SIZE, offset_in_page() wraps into the first base page,
corrupting 8 bytes of another object's data or header with the dst handle
address while leaving the real object header pointing to src.  If the
caller then frees src as documented on struct zs_handle, a subsequent
zs_compact() -> migrate_zspage() reads the stale src handle from the real
header, causing a use-after-free while leaving dst dangling.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261205021803.3704464-1-zhaonanzhe@xiaomi.com?part=1


^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [PATCH 2/4] zram: support compression at the granularity of multi-pages
  2026-12-05  2:18 ` [PATCH 2/4] zram: support compression at the granularity of multi-pages Nanzhe Zhao
@ 2026-12-06  2:20   ` sashiko-bot
  0 siblings, 0 replies; 8+ messages in thread
From: sashiko-bot @ 2026-12-06  2:20 UTC (permalink / raw)
  To: Nanzhe Zhao, Andrew Morton
  Cc: linux-mm, Jens Axboe, Sergey Senozhatsky, Minchan Kim,
	Kairui Song, Johannes Weiner, Nhat Pham, Usama Arif, Yosry Ahmed,
	Chengming Zhou, Chris Li, David Hildenbrand, Ying Huang,
	Suren Baghdasaryan, Ryan Roberts, Kanchana P Sridhar,
	Wajdi K Feghali, Bala Seshasayee, Nick Terrell, Barry Song,
	Tangquan Zheng, Bo Zhang

Thank you for your contribution! Sashiko AI review found 18 potential
issues to consider:
- [Critical] zram: lockless first-sector dispatch and missing recheck in
  zram_bio_read()
- [Critical] zram: stale ZRAM_COMP_MULTI_PAGES flags on fallback and
  single-page writes
- [Critical] zram: premature __slot_free() in partial multi-page write
  loses sibling data
- [Critical] zram: zram_slot_free_notify() frees live multi-page slot on
  cleared index
- [Critical] zram: self-deadlock on excl_lock in
  zram_read_partial_from_zspool()
- [High] zram: multi-page zram_write_page() leaks tail slots and stale
  flags on error
- [High] zram: non-atomic tail flag updates under head lock corrupt
  bit-lock
- [High] zram: TOCTOU wrong-slot lock and out-of-range frees in
  zram_bio_discard()
- [High] zram: REQ_OP_WRITE_ZEROES silently skips partial multi-page
  slots
- [High] zram: missing slot_lock() mode recheck causes TOCTOU races in
  read/write
- [Medium] zram: broken bi_vcnt check and bi_io_vec read in
  want_multi_pages_comp()
- [Medium] zram: sysfs io_stat and mm_stat miscounted for multi-page
  slots
- [Medium] zram: zram_write_page() holds slot_lock() across compression
- [Medium] zram: zram_read_partial_from_zspool() forces exclusive dstrm
  mode
- [Medium] zram: global atomic64_inc() stats in struct zram cause
  cacheline bouncing
- [Medium] zram: redundant second slot_lock() in multi-page bio read and
  write loops
- [Medium] zram: high-order GFP_NOIO allocation under slot_lock() in
  partial write
- [Medium] zram: missing head recheck after slot_trylock() in
  zram_slot_free_notify()
--

commit 640f4f78298a7b9bcecc7f76d3900db49be4d15d
Author: Tangquan Zheng <zhengtangquan@oppo.com>

zram: support compression at the granularity of multi-pages

This commit adds CONFIG_ZRAM_MULTI_PAGES to compress and decompress
multi-page chunks at ZSMALLOC_MULTI_PAGES_ORDER granularity, serializing
each multi-page window on the bit-lock of its aligned head slot.

> diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c
> index 95cec8b34239a..f2476ce6afa8d 100644
> --- a/drivers/block/zram/zram_drv.c
> +++ b/drivers/block/zram/zram_drv.c

[ ... ]

> +static void slot_free(struct zram *zram, unsigned long index)
> +{
> +#ifdef CONFIG_ZRAM_MULTI_PAGES
> +	unsigned long head = zram_multi_pages_head_index(index);
> +	int nr_pages = 1;
> +	int i;
> +
> +	/* Clear all slots' MULTI flags first. */
> +	if (__test_multi_pages_comp(zram, head)) {
> +		index = head;
> +		nr_pages = ZCOMP_MULTI_PAGES_NR;
> +		for (i = 0; i < nr_pages; i++)
> +			clear_slot_flag(zram, head + i, ZRAM_COMP_MULTI_PAGES);
> +	}
> +
> +	/*
> +	 * Then release the whole multi-page slot (by releasing the head
> +	 * slot's handle).
> +	 */
> +	__slot_free(zram, index, nr_pages);
> +
> +	/*
> +	 * Drop single-page objects left behind by a failed
> +	 * zram_slot_free_notify trylock.
> +	 */
> +	for (i = 1; i < nr_pages; i++)
> +		__slot_free(zram, index + i, 1);
> +#else
> +	__slot_free(zram, index, 1);
> +#endif
> +}

[Severity: High]
Can modifying tail slots' attr.flags and calling __slot_free() on tail
slots under only slot_lock(zram, head) corrupt tail bit-locks and race
with zs_free()?

In struct zram_table_entry, u32 attr.flags aliases the same word as
unsigned long __lock, where ZRAM_ENTRY_LOCK_BIT lives.  set_slots_multi_pages(),
slot_free(), zram_bvec_write_multi_pages_partial(), and
zram_slot_free_notify() all perform non-atomic read-modify-writes on
tail slots' attr.flags while holding only slot_lock(zram, head).

Meanwhile, mark_slots_idle() and zram_block_state_show() iterate every
index and acquire slot_lock(zram, tail) directly.  In addition,
slot_free() clears ZRAM_COMP_MULTI_PAGES on all slots before calling
__slot_free(zram, index + i, 1), allowing concurrent single-page I/O to
lock and modify tail slots at the same time:

CPU0                              CPU1
slot_lock(zram, head)
slot_free(zram, head)
  clear_slot_flag(tail, MULTI)
                                  slot_lock(zram, tail)
  __slot_free(zram, tail, 1)
    clear_slot_flag(tail, ...)
    zs_free(table[tail].handle)   <-- races on attr.flags / __lock & handle
                                  slot_unlock(zram, tail)

An interleaved non-atomic write to attr.flags can restore
ZRAM_ENTRY_LOCK_BIT to 1 after slot_unlock() (permanent deadlock) or
clear it while held, and unlocked __slot_free() can double-free or
use-after-free the zsmalloc handle.

[ ... ]

> -static int zram_read_page(struct zram *zram, struct page *page,
> -			  unsigned long index, struct bio *parent)
> +static int zram_read_page_size(struct zram *zram, struct page *page,
> +			       unsigned long index, struct bio *parent,
> +			       unsigned long page_size)
>  {
>  	int ret;
>  
>  	slot_lock(zram, index);
>  	mark_slot_accessed(zram, index);
>  	if (!test_slot_flag(zram, index, ZRAM_WB)) {
>  		/* Slot should be locked through out the function call */
> -		ret = read_from_zspool(zram, page, index);
> +		ret = read_from_zspool(zram, page, index, page_size);
>  		slot_unlock(zram, index);

[Severity: High]
Should zram_read_page_size(), zram_bvec_read_multi_pages_partial(), and
zram_write_page() recheck __test_multi_pages_comp() after acquiring
slot_lock()?

Unlike zram_bvec_write_multi_pages_partial(), none of these paths verify
under slot_lock() that the slot's single-page vs multi-page mode still
matches the lockless hint from zram_bio_read() or zram_bio_write():

CPU0                              CPU1
zram_bio_read()
  test_multi_pages_comp() -> true
                                  zram_bio_discard() -> slot_free(head)
                                  zram_write_page(head, PAGE_SIZE)
zram_read_page_size(head,
    ZCOMP_MULTI_PAGES_SIZE)
  slot_lock(zram, head)
  read_incompressible_page()
    zs_obj_read_sg_begin(...,     <-- NULL deref if 4 KiB ZRAM_HUGE
        ZCOMP_MULTI_PAGES_SIZE)

If table[head] was replaced by a single-page ZRAM_HUGE object,
zs_obj_read_sg_begin() takes the spanning branch where get_next_zpdesc()
returns NULL, causing a NULL pointer dereference in sg_copy_to_buffer().
In the reverse single-to-multi race, single-page reads on tail slots
return zeroes and single-page writes leave 4 KiB objects tagged with
ZRAM_COMP_MULTI_PAGES or race on tail slots' __lock.

[ ... ]

> -	zram_stat_add(zram, ZRAM_STAT_COMPR_DATA_SIZE, PAGE_SIZE);
> +	zram_stat_add(zram, ZRAM_STAT_COMPR_DATA_SIZE, page_size);
>  	zram_stat_add(zram, ZRAM_STAT_HUGE_PAGES, 1);
>  	zram_stat_add(zram, ZRAM_STAT_HUGE_PAGES_SINCE, 1);
> -	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, 1);
> +	zram_stat_add(zram, ZRAM_STAT_PAGES_STORED, nr_pages);

[Severity: Medium]
Should ZRAM_STAT_HUGE_PAGES and ZRAM_STAT_HUGE_PAGES_SINCE be updated by
nr_pages here (and in __slot_free()) instead of 1?

Documentation/admin-guide/blockdev/zram.rst defines both counters as the
number of incompressible pages, matching ZRAM_STAT_PAGES_STORED and
ZRAM_STAT_SAME_PAGES, so counting 1 underreports by ZCOMP_MULTI_PAGES_NR.

Three other stats have similar mismatches: zram_bio_read_multi_pages()
and zram_bio_write_multi_pages() do not increment zram->stats.failed_reads
and failed_writes (leaving io_stat at 0 on multi-page errors),
zram_bio_discard() adds 1 instead of page_size >> PAGE_SHIFT to
ZRAM_STAT_NOTIFY_FREE, and zram_slot_free_notify() increments
multi_pages_miss_free even when the contended slot is a single-page slot.

[ ... ]

> -	slot_lock(zram, index);
> -	slot_free(zram, index);
> +	__slot_free(zram, index, zram_slot_nr_pages(zram, index));
>  	ret = zs_store(zram->mem_pool, &zram->table[index].handle,
>  		       zstrm->buffer, comp_len,
>  		       GFP_NOIO | __GFP_NOWARN |
>  		       __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page));
>  	zcomp_cstrm_put(zstrm);
> -	if (ret) {
> -		slot_unlock(zram, index);
> +	if (ret)
>  		return ret;
> -	}

[Severity: High]
Can a full multi-page write in zram_write_page() leak leftover
single-page objects in tail slots and leave stale ZRAM_COMP_MULTI_PAGES
flags on error?

As slot_free() notes, failed zram_slot_free_notify() trylocks can leave
live single-page objects in tail slots index + 1 .. index + nr_pages - 1.
Because __zram_write_page(), write_same_filled_page(), and
write_incompressible_page() only call __slot_free() on index, those tail
objects remain allocated and double-counted in ZRAM_STAT_PAGES_STORED
and ZRAM_STAT_COMPR_DATA_SIZE across multi-page overwrites.

Also, if zs_store() fails after __slot_free() when overwriting a
multi-page slot, ZRAM_COMP_MULTI_PAGES remains set on the empty window,
so a later single-page write can enter zram_bvec_write_multi_pages_partial()
and leak a multi-page object whose unused sibling flags are never cleared.

> +static int zram_write_page(struct zram *zram, struct page *page,
> +			   unsigned long index, unsigned int page_size)
> +{
> +	int ret;
> +
> +	slot_lock(zram, index);
> +	ret = __zram_write_page(zram, page, index, page_size);
> +#ifdef CONFIG_ZRAM_MULTI_PAGES
> +	if (!ret && page_size > PAGE_SIZE)
> +		set_slots_multi_pages(zram, index, page_size >> PAGE_SHIFT);
> +#endif
> +	slot_unlock(zram, index);
> +
> +	return ret;
> +}

[Severity: Medium]
Does holding slot_lock() across page_same_filled(), zcomp_cstrm_get(),
and zcomp_compress() regress write-path lock contention even when
CONFIG_ZRAM_MULTI_PAGES is disabled?

Previously, zram_write_page() only acquired slot_lock() after
compression completed.  Holding slot_lock() while waiting on cstrm->lock
and compressing widens contention on the shared head slot and increases
dropped frees (miss_free) in zram_slot_free_notify().

[ ... ]

> +	offset = page_offset + ((index - head) << PAGE_SHIFT);
>  	if (offset) {
> -		if (n <= (PAGE_SIZE - offset))
> +		if (n <= page_size - offset) {
> +			slot_unlock(zram, head);
>  			goto end_bio;
> -
> -		n -= (PAGE_SIZE - offset);
> -		index++;
> +		}
> +		n -= page_size - offset;
> +		index = head + (page_size >> PAGE_SHIFT);
>  	}
> +	slot_unlock(zram, head);

[Severity: High]
Does skipping partial multi-page slots in zram_bio_discard() break
REQ_OP_WRITE_ZEROES?

When ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE, zram_add() sets
max_write_zeroes_sectors = UINT_MAX and zram_submit_bio() routes
REQ_OP_WRITE_ZEROES to zram_bio_discard().  Skipping leading (offset != 0)
or trailing (n < page_size) portions of a multi-page slot completes
REQ_OP_WRITE_ZEROES with BLK_STS_OK while leaving old non-zero data in
those 4 KiB-aligned sectors.

>  	while (n >= PAGE_SIZE) {
> -		slot_lock(zram, index);
> +		unsigned long head = zram_slot_head_index(zram, index);
> +		unsigned int page_size;
> +
> +		slot_lock(zram, head);
> +		page_size = zram_slot_page_size(zram, head);
> +		if (n < page_size) {
> +			/* the request ends inside this slot, leave it alone */
> +			slot_unlock(zram, head);
> +			break;
> +		}
>  		slot_free(zram, index);
> -		slot_unlock(zram, index);
> +		slot_unlock(zram, head);
>  		zram_stat_add(zram, ZRAM_STAT_NOTIFY_FREE, 1);
> -		index++;
> -		n -= PAGE_SIZE;
> +		index = head + (page_size >> PAGE_SHIFT);
> +		n -= page_size;
>  	}

[Severity: High]
Can the lockless head lookup in zram_bio_discard() lead to an unlocked
slot_free() or freeing slots outside the requested range?

In the while loop, head is computed before slot_lock(zram, head) and is
never revalidated against index under the lock:

CPU0 (discard starting at 6)      CPU1
zram_slot_head_index(zram, 6)
  -> head = 4 (multi-page 4..7)
                                  slot_free(4) (now single-page)
slot_lock(zram, 4)
page_size = PAGE_SIZE
slot_free(zram, 6)                <-- unlocked slot 6 (races with I/O)
slot_unlock(zram, 4)
index = 4 + 1 = 5                 <-- moves backwards before start

In the reverse single-to-multi race, head == 6 is locked while
slot_free(zram, 6) frees table[4].handle without holding slot_lock(4),
destroying live slots 4 and 5 before the discard range and skipping
slots 8 and 9.  The prologue above also only rechecks the multi-to-single
transition, not single-to-multi.

> +#ifdef CONFIG_ZRAM_MULTI_PAGES
> +
> +static inline bool want_multi_pages_comp(struct zram *zram, struct bio *bio)
> +{
> +	unsigned long index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
> +
> +	/*
> +	 * For a synchronous device such as zram, swap submits one bio with a
> +	 * single bvec that carries one folio.  Bios with more than one bvec
> +	 * are not supported.
> +	 */
> +	WARN_ON_ONCE(bio->bi_vcnt != 1);
> +
> +	if (bio->bi_io_vec->bv_len >= ZCOMP_MULTI_PAGES_SIZE)
> +		return true;
> +
> +	return !!__test_multi_pages_comp(zram, index);
> +}

[Severity: Medium]
Will WARN_ON_ONCE(bio->bi_vcnt != 1) fire on the first swap writeout?

swap_bdev_submit_write() initializes the bio with bio_init() (which sets
bio->bi_vcnt = 0) and populates bio->bi_iter.bi_size directly without
incrementing bi_vcnt:

mm/page_io.c:swap_bdev_submit_write() {
	...
	bio_init(bio, ctx->sis->bdev, sio->bvecs, ARRAY_SIZE(sio->bvecs),
			REQ_OP_WRITE | REQ_SWAP);
	bio->bi_iter.bi_size = sio->len;
	...
}

Reading bio->bi_io_vec->bv_len directly also ignores bio->bi_iter for
split, cloned, or multi-bvec bios, and not gating on REQ_SWAP or
alignment lets misaligned non-swap block writes enter the multi-page
write path and trigger the WARN_ON_ONCE() checks.

[ ... ]

> +		prio = get_slot_comp_priority(zram, index);
> +		zstrm = zcomp_dstrm_get(zram->comps[prio],
> +					ZCOMP_DSTRM_EXCLUSIVE);
> +		ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size,
> +				       zstrm->decomp_buf, page_size);
> +		if (!ret) {
> +			dst = kmap_local_page(bvec->bv_page);
> +			memcpy(dst + bvec->bv_offset,
> +			       zstrm->decomp_buf + offset, bvec->bv_len);
> +			kunmap_local(dst);
> +		}

[Severity: Critical]
Can zram_read_partial_from_zspool() self-deadlock on zstrm->excl_lock
with stateless decompression backends such as lzo-rle or lz4?

zcomp_dstrm_get(..., ZCOMP_DSTRM_EXCLUSIVE) returns with zstrm->excl_lock
held.  When the compressed object spans two physical pages in zsmalloc,
zcomp_decompress() checks !zcomp_shared_decomp(comp), which is false for
stateless backends (create_dctx == NULL), so it falls through to the
shared path:

drivers/block/zram/zcomp.c:zcomp_decompress() {
	...
	/* shared mode: try a per-request bounce buffer first */
	src = kmalloc(src_len, GFP_NOWAIT | __GFP_NOWARN);
	if (src) {
		ret = zcomp_decompress_buf(comp, zstrm, sg, src, &req);
		kfree(src);
		return ret;
	}

	/* fall back to ->local_copy serialized by ->excl_lock */
	mutex_lock(&zstrm->excl_lock);
	...
}

Under swap-in memory pressure, if the GFP_NOWAIT allocation fails,
zcomp_decompress() calls mutex_lock(&zstrm->excl_lock) while the current
task already holds it, hanging permanently while also holding slot_lock()
and the zspage read lock.

> +		zcomp_dstrm_put(zram->comps[prio], zstrm,
> +				ZCOMP_DSTRM_EXCLUSIVE);

[Severity: Medium]
Does unconditionally using ZCOMP_DSTRM_EXCLUSIVE here defeat shared
decompression on stateless backends during concurrent partial swap-ins?

Unlike read_compressed_page(), which uses ZCOMP_DSTRM_SHARED when
zcomp_shared_decomp() is true, ZCOMP_DSTRM_EXCLUSIVE scans all online
CPUs in zcomp_dstrm_excl_tryget() and sleeps on the global
comp->dstrm_waitq under contention.  Trying a temporary bounce buffer
with ZCOMP_DSTRM_SHARED and falling back to exclusive mode on allocation
failure would preserve shared decompression scalability.

[ ... ]

> +	slot_lock(zram, index);
> +	if (!__test_multi_pages_comp(zram, index)) {
> +		slot_unlock(zram, index);
> +		return -EAGAIN;
> +	}
> +	mark_slot_accessed(zram, index);
> +
> +	page = alloc_pages(GFP_NOIO | __GFP_COMP, ZCOMP_MULTI_PAGES_ORDER);

[Severity: Medium]
Can allocating a high-order GFP_NOIO page while holding slot_lock(zram,
index) stall sibling slots during direct compaction or reclaim?

The temporary page does not depend on the slot contents and could be
allocated before taking slot_lock() (as zram_bvec_write_partial() does),
freeing it on the -EAGAIN path.

> +	ret = read_from_zspool(zram, page, index, ZCOMP_MULTI_PAGES_SIZE);
> +	if (!ret) {
> +		src = kmap_local_page(bvec->bv_page);
> +		dst = kmap_local_page(page);
> +		memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
> +		kunmap_local(dst);
> +		kunmap_local(src);
> +
> +		atomic64_inc(&zram->stats.zram_bio_write_multi_pages_partial_count);
> +		ret = __zram_write_page(zram, page, index,
> +					ZCOMP_MULTI_PAGES_SIZE);

[Severity: Critical]
Does __zram_write_page() destroy untouched live sibling pages if
zs_store() fails with -ENOMEM during a partial multi-page write?

Both __zram_write_page() and write_incompressible_page() call
__slot_free() on table[index] before calling zs_store().  If zs_store()
fails under memory pressure, the old multi-page handle is already freed
while ZRAM_COMP_MULTI_PAGES remains set on live sibling slots, so those
sibling pages silently read back as all zeroes on later swap-in.
Storing into a temporary zs_handle before freeing the old handle would
avoid losing sibling data on allocation failure.

[ ... ]

> +		slot_lock(zram, index);
> +		mark_slot_accessed(zram, index);
> +		slot_unlock(zram, index);

[Severity: Medium]
Is this second slot_lock()/slot_unlock() round-trip in
zram_bio_read_multi_pages() (and the identical block in
zram_bio_write_multi_pages()) redundant?

zram_read_page_size(), zram_write_page(), and
zram_bvec_write_multi_pages_partial() already call mark_slot_accessed()
under slot_lock(), and zram_bvec_read_multi_pages_partial() already holds
slot_lock() and can call mark_slot_accessed() there.  Removing both
blocks halves head-slot lock traffic on every multi-page I/O.

[ ... ]

>  static void zram_bio_read(struct zram *zram, struct bio *bio)
>  {
> +	if (test_multi_pages_comp(zram, bio)) {
> +		zram_bio_read_multi_pages(zram, bio);
> +		return;
> +	}

[Severity: Critical]
Can dispatching the entire read bio from a lockless check of only the
first sector cause a NULL pointer dereference or leak stale plaintext
across processes?

A multi-window read bio that starts in a multi-page window and crosses
into a single-page window (or hits a concurrent replacement before
slot_lock()) enters zram_bio_read_multi_pages() without per-window
rechecks in zram_read_page_size() or zram_bvec_read_multi_pages_partial().

If a single-page ZRAM_HUGE slot is read with ZCOMP_MULTI_PAGES_SIZE,
zs_obj_read_sg_begin() calls get_next_zpdesc(), which returns NULL on a
single-zpdesc huge zspage, crashing in sg_copy_to_buffer().  If a partial
read hits a single-page compressed slot at head with offset >= PAGE_SIZE,
zcomp_decompress() writes only PAGE_SIZE bytes and returns 0, so
memcpy() from zstrm->decomp_buf + offset copies stale data from prior
decompressions on that CPU into the caller's page.

[ ... ]

> +static void zram_bio_write(struct zram *zram, struct bio *bio)
> +{
> +	unsigned long start_time = bio_start_io_acct(bio);
> +	int ret = -EAGAIN;
> +
> +	if (want_multi_pages_comp(zram, bio))
> +		ret = zram_bio_write_multi_pages(zram, bio);
> +
> +	/*
> +	 * If the multi-page slot has been freed, fall back to the single-page
> +	 * path.
> +	 */
> +	if (ret == -EAGAIN)
> +		ret = zram_bio_write_page(zram, bio);

[Severity: Critical]
Can falling back to zram_bio_write_page() on -EAGAIN (or any single-page
write hitting a multi-page slot) leave 4 KiB objects tagged with
ZRAM_COMP_MULTI_PAGES?

If a write bio larger than ZCOMP_MULTI_PAGES_SIZE has a trailing partial
chunk on a non-multi-page slot (for example, a 20 KiB write covering
slots 0..4), iteration 1 of zram_bio_write_multi_pages() commits a
multi-page object to slots 0..3 and iteration 2 returns -EAGAIN.
zram_bio_write() then replays the whole bio from slot 0 via
zram_bio_write_page().

In zram_write_page() with page_size == PAGE_SIZE, overwriting slot 0
calls __slot_free() without clearing ZRAM_COMP_MULTI_PAGES on slots 0..3,
leaving a 4 KiB object tagged as multi-page (which corrupts accounting
and later triggers NULL dereference or stale decomp_buf reads).  For tail
slots, zram_write_page() locks index instead of head, leaking the tail
handle while subsequent reads still consult table[head].

[ ... ]

> +#ifdef CONFIG_ZRAM_MULTI_PAGES
> +	{
> +		unsigned long head = zram_slot_head_index(zram, index);
> +
> +		/*
> +		 * Try to lock the head slot to serialize with concurrent
> +		 * slot_free().  On failure, skip this free, same as the
> +		 * single-page path.
> +		 */
> +		if (!slot_trylock(zram, head)) {
> +			atomic64_inc(&zram->stats.miss_free);
> +			atomic64_inc(&zram->stats.multi_pages_miss_free);
> +			return;
> +		}

[Severity: Medium]
Can zram_slot_free_notify() run __slot_free(zram, index, 1) without
holding slot_lock(zram, index) if head != index and the multi-page slot
is freed before slot_trylock(zram, head)?

Because BLKDISCARD and BLKZEROOUT do not check IS_SWAPFILE() or hold the
swap cluster lock, a concurrent discard on the swap device can clear
ZRAM_COMP_MULTI_PAGES in the window before slot_trylock(zram, head):

CPU0 (notify index = 1)           CPU1 (BLKDISCARD)
zram_slot_head_index(zram, 1)
  -> head = 0
                                  slot_lock(zram, 0)
                                  slot_free(zram, 0)
                                  slot_unlock(zram, 0)
slot_trylock(zram, 0) -> ok
__test_multi_pages_comp(0) == 0
slot_free(zram, 1)
  __slot_free(zram, 1, 1)         <-- unlocked non-atomic RMW on table[1]

Since table[1].attr.flags aliases table[1].__lock, racing with a
concurrent slot_lock(zram, 1) can corrupt or permanently stick the slot 1
bit-lock.  When head != index and __test_multi_pages_comp(zram, head) ==
0, zram_slot_free_notify() should unlock head and retry slot_trylock() on
index.

> +		if (__test_multi_pages_comp(zram, head) > 1) {
> +			clear_slot_flag(zram, index, ZRAM_COMP_MULTI_PAGES);
> +			slot_unlock(zram, head);
> +			return;
> +		}
> +
> +		/*
> +		 * Free the whole multi-page slot if this is the last slot
> +		 * holding the MULTI_PAGE flag.
> +		 */
> +		slot_free(zram, index);
> +		slot_unlock(zram, head);

[Severity: Critical]
Can zram_slot_free_notify() destroy a live sibling page when called for
an index whose ZRAM_COMP_MULTI_PAGES flag is already clear?

Suppose slots 0..3 hold a multi-page object and slots 1..3 are freed,
leaving ZRAM_COMP_MULTI_PAGES set only on live slot 0.  If swap reuses
slot 1 for a zero-filled folio (recorded in swap zeromap without writing
to zram) and later frees slot 1, swap_range_free() calls
zram_slot_free_notify(bdev, 1).

Because __test_multi_pages_comp(zram, 0) is 1 (belonging to slot 0) and
test_slot_flag(zram, index, ZRAM_COMP_MULTI_PAGES) is never checked,
execution falls through to slot_free(zram, 1), freeing table[0].handle so
live slot 0 silently reads back as all zeroes.

> diff --git a/drivers/block/zram/zram_drv.h b/drivers/block/zram/zram_drv.h
> index 1fbb00dc2c298..5969619129924 100644
> --- a/drivers/block/zram/zram_drv.h
> +++ b/drivers/block/zram/zram_drv.h

[ ... ]

>  struct zram_stats {
>  	atomic64_t failed_reads;	/* can happen when memory is too low */
>  	atomic64_t failed_writes;	/* can happen when memory is too low */
>  	atomic_long_t max_used_pages;	/* no. of maximum pages stored */
>  	atomic64_t miss_free;		/* no. of missed free */
>  #ifdef	CONFIG_ZRAM_WRITEBACK
>  	atomic64_t bd_count;		/* no. of pages in backing device */
>  	atomic64_t bd_reads;		/* no. of reads from backing device */
>  	atomic64_t bd_writes;		/* no. of writes from backing device */
>  #endif
> +#ifdef CONFIG_ZRAM_MULTI_PAGES
> +	atomic64_t zram_bio_write_multi_pages_count;
> +	atomic64_t zram_bio_read_multi_pages_count;
> +	atomic64_t multi_pages_failed_writes;
> +	atomic64_t multi_pages_failed_reads;
> +	atomic64_t zram_bio_write_multi_pages_partial_count;
> +	atomic64_t zram_bio_read_multi_pages_partial_count;
> +	atomic64_t multi_pages_miss_free;
> +#endif
>  };

[Severity: Medium]
Should the hot per-I/O multi-page counters live in struct zram_pcpu_stats
as local64_t instead of global atomic64_t fields in struct zram_stats?

Incrementing these shared counters on every multi-page read and write
dirties cachelines inside struct zram adjacent to max_used_pages,
pcpu_stats, limit_pages, and disksize, reintroducing the cross-CPU
cacheline bouncing that commit 7691f2fb29d7 ("zram: keep the hot
statistics per CPU") eliminated.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261205021803.3704464-1-zhaonanzhe@xiaomi.com?part=2


^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [PATCH 4/4] mm: swap: allow direct reclaim for synchronous multi-page swapin
  2026-12-05  2:18 ` [PATCH 4/4] mm: swap: allow direct reclaim for synchronous multi-page swapin Nanzhe Zhao
@ 2026-12-06  2:20   ` sashiko-bot
  0 siblings, 0 replies; 8+ messages in thread
From: sashiko-bot @ 2026-12-06  2:20 UTC (permalink / raw)
  To: Nanzhe Zhao, Andrew Morton
  Cc: linux-mm, Jens Axboe, Sergey Senozhatsky, Minchan Kim,
	Kairui Song, Johannes Weiner, Nhat Pham, Usama Arif, Yosry Ahmed,
	Chengming Zhou, Chris Li, David Hildenbrand, Ying Huang,
	Suren Baghdasaryan, Ryan Roberts, Kanchana P Sridhar,
	Wajdi K Feghali, Bala Seshasayee, Nick Terrell, Barry Song,
	Tangquan Zheng, Bo Zhang

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] mm: __swap_cache_alloc() overrides THP defrag policy for
  order-2 swapin
- [Medium] mm: __swap_cache_alloc() forces __GFP_NORETRY on
  MADV_HUGEPAGE order-2 swapin
- [Medium] mm: __swap_cache_alloc() hardcodes order 2 ignoring
  ZSMALLOC_MULTI_PAGES_ORDER
- [Medium] mm: __swap_cache_alloc() order-2 override diverges for shmem
  by CONFIG_NUMA
--

commit b74f743bdab4a09e250301d1a8c1e37d3a3a1a0c
Author: Nanzhe Zhao <zhaonanzhe@xiaomi.com>

mm: swap: allow direct reclaim for synchronous multi-page swapin

This commit adds __GFP_RECLAIM | __GFP_NORETRY to the gfp mask for order-2
allocations in __swap_cache_alloc() when allocating via vma_alloc_folio().

> diff --git a/mm/swap_state.c b/mm/swap_state.c
> index da65d75ceead1..0e703dcc42105 100644
> --- a/mm/swap_state.c
> +++ b/mm/swap_state.c
> @@ -462,6 +462,13 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
>  	if (mpol || !vmf) {
>  		folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id());
>  	} else {
> +		/*
> +		 * zsmalloc uses order-2 pages to store compressed data.
> +		 * Allow direct reclaim to improve allocation success and
> +		 * avoid partial reads.
> +		 */
> +		if (order == 2)
> +			gfp |= __GFP_RECLAIM | __GFP_NORETRY;
>  		address = round_down(vmf->address, PAGE_SIZE << order);
>  		folio = vma_alloc_folio(gfp, order, vmf->vma, address);
>  	}

[Severity: High]
Does unconditionally adding __GFP_RECLAIM here override the
transparent_hugepage/defrag policy from vma_thp_gfp_mask()?

Because order 2 is within PAGE_ALLOC_COSTLY_ORDER, __alloc_pages_slowpath()
keeps __GFP_DIRECT_RECLAIM despite __GFP_NORETRY.  Under defrag=never or on
non-MADV_HUGEPAGE VMAs, faults on any SWP_SYNCHRONOUS_IO device (such as
brd, pmem, or single-page zram) will stall in direct reclaim and compaction.

Using __GFP_RECLAIM also enables __GFP_KSWAPD_RECLAIM, which GFP_TRANSHUGE
omits.  Mutating gfp in place also passes __GFP_DIRECT_RECLAIM to the later
mem_cgroup_swapin_charge_folio() call, causing blocking memcg reclaim.

[Severity: Medium]
Can unconditionally ORing __GFP_NORETRY regress MADV_HUGEPAGE VMAs?

Under defrag=madvise, vma_thp_gfp_mask() returns GFP_TRANSHUGE without
__GFP_NORETRY for MADV_HUGEPAGE VMAs.  Forcing __GFP_NORETRY here makes
both __alloc_pages_slowpath() and try_charge_memcg() abort after a single
reclaim pass, increasing order-0 fallbacks and partial reads.

[Severity: Medium]
Should this avoid hardcoding order == 2 for zsmalloc in generic swap code?

CONFIG_ZSMALLOC_MULTI_PAGES_ORDER can be configured from 1 to 3, and zram's
is_multi_pages_partial_io() checks against ZCOMP_MULTI_PAGES_SIZE.  When
configured to order 1 or 3, the actual compression order gets no direct
reclaim while order 2 stalls unnecessarily and still incurs partial reads.

This also runs when CONFIG_ZRAM_MULTI_PAGES is disabled or on non-zram
synchronous devices, and assumes a 4 KiB PAGE_SIZE.  Querying a swap-device
or block-layer property would avoid coupling mm/swap_state.c to zsmalloc.

[Severity: Medium]
Why is this override placed in the else branch of if (mpol || !vmf), after
thp_shmem_limit_gfp_mask()?

In shmem_swap_alloc_folio(), shmem_get_pgoff_policy() is always non-NULL on
CONFIG_NUMA kernels (via get_task_policy()), so shmem always skips this
branch.  On !CONFIG_NUMA kernels it returns NULL, making shmem_fault()
diverge from both CONFIG_NUMA and non-fault shmem reads (vmf == NULL).

ORing __GFP_RECLAIM after thp_shmem_limit_gfp_mask() also breaks its
contract that the result never exceeds the caller's limit_gfp reclaim flags.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261205021803.3704464-1-zhaonanzhe@xiaomi.com?part=4


^ permalink raw reply	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2026-12-06  2:20 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-05  2:17 [RFC PATCH v5 0/4] zram/zsmalloc: multi-page compression for large folios Nanzhe Zhao
2026-12-05  2:18 ` [PATCH 1/4] mm: zsmalloc: support objects compressed based on multiple pages Nanzhe Zhao
2026-12-06  2:20   ` sashiko-bot
2026-12-05  2:18 ` [PATCH 2/4] zram: support compression at the granularity of multi-pages Nanzhe Zhao
2026-12-06  2:20   ` sashiko-bot
2026-12-05  2:18 ` [PATCH 3/4] zram: backend_zstd: use multi-page size for zstd parameter setup Nanzhe Zhao
2026-12-05  2:18 ` [PATCH 4/4] mm: swap: allow direct reclaim for synchronous multi-page swapin Nanzhe Zhao
2026-12-06  2:20   ` sashiko-bot

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.