mTHP-friendly compression in zsmalloc and zram based on multi-pages
Subsystems (6)
v3 cover mTHP-friendly compression in zsmalloc and zram based on multi-pages
From: Barry Song <[email protected]>
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.
For example, swapping out and swapping in 100MiB of typical anonymous data 100 times (with 16KB mTHP enabled) using zstd yields the following results:
w/o patches w/ patches swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%
I deliberately created a test case with intense swap thrashing. On my Intel i9 10-core, 20-thread PC, I imposed a 1GB memory limit on a memcg to compile the Linux kernel, intending to amplify swap activity and analyze its impact on system time. Using the ZSTD algorithm, my test script, which builds the kernel for five rounds, is as follows:
#!/bin/bash
echo never > /sys/kernel/mm/transparent_hugepage/hugepages-64kB/enabled echo never > /sys/kernel/mm/transparent_hugepage/hugepages-32kB/enabled echo always > /sys/kernel/mm/transparent_hugepage/hugepages-16kB/enabled echo never > /sys/kernel/mm/transparent_hugepage/hugepages-2048kB/enabled
vmstat_path="/proc/vmstat" thp_base_path="/sys/kernel/mm/transparent_hugepage"
read_values() {
pswpin=$(grep "pswpin" $vmstat_path | awk '{print $2}')
pswpout=$(grep "pswpout" $vmstat_path | awk '{print $2}')
pgpgin=$(grep "pgpgin" $vmstat_path | awk '{print $2}')
pgpgout=$(grep "pgpgout" $vmstat_path | awk '{print $2}')
swpout_64k=$(cat $thp_base_path/hugepages-64kB/stats/swpout 2>/dev/null || echo 0)
swpout_32k=$(cat $thp_base_path/hugepages-32kB/stats/swpout 2>/dev/null || echo 0)
swpout_16k=$(cat $thp_base_path/hugepages-16kB/stats/swpout 2>/dev/null || echo 0)
swpin_64k=$(cat $thp_base_path/hugepages-64kB/stats/swpin 2>/dev/null || echo 0)
swpin_32k=$(cat $thp_base_path/hugepages-32kB/stats/swpin 2>/dev/null || echo 0)
swpin_16k=$(cat $thp_base_path/hugepages-16kB/stats/swpin 2>/dev/null || echo 0)
echo "$pswpin $pswpout $swpout_64k $swpout_32k $swpout_16k $swpin_64k $swpin_32k $swpin_16k $pgpgin $pgpgout"
}for ((i=1; i<=5; i++))
do
echo
echo "*** Executing round $i ***"
make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- clean 1>/dev/null 2>/dev/null echo 3 > /proc/sys/vm/drop_caches
#kernel build
initial_values=($(read_values))
time systemd-run --scope -p MemoryMax=1G make ARCH=arm64 \
CROSS_COMPILE=aarch64-linux-gnu- vmlinux -j20 1>/dev/null 2>/dev/null
final_values=($(read_values)) echo "pswpin: $((final_values[0] - initial_values[0]))" echo "pswpout: $((final_values[1] - initial_values[1]))" echo "64kB-swpout: $((final_values[2] - initial_values[2]))" echo "32kB-swpout: $((final_values[3] - initial_values[3]))" echo "16kB-swpout: $((final_values[4] - initial_values[4]))" echo "64kB-swpin: $((final_values[5] - initial_values[5]))" echo "32kB-swpin: $((final_values[6] - initial_values[6]))" echo "pgpgin: $((final_values[8] - initial_values[8]))" echo "pgpgout: $((final_values[9] - initial_values[9]))"
done
****************** Test results
******* Without the patchset:
*** Executing round 1 ***
real 7m56.173s
user 81m29.401s
sys 42m57.470s
pswpin: 29815871
pswpout: 50548760
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11206086
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6596517
pgpgin: 146093656
pgpgout: 211024708
*** Executing round 2 ***
real 7m48.227s
user 81m20.558s
sys 43m0.940s
pswpin: 29798189
pswpout: 50882005
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11286587
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6596103
pgpgin: 146841468
pgpgout: 212374760
*** Executing round 3 ***
real 7m56.664s
user 81m10.936s
sys 43m5.991s
pswpin: 29760702
pswpout: 51230330
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11363346
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6586263
pgpgin: 145374744
pgpgout: 213355600
*** Executing round 4 ***
real 8m29.115s
user 81m18.955s
sys 42m49.050s
pswpin: 29651724
pswpout: 50631678
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11249036
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6583515
pgpgin: 145819060
pgpgout: 211373768
*** Executing round 5 ***
real 7m46.124s
user 80m29.780s
sys 41m37.005s
pswpin: 28805646
pswpout: 49570858
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11010873
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6391598
pgpgin: 142354376
pgpgout: 20713566
******* With the patchset:
*** Executing round 1 ***
real 7m43.760s
user 80m35.185s
sys 35m50.685s
pswpin: 29870407
pswpout: 50101263
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11140509
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6838090
pgpgin: 146500224
pgpgout: 209218896
*** Executing round 2 ***
real 7m31.820s
user 81m39.787s
sys 37m24.341s
pswpin: 31100304
pswpout: 51666202
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11471841
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 7106112
pgpgin: 151763112
pgpgout: 215526464
*** Executing round 3 ***
real 7m35.732s
user 79m36.028s
sys 34m4.190s
pswpin: 28357528
pswpout: 47716236
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 10619547
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6500899
pgpgin: 139903688
pgpgout: 199715908
*** Executing round 4 ***
real 7m38.242s
user 80m50.768s
sys 35m54.201s
pswpin: 29752937
pswpout: 49977585
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11117552
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6815571
pgpgin: 146293900
pgpgout: 208755500
*** Executing round 5 ***
real 8m2.692s
user 81m40.159s
sys 37m11.361s
pswpin: 30813683
pswpout: 51687672
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11481684
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 7044988
pgpgin: 150231840
pgpgout: 215616760
Although the real time fluctuated significantly on my PC, the sys time has clearly decreased from over 40 minutes to just over 30 minutes across all five rounds.
-v3:
* Added a patch to fall back to four smaller folios to avoid partial reads. discussed this option with Usama, Ying, and Nhat in v2. Not entirely sure it will be well-received, but I've done my best to minimize the complexity added to do_swap_page().
* Add a patch to adjust zstd backend estimated_src_size;
* Addressed one VM_WARN_ON in patch 1 for PageMovable();
-v2:
https://lore.kernel.org/linux-mm/[email protected]/
While it is not mature yet, I know some people are waiting for an update :-)
* Fixed some stability issues.
* rebase againest the latest mm-unstable.
* Set default order to 2 which benefits all anon mTHP.
* multipages ZsPageMovable is not supported yet.
Barry Song (2):
zram: backend_zstd: Adjust estimated_src_size to accommodate
multi-page compression
mm: fall back to four small folios if mTHP allocation fails
Tangquan Zheng (2):
mm: zsmalloc: support objects compressed based on multiple pages
zram: support compression at the granularity of multi-pages
drivers/block/zram/Kconfig | 9 + drivers/block/zram/backend_zstd.c | 6 +- drivers/block/zram/zcomp.c | 17 +- drivers/block/zram/zcomp.h | 12 +- drivers/block/zram/zram_drv.c | 450 ++++++++++++++++++++++++++++-- drivers/block/zram/zram_drv.h | 45 +++ include/linux/zsmalloc.h | 10 +- mm/Kconfig | 18 ++ mm/memory.c | 203 +++++++++++++- mm/zsmalloc.c | 235 ++++++++++++---- 10 files changed, 896 insertions(+), 109 deletions(-)
Signature · 1 line
2.39.3 (Apple Git-146)
RFC PATCH v3 1/4 mm: zsmalloc: support objects compressed based on multiple pages
From: Tangquan Zheng <[email protected]>
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.
--- drivers/block/zram/zram_drv.c | 3 +- include/linux/zsmalloc.h | 10 +- mm/Kconfig | 18 +++ mm/zsmalloc.c | 235 ++++++++++++++++++++++++++-------- 4 files changed, 207 insertions(+), 59 deletions(-)
drivers/block/zram/zram_drv.c +1 -2
@@ -1461,8 +1461,7 @@ 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); + huge_class_size =zs_huge_class_size (zram->mem_pool,0 );for (index =0 ; index < num_pages; index++)spin_lock_init (&zram->table[index].lock);
include/linux/zsmalloc.h +9 -1
@@ -33,6 +33,14 @@ enum zs_mapmode {*/ }; +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;
@@ -46,7 +54,7 @@ void zs_destroy_pool(struct zs_pool *pool);unsigned long zs_malloc (struct zs_pool *pool,size_t size,gfp_t flags);void zs_free (struct zs_pool *pool,unsigned long obj); -size_t zs_huge_class_size (struct zs_pool *pool); +size_t zs_huge_class_size (struct zs_pool *pool,enum zsmalloc_type type);void *zs_map_object (struct zs_pool *pool,unsigned long handle,enum zs_mapmode mm);
mm/Kconfig +18 -0
@@ -237,6 +237,24 @@ config ZSMALLOC_CHAIN_SIZE For more information, see zsmalloc documentation. +config ZSMALLOC_MULTI_PAGES + bool "support zsmalloc multiple pages" + depends on ZSMALLOC && !CONFIG_HIGHMEM + 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. + +config ZSMALLOC_MULTI_PAGES_ORDER + int "zsmalloc multiple pages order" + default 2 + range 1 9 + depends on ZSMALLOC_MULTI_PAGES + help + This option is used to configure zsmalloc to support the compression + of multiple pages. + menu "Slab allocator options" config SLUB
mm/zsmalloc.c +179 -56
538 lines not on this page · raw message
Signature · 1 line
2.39.3 (Apple Git-146)
Sergey Senozhatsky
maintainerRe: [PATCH RFC v3 1/4] mm: zsmalloc: support objects compressed based on multiple pages
mm/zsmalloc.c static inline bool obj_allocated(struct page *page, void *obj, · line 874
Quoted 5 lines · Barry Song
static void
reset_page(struct page *page)
{mm/zsmalloc.c +2
-1-__ClearPageMovable (page); +if (PageMovable (page)) +__ClearPageMovable (page);
A side note:
ERROR: modpost: "PageMovable" [mm/zsmalloc.ko] undefined!
Re: [PATCH RFC v3 1/4] mm: zsmalloc: support objects compressed based on multiple pages
Quoted 10 lines · Sergey Senozhatsky
mm/zsmalloc.c static inline bool obj_allocated(struct page *page, void *obj, · line 874
Quoted 5 lines · Barry Song
static void
reset_page(struct page *page)
{mm/zsmalloc.c +2
-1-__ClearPageMovable (page); +if (PageMovable (page)) +__ClearPageMovable (page);A side note:
ERROR: modpost: "PageMovable" [mm/zsmalloc.ko] undefined!
My mistake. It could be if (!__PageMovable(page)). Ideally, we should support movability for large block compression.
Thanks
Barry
RFC PATCH v3 2/4 zram: support compression at the granularity of multi-pages
In reply to Barry SongFrom: Tangquan Zheng <[email protected]>
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.
This modification will notably reduce CPU consumption and enhance compression ratios. The following data illustrates the time and compressed data for typical anonymous pages gathered from Android phones.
--- drivers/block/zram/Kconfig | 9 + drivers/block/zram/zcomp.c | 17 +- drivers/block/zram/zcomp.h | 12 +- drivers/block/zram/zram_drv.c | 449 +++++++++++++++++++++++++++++++--- drivers/block/zram/zram_drv.h | 45 ++++ 5 files changed, 495 insertions(+), 37 deletions(-)
drivers/block/zram/Kconfig +9 -0
@@ -145,3 +145,12 @@ 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 + 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.
drivers/block/zram/zcomp.c +11 -6
@@ -52,6 +52,11 @@ static void zcomp_strm_free(struct zcomp *comp, struct zcomp_strm *zstrm)static int zcomp_strm_init (struct zcomp *comp,struct zcomp_strm *zstrm) { +#ifdef CONFIG_ZRAM_MULTI_PAGES +unsigned long page_size =ZCOMP_MULTI_PAGES_SIZE ; +#else +unsigned long page_size =PAGE_SIZE ; +#endif int ret; ret = comp->ops->create_ctx (comp->params, &zstrm->ctx);
@@ -62,7 +67,7 @@ static int zcomp_strm_init(struct zcomp *comp, struct zcomp_strm *zstrm)* allocate 2 pages. 1 for compressed data, plus 1 extra for the * case when compressed size is larger than the original one */ - zstrm->buffer =vzalloc (2 *PAGE_SIZE ); + zstrm->buffer =vzalloc (2 * page_size);if (!zstrm->buffer) {zcomp_strm_free (comp, zstrm);return -ENOMEM ;
@@ -119,13 +124,13 @@ void zcomp_stream_put(struct zcomp *comp) }int zcomp_compress (struct zcomp *comp,struct zcomp_strm *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 = src_len *2 , };int ret;
@@ -136,13 +141,13 @@ int zcomp_compress(struct zcomp *comp, struct zcomp_strm *zstrm, }int zcomp_decompress (struct zcomp *comp,struct zcomp_strm *zstrm, -const void *src,unsigned int src_len,void *dst) +const void *src,unsigned int src_len,void *dst,unsigned int dst_len) {struct zcomp_req req = { .src = src, .dst = dst, .src_len = src_len, - .dst_len =PAGE_SIZE , + .dst_len = dst_len, };return comp->ops->decompress (comp->params, &zstrm->ctx, &req);
drivers/block/zram/zcomp.h +10 -2
@@ -30,6 +30,13 @@ 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) +#endif +struct zcomp_strm {local_lock_t lock;/* compression buffer */
@@ -80,8 +87,9 @@ struct zcomp_strm *zcomp_stream_get(struct zcomp *comp);void zcomp_stream_put (struct zcomp *comp);int zcomp_compress (struct zcomp *comp,struct zcomp_strm *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_strm *zstrm, -const void *src,unsigned int src_len,void *dst); +const void *src,unsigned int src_len,void *dst, +unsigned int dst_len);#endif /* _ZCOMP_H_ */
drivers/block/zram/zram_drv.c +420 -29
651 lines not on this page · raw message
drivers/block/zram/zram_drv.h +45 -0
74 lines not on this page · raw message
Signature · 1 line
2.39.3 (Apple Git-146)
RFC PATCH v3 3/4 zram: backend_zstd: Adjust estimated_src_size to accommodate multi-page compression
In reply to Barry SongFrom: Barry Song <[email protected]>
If we continue using PAGE_SIZE as the estimated_src_size, we won't benefit from the reduced CPU usage and improved compression ratio brought by larger block compression.
--- drivers/block/zram/backend_zstd.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/block/zram/backend_zstd.c +3 -3
@@ -70,12 +70,12 @@ static int zstd_setup_params(struct zcomp_params *params)if (params->level ==ZCOMP_PARAM_NO_LEVEL ) params->level =zstd_default_clevel (); - 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; - 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,
@@ -137,7 +137,7 @@ static int zstd_create(struct zcomp_params *params, struct zcomp_ctx *ctx) ctx->context = zctx;if (params->dict_sz ==0 ) { - prm =zstd_get_params (params->level,PAGE_SIZE ); + prm =zstd_get_params (params->level,ZCOMP_MULTI_PAGES_SIZE ); sz =zstd_cctx_workspace_bound (&prm.cParams); zctx->cctx_mem =vzalloc (sz);if (!zctx->cctx_mem)
Signature · 1 line
2.39.3 (Apple Git-146)
RFC PATCH v3 4/4 mm: fall back to four small folios if mTHP allocation fails
In reply to Barry SongFrom: Barry Song <[email protected]>
The swapfile can compress/decompress at 4 * PAGES granularity, reducing CPU usage and improving the compression ratio. However, if allocating an mTHP fails and we fall back to a single small folio, the entire large block must still be decompressed. This results in a 16 KiB area requiring 4 page faults, where each fault decompresses 16 KiB but retrieves only 4 KiB of data from the block. To address this inefficiency, we instead fall back to 4 small folios, ensuring that each decompression occurs only once.
Allowing swap_read_folio() to decompress and read into an array of 4 folios would be extremely complex, requiring extensive changes throughout the stack, including swap_read_folio, zeromap, zswap, and final swap implementations like zRAM. In contrast, having these components fill a large folio with 4 subpages is much simpler.
To avoid a full-stack modification, we introduce a per-CPU order-2 large folio as a buffer. This buffer is used for swap_read_folio(), after which the data is copied into the 4 small folios. Finally, in do_swap_page(), all these small folios are mapped.
--- mm/memory.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 192 insertions(+), 11 deletions(-)
mm/memory.c +192 -11
@@ -4042,6 +4042,15 @@ static struct folio *__alloc_swap_folio(struct vm_fault *vmf)return folio; } +#define BATCH_SWPIN_ORDER 2 +#define BATCH_SWPIN_COUNT (1 << BATCH_SWPIN_ORDER) +#define BATCH_SWPIN_SIZE (PAGE_SIZE << BATCH_SWPIN_ORDER) + +struct batch_swpin_buffer { +struct folio *folio; +struct mutex mutex; +}; +#ifdef CONFIG_TRANSPARENT_HUGEPAGE static inline int non_swapcache_batch (swp_entry_t entry,int max_nr) {
@@ -4120,7 +4129,101 @@ static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset,return orders; } -static struct folio *alloc_swap_folio (struct vm_fault *vmf) +static DEFINE_PER_CPU(struct batch_swpin_buffer, swp_buf); + +static int __init batch_swpin_buffer_init (void ) +{ +int ret, cpu; +struct batch_swpin_buffer *buf; + +for_each_possible_cpu (cpu) { + buf =per_cpu_ptr (&swp_buf, cpu); + buf->folio = (struct folio *)alloc_pages_node (cpu_to_node (cpu), +GFP_KERNEL | __GFP_COMP,BATCH_SWPIN_ORDER ); +if (!buf->folio) { + ret = -ENOMEM ; + goto err; + } +mutex_init (&buf->mutex); + } +return 0 ; + +err: +for_each_possible_cpu (cpu) { + buf =per_cpu_ptr (&swp_buf, cpu); +if (buf->folio) { +folio_put (buf->folio); + buf->folio =NULL ; + } + } +return ret; +} +core_initcall (batch_swpin_buffer_init); + +static struct folio *alloc_batched_swap_folios (struct vm_fault *vmf, +struct batch_swpin_buffer **buf,struct folio **folios, +swp_entry_t entry) +{ +unsigned long haddr =ALIGN_DOWN (vmf->address,BATCH_SWPIN_SIZE ); +struct batch_swpin_buffer *sbuf =raw_cpu_ptr (&swp_buf); +struct folio *folio = sbuf->folio; +unsigned long addr; +int i; + +if (unlikely (!folio)) +return NULL ; + +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) { + addr = haddr + i *PAGE_SIZE ; + folios[i] =vma_alloc_folio (GFP_HIGHUSER_MOVABLE ,0 , vmf->vma, addr); +if (!folios[i]) + goto err; +if (mem_cgroup_swapin_charge_folio (folios[i], vmf->vma->vm_mm, +GFP_KERNEL , entry)) + goto err; + } + +mutex_lock (&sbuf->mutex); + *buf = sbuf; +#ifdef CONFIG_MEMCG + folio->memcg_data = (*folios)->memcg_data; +#endif +return folio; + +err: +for (i--; i >=0 ; i--) +folio_put (folios[i]); +return NULL ; +} + +static void fill_batched_swap_folios (struct vm_fault *vmf, +void *shadow,struct batch_swpin_buffer *buf, +struct folio *folio,struct folio **folios) +{ +unsigned long haddr =ALIGN_DOWN (vmf->address,BATCH_SWPIN_SIZE ); +unsigned long addr; +int i; + +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) { + addr = haddr + i *PAGE_SIZE ; +__folio_set_locked (folios[i]); +__folio_set_swapbacked (folios[i]); +if (shadow) +workingset_refault (folios[i], shadow); +folio_add_lru (folios[i]); +copy_user_highpage (&folios[i]->page,folio_page (folio, i), + addr, vmf->vma); +if (folio_test_uptodate (folio)) +folio_mark_uptodate (folios[i]); + } + + folio->flags &= ~(PAGE_FLAGS_CHECK_AT_PREP & ~(1UL << PG_head)); +mutex_unlock (&buf->mutex); +} + +static struct folio *alloc_swap_folio (struct vm_fault *vmf, +struct batch_swpin_buffer **buf, +struct folio **folios) {struct vm_area_struct *vma = vmf->vma;unsigned long orders;
@@ -4180,6 +4283,9 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf)pte_unmap_unlock (pte, ptl); +if (!orders) + goto fallback; +/* Try allocating the highest of the remaining orders. */ gfp =vma_thp_gfp_mask (vma);while (orders) {
@@ -4194,14 +4300,29 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf) order = next_order(&orders, order); } +/* +* During swap-out, a THP might have been compressed into multiple +* order-2 blocks to optimize CPU usage and compression ratio. +* Attempt to batch swap-in 4 smaller folios to ensure they are +* decompressed together as a single unit only once. +*/ +return alloc_batched_swap_folios (vmf, buf, folios, entry); + fallback:return __alloc_swap_folio (vmf); }#else /* !CONFIG_TRANSPARENT_HUGEPAGE */ -static struct folio *alloc_swap_folio (struct vm_fault *vmf) +static struct folio *alloc_swap_folio (struct vm_fault *vmf, +struct batch_swpin_buffer **buf, +struct folio **folios) {return __alloc_swap_folio (vmf); } +static inline void fill_batched_swap_folios (struct vm_fault *vmf, +void *shadow,struct batch_swpin_buffer *buf, +struct folio *folio,struct folio **folios) +{ +}#endif /* CONFIG_TRANSPARENT_HUGEPAGE */ static DECLARE_WAIT_QUEUE_HEAD (swapcache_wq);
@@ -4216,6 +4337,8 @@ static DECLARE_WAIT_QUEUE_HEAD(swapcache_wq);*/ vm_fault_t do_swap_page (struct vm_fault *vmf) { +struct folio *folios[BATCH_SWPIN_COUNT ] = {NULL }; +struct batch_swpin_buffer *buf =NULL ;struct vm_area_struct *vma = vmf->vma;struct folio *swapcache, *folio =NULL ;DECLARE_WAITQUEUE (wait, current);
@@ -4228,7 +4351,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)pte_t pte;vm_fault_t ret =0 ;void *shadow =NULL ; -int nr_pages; +int nr_pages, i;unsigned long page_idx;unsigned long address;pte_t *ptep;
@@ -4296,7 +4419,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (data_race (si->flags &SWP_SYNCHRONOUS_IO ) &&__swap_count (entry) ==1 ) {/* skip swapcache */ - folio =alloc_swap_folio (vmf); + folio =alloc_swap_folio (vmf, &buf, folios);if (folio) {__folio_set_locked (folio);__folio_set_swapbacked (folio);
@@ -4327,10 +4450,10 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)mem_cgroup_swapin_uncharge_swap (entry, nr_pages); shadow =get_shadow_from_swap_cache (entry); -if (shadow) +if (shadow && !buf)workingset_refault (folio, shadow); - -folio_add_lru (folio); +if (!buf) +folio_add_lru (folio);/* To provide entry to swap_read_folio() */ folio->swap = entry;
@@ -4361,6 +4484,16 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)count_vm_event (PGMAJFAULT );count_memcg_event_mm (vma->vm_mm,PGMAJFAULT ); page =folio_file_page (folio,swp_offset (entry)); +/* +* Copy data into batched small folios from the large +* folio buffer +*/ +if (buf) { +fill_batched_swap_folios (vmf, shadow, buf, folio, folios); + folio = folios[0 ]; + page = &folios[0 ]->page; + goto do_map; + } }else if (PageHWPoison (page)) {/* * hwpoisoned dirty swapcache pages are kept for killing
@@ -4415,6 +4548,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)lru_add_drain (); } +do_map:folio_throttle_swaprate (folio,GFP_KERNEL );/*
@@ -4431,8 +4565,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) }/* allocated large folios for SWP_SYNCHRONOUS_IO */ -if (folio_test_large (folio) && !folio_test_swapcache (folio)) { -unsigned long nr =folio_nr_pages (folio); +if ((folio_test_large (folio) || buf) && !folio_test_swapcache (folio)) { +unsigned long nr = buf ?BATCH_SWPIN_COUNT :folio_nr_pages (folio);unsigned long folio_start =ALIGN_DOWN (vmf->address, nr *PAGE_SIZE );unsigned long idx = (vmf->address - folio_start) /PAGE_SIZE ;pte_t *folio_ptep = vmf->pte - idx;
@@ -4527,6 +4661,42 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) } } +/* Batched mapping of allocated small folios for SWP_SYNCHRONOUS_IO */ +if (buf) { +for (i =0 ; i < nr_pages; i++) +arch_swap_restore (swp_entry (swp_type (entry), +swp_offset (entry) + i), folios[i]); +swap_free_nr (entry, nr_pages); +add_mm_counter (vma->vm_mm,MM_ANONPAGES , nr_pages); +add_mm_counter (vma->vm_mm,MM_SWAPENTS , -nr_pages); + rmap_flags |=RMAP_EXCLUSIVE ; +for (i =0 ; i < nr_pages; i++) { +unsigned long addr = address + i *PAGE_SIZE ; + + pte =mk_pte (&folios[i]->page, vma->vm_page_prot); +if (pte_swp_soft_dirty (vmf->orig_pte)) + pte =pte_mksoft_dirty (pte); +if (pte_swp_uffd_wp (vmf->orig_pte)) + pte =pte_mkuffd_wp (pte); +if ((vma->vm_flags &VM_WRITE ) && !userfaultfd_pte_wp (vma, pte) && + !pte_needs_soft_dirty_wp (vma, pte)) { + pte =pte_mkwrite (pte, vma); +if ((vmf->flags &FAULT_FLAG_WRITE ) && (i == page_idx)) { + pte =pte_mkdirty (pte); + vmf->flags &= ~FAULT_FLAG_WRITE ; + } + } +flush_icache_page (vma, &folios[i]->page); +folio_add_new_anon_rmap (folios[i], vma, addr, rmap_flags); +set_pte_at (vma->vm_mm, addr, ptep + i, pte); +arch_do_swap_page_nr (vma->vm_mm, vma, addr, pte, pte,1 ); +if (i == page_idx) + vmf->orig_pte = pte; +folio_unlock (folios[i]); + } + goto wp_page; + } +/* * Some architectures may have to restore extra metadata to the page * when reading from swap. This metadata may be indexed by swap entry
@@ -4612,6 +4782,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)folio_put (swapcache); } +wp_page:if (vmf->flags &FAULT_FLAG_WRITE ) { ret |=do_wp_page (vmf);if (ret &VM_FAULT_ERROR )
@@ -4638,9 +4809,19 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (vmf->pte)pte_unmap_unlock (vmf->pte, vmf->ptl); out_page: -folio_unlock (folio); +if (!buf) { +folio_unlock (folio); + }else { +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) +folio_unlock (folios[i]); + } out_release: -folio_put (folio); +if (!buf) { +folio_put (folio); + }else { +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) +folio_put (folios[i]); + }if (folio != swapcache && swapcache) {folio_unlock (swapcache);folio_put (swapcache);
Signature · 1 line
2.39.3 (Apple Git-146)
Re: [PATCH RFC v3 4/4] mm: fall back to four small folios if mTHP allocation fails
Quoted 35 lines · Barry Song
From: Barry Song <[email protected]>
The swapfile can compress/decompress at 4 * PAGES granularity, reducing CPU usage and improving the compression ratio. However, if allocating an mTHP fails and we fall back to a single small folio, the entire large block must still be decompressed. This results in a 16 KiB area requiring 4 page faults, where each fault decompresses 16 KiB but retrieves only 4 KiB of data from the block. To address this inefficiency, we instead fall back to 4 small folios, ensuring that each decompression occurs only once.
Allowing
swap_read_folio()to decompress and read into an array of 4 folios would be extremely complex, requiring extensive changes throughout the stack, includingswap_read_folio, zeromap, zswap, and final swap implementations like zRAM. In contrast, having these components fill a large folio with 4 subpages is much simpler.To avoid a full-stack modification, we introduce a per-CPU order-2 large folio as a buffer. This buffer is used for
swap_read_folio(), after which the data is copied into the 4 small folios. Finally, indo_swap_page(), all these small folios are mapped.Co-developed-by Chuanhua Han <[email protected]>Signed-off-by Chuanhua Han <[email protected]>Signed-off-by Barry Song <[email protected]>--- mm/memory.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 192 insertions(+), 11 deletions(-)mm/memory.c +0
-0
mm/memory.c static struct folio *__alloc_swap_folio(struct vm_fault *vmf) · line 4045
Quoted 4 lines
mm/memory.c +1
-0@@ -4042,6 +4042,15 @@ static struct folio *__alloc_swap_folio(struct vm_fault *vmf)return folio; } +#define BATCH_SWPIN_ORDER 2
Hi Barry,
Thanks for the series and the numbers in the cover letter.
Just a few things.
Should BATCH_SWPIN_ORDER be ZSMALLOC_MULTI_PAGES_ORDER instead of 2?
Did you check the performance difference with and without patch 4?
I know that it wont help if you have a lot of unmovable pages scattered everywhere, but were you able to compare the performance of defrag=always vs patch 4? I feel like if you have space for 4 folios then hopefully compaction should be able to do its job and you can directly fill the large folio if the unmovable pages are better placed. Johannes' series on preventing type mixing [1] would help.
[1] https://lore.kernel.org/all/[email protected]/
Thanks,
Usama
Quoted 305 lines
mm/memory.c +191
-11+#define BATCH_SWPIN_COUNT (1 << BATCH_SWPIN_ORDER) +#define BATCH_SWPIN_SIZE (PAGE_SIZE << BATCH_SWPIN_ORDER) + +struct batch_swpin_buffer { +struct folio *folio; +struct mutex mutex; +}; +#ifdef CONFIG_TRANSPARENT_HUGEPAGE static inline int non_swapcache_batch (swp_entry_t entry,int max_nr) {@@ -4120,7 +4129,101 @@ static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset,return orders; } -static struct folio *alloc_swap_folio (struct vm_fault *vmf) +static DEFINE_PER_CPU(struct batch_swpin_buffer, swp_buf); + +static int __init batch_swpin_buffer_init (void ) +{ +int ret, cpu; +struct batch_swpin_buffer *buf; + +for_each_possible_cpu (cpu) { + buf =per_cpu_ptr (&swp_buf, cpu); + buf->folio = (struct folio *)alloc_pages_node (cpu_to_node (cpu), +GFP_KERNEL | __GFP_COMP,BATCH_SWPIN_ORDER ); +if (!buf->folio) { + ret = -ENOMEM ; + goto err; + } +mutex_init (&buf->mutex); + } +return 0 ; + +err: +for_each_possible_cpu (cpu) { + buf =per_cpu_ptr (&swp_buf, cpu); +if (buf->folio) { +folio_put (buf->folio); + buf->folio =NULL ; + } + } +return ret; +} +core_initcall (batch_swpin_buffer_init); + +static struct folio *alloc_batched_swap_folios (struct vm_fault *vmf, +struct batch_swpin_buffer **buf,struct folio **folios, +swp_entry_t entry) +{ +unsigned long haddr =ALIGN_DOWN (vmf->address,BATCH_SWPIN_SIZE ); +struct batch_swpin_buffer *sbuf =raw_cpu_ptr (&swp_buf); +struct folio *folio = sbuf->folio; +unsigned long addr; +int i; + +if (unlikely (!folio)) +return NULL ; + +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) { + addr = haddr + i *PAGE_SIZE ; + folios[i] =vma_alloc_folio (GFP_HIGHUSER_MOVABLE ,0 , vmf->vma, addr); +if (!folios[i]) + goto err; +if (mem_cgroup_swapin_charge_folio (folios[i], vmf->vma->vm_mm, +GFP_KERNEL , entry)) + goto err; + } + +mutex_lock (&sbuf->mutex); + *buf = sbuf; +#ifdef CONFIG_MEMCG + folio->memcg_data = (*folios)->memcg_data; +#endif +return folio; + +err: +for (i--; i >=0 ; i--) +folio_put (folios[i]); +return NULL ; +} + +static void fill_batched_swap_folios (struct vm_fault *vmf, +void *shadow,struct batch_swpin_buffer *buf, +struct folio *folio,struct folio **folios) +{ +unsigned long haddr =ALIGN_DOWN (vmf->address,BATCH_SWPIN_SIZE ); +unsigned long addr; +int i; + +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) { + addr = haddr + i *PAGE_SIZE ; +__folio_set_locked (folios[i]); +__folio_set_swapbacked (folios[i]); +if (shadow) +workingset_refault (folios[i], shadow); +folio_add_lru (folios[i]); +copy_user_highpage (&folios[i]->page,folio_page (folio, i), + addr, vmf->vma); +if (folio_test_uptodate (folio)) +folio_mark_uptodate (folios[i]); + } + + folio->flags &= ~(PAGE_FLAGS_CHECK_AT_PREP & ~(1UL << PG_head)); +mutex_unlock (&buf->mutex); +} + +static struct folio *alloc_swap_folio (struct vm_fault *vmf, +struct batch_swpin_buffer **buf, +struct folio **folios) {struct vm_area_struct *vma = vmf->vma;unsigned long orders;@@ -4180,6 +4283,9 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf)pte_unmap_unlock (pte, ptl); +if (!orders) + goto fallback; +/* Try allocating the highest of the remaining orders. */ gfp =vma_thp_gfp_mask (vma);while (orders) {@@ -4194,14 +4300,29 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf) order = next_order(&orders, order); } +/* +* During swap-out, a THP might have been compressed into multiple +* order-2 blocks to optimize CPU usage and compression ratio. +* Attempt to batch swap-in 4 smaller folios to ensure they are +* decompressed together as a single unit only once. +*/ +return alloc_batched_swap_folios (vmf, buf, folios, entry); + fallback:return __alloc_swap_folio (vmf); }#else /* !CONFIG_TRANSPARENT_HUGEPAGE */ -static struct folio *alloc_swap_folio (struct vm_fault *vmf) +static struct folio *alloc_swap_folio (struct vm_fault *vmf, +struct batch_swpin_buffer **buf, +struct folio **folios) {return __alloc_swap_folio (vmf); } +static inline void fill_batched_swap_folios (struct vm_fault *vmf, +void *shadow,struct batch_swpin_buffer *buf, +struct folio *folio,struct folio **folios) +{ +}#endif /* CONFIG_TRANSPARENT_HUGEPAGE */ static DECLARE_WAIT_QUEUE_HEAD (swapcache_wq);@@ -4216,6 +4337,8 @@ static DECLARE_WAIT_QUEUE_HEAD(swapcache_wq);*/ vm_fault_t do_swap_page (struct vm_fault *vmf) { +struct folio *folios[BATCH_SWPIN_COUNT ] = {NULL }; +struct batch_swpin_buffer *buf =NULL ;struct vm_area_struct *vma = vmf->vma;struct folio *swapcache, *folio =NULL ;DECLARE_WAITQUEUE (wait, current);@@ -4228,7 +4351,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)pte_t pte;vm_fault_t ret =0 ;void *shadow =NULL ; -int nr_pages; +int nr_pages, i;unsigned long page_idx;unsigned long address;pte_t *ptep;@@ -4296,7 +4419,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (data_race (si->flags &SWP_SYNCHRONOUS_IO ) &&__swap_count (entry) ==1 ) {/* skip swapcache */ - folio =alloc_swap_folio (vmf); + folio =alloc_swap_folio (vmf, &buf, folios);if (folio) {__folio_set_locked (folio);__folio_set_swapbacked (folio);@@ -4327,10 +4450,10 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)mem_cgroup_swapin_uncharge_swap (entry, nr_pages); shadow =get_shadow_from_swap_cache (entry); -if (shadow) +if (shadow && !buf)workingset_refault (folio, shadow); - -folio_add_lru (folio); +if (!buf) +folio_add_lru (folio);/* To provide entry to swap_read_folio() */ folio->swap = entry;@@ -4361,6 +4484,16 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)count_vm_event (PGMAJFAULT );count_memcg_event_mm (vma->vm_mm,PGMAJFAULT ); page =folio_file_page (folio,swp_offset (entry)); +/* +* Copy data into batched small folios from the large +* folio buffer +*/ +if (buf) { +fill_batched_swap_folios (vmf, shadow, buf, folio, folios); + folio = folios[0 ]; + page = &folios[0 ]->page; + goto do_map; + } }else if (PageHWPoison (page)) {/* * hwpoisoned dirty swapcache pages are kept for killing @@ -4415,6 +4548,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)lru_add_drain (); } +do_map:folio_throttle_swaprate (folio,GFP_KERNEL );/* @@ -4431,8 +4565,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) }/* allocated large folios for SWP_SYNCHRONOUS_IO */ -if (folio_test_large (folio) && !folio_test_swapcache (folio)) { -unsigned long nr =folio_nr_pages (folio); +if ((folio_test_large (folio) || buf) && !folio_test_swapcache (folio)) { +unsigned long nr = buf ?BATCH_SWPIN_COUNT :folio_nr_pages (folio);unsigned long folio_start =ALIGN_DOWN (vmf->address, nr *PAGE_SIZE );unsigned long idx = (vmf->address - folio_start) /PAGE_SIZE ;pte_t *folio_ptep = vmf->pte - idx;@@ -4527,6 +4661,42 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) } } +/* Batched mapping of allocated small folios for SWP_SYNCHRONOUS_IO */ +if (buf) { +for (i =0 ; i < nr_pages; i++) +arch_swap_restore (swp_entry (swp_type (entry), +swp_offset (entry) + i), folios[i]); +swap_free_nr (entry, nr_pages); +add_mm_counter (vma->vm_mm,MM_ANONPAGES , nr_pages); +add_mm_counter (vma->vm_mm,MM_SWAPENTS , -nr_pages); + rmap_flags |=RMAP_EXCLUSIVE ; +for (i =0 ; i < nr_pages; i++) { +unsigned long addr = address + i *PAGE_SIZE ; + + pte =mk_pte (&folios[i]->page, vma->vm_page_prot); +if (pte_swp_soft_dirty (vmf->orig_pte)) + pte =pte_mksoft_dirty (pte); +if (pte_swp_uffd_wp (vmf->orig_pte)) + pte =pte_mkuffd_wp (pte); +if ((vma->vm_flags &VM_WRITE ) && !userfaultfd_pte_wp (vma, pte) && + !pte_needs_soft_dirty_wp (vma, pte)) { + pte =pte_mkwrite (pte, vma); +if ((vmf->flags &FAULT_FLAG_WRITE ) && (i == page_idx)) { + pte =pte_mkdirty (pte); + vmf->flags &= ~FAULT_FLAG_WRITE ; + } + } +flush_icache_page (vma, &folios[i]->page); +folio_add_new_anon_rmap (folios[i], vma, addr, rmap_flags); +set_pte_at (vma->vm_mm, addr, ptep + i, pte); +arch_do_swap_page_nr (vma->vm_mm, vma, addr, pte, pte,1 ); +if (i == page_idx) + vmf->orig_pte = pte; +folio_unlock (folios[i]); + } + goto wp_page; + } +/* * Some architectures may have to restore extra metadata to the page * when reading from swap. This metadata may be indexed by swap entry @@ -4612,6 +4782,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)folio_put (swapcache); } +wp_page:if (vmf->flags &FAULT_FLAG_WRITE ) { ret |=do_wp_page (vmf);if (ret &VM_FAULT_ERROR )@@ -4638,9 +4809,19 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (vmf->pte)pte_unmap_unlock (vmf->pte, vmf->ptl); out_page: -folio_unlock (folio); +if (!buf) { +folio_unlock (folio); + }else { +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) +folio_unlock (folios[i]); + } out_release: -folio_put (folio); +if (!buf) { +folio_put (folio); + }else { +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) +folio_put (folios[i]); + }if (folio != swapcache && swapcache) {folio_unlock (swapcache);folio_put (swapcache);
Re: [PATCH RFC v3 4/4] mm: fall back to four small folios if mTHP allocation fails
Quoted 46 lines · Usama Arif
Quoted 35 lines · Barry Song
From: Barry Song <[email protected]>
The swapfile can compress/decompress at 4 * PAGES granularity, reducing CPU usage and improving the compression ratio. However, if allocating an mTHP fails and we fall back to a single small folio, the entire large block must still be decompressed. This results in a 16 KiB area requiring 4 page faults, where each fault decompresses 16 KiB but retrieves only 4 KiB of data from the block. To address this inefficiency, we instead fall back to 4 small folios, ensuring that each decompression occurs only once.
Allowing
swap_read_folio()to decompress and read into an array of 4 folios would be extremely complex, requiring extensive changes throughout the stack, includingswap_read_folio, zeromap, zswap, and final swap implementations like zRAM. In contrast, having these components fill a large folio with 4 subpages is much simpler.To avoid a full-stack modification, we introduce a per-CPU order-2 large folio as a buffer. This buffer is used for
swap_read_folio(), after which the data is copied into the 4 small folios. Finally, indo_swap_page(), all these small folios are mapped.Co-developed-by Chuanhua Han <[email protected]>Signed-off-by Chuanhua Han <[email protected]>Signed-off-by Barry Song <[email protected]>--- mm/memory.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 192 insertions(+), 11 deletions(-)mm/memory.c +0
-0mm/memory.c static struct folio *__alloc_swap_folio(struct vm_fault *vmf) · line 4045
Quoted 4 lines
mm/memory.c +1
-0@@ -4042,6 +4042,15 @@ static struct folio *__alloc_swap_folio(struct vm_fault *vmf)return folio; } +#define BATCH_SWPIN_ORDER 2Hi Barry,
Quoted 5 lines
Thanks for the series and the numbers in the cover letter.
Just a few things.
Should
BATCH_SWPIN_ORDERbeZSMALLOC_MULTI_PAGES_ORDERinstead of 2?
Technically, yes. I'm also considering removing ZSMALLOC_MULTI_PAGES_ORDER and always setting it to 2, which is the minimum anonymous mTHP order. The main reason is that it may be difficult for users to select the appropriate Kconfig?
On the other hand, 16KB provides the most advantages for zstd compression and decompression with larger blocks. While increasing from 16KB to 32KB or 64KB can offer additional benefits, the improvement is not as significant as the jump from
4KB to 16KB.
As I use zstd to compress and decompress the 'Beyond Compare' software package:
root@barry-desktop:~# ./zstd File size: 182502912 bytes 4KB Block: Compression time = 0.765915 seconds, Decompression time = 0.203366 seconds Original size: 182502912 bytes Compressed size: 66089193 bytes Compression ratio: 36.21% 16KB Block: Compression time = 0.558595 seconds, Decompression time = 0.153837 seconds Original size: 182502912 bytes Compressed size: 59159073 bytes Compression ratio: 32.42% 32KB Block: Compression time = 0.538106 seconds, Decompression time = 0.137768 seconds Original size: 182502912 bytes Compressed size: 57958701 bytes Compression ratio: 31.76% 64KB Block: Compression time = 0.532212 seconds, Decompression time = 0.127592 seconds Original size: 182502912 bytes Compressed size: 56700795 bytes Compression ratio: 31.07%
In that case, would we no longer need to rely on ZSMALLOC_MULTI_PAGES_ORDER?
Quoted 2 lines
Did you check the performance difference with and without patch 4?
I retested after reverting patch 4, and the sys time increased to over 40 minutes
again, though it was slightly better than without the entire series.
*** Executing round 1 ***
real 7m49.342s
user 80m53.675s
sys 42m28.393s
pswpin: 29965548
pswpout: 51127359
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11347712
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6641230
pgpgin: 147376000
pgpgout: 213343124
*** Executing round 2 ***
real 7m41.331s
user 81m16.631s
sys 41m39.845s
pswpin: 29208867
pswpout: 50006026
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11104912
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6483827
pgpgin: 144057340
pgpgout: 208887688
*** Executing round 3 ***
real 7m47.280s
user 78m36.767s
sys 37m32.210s
pswpin: 26426526
pswpout: 45420734
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 10104304
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 5884839
pgpgin: 132013648
pgpgout: 190537264
*** Executing round 4 ***
real 7m56.723s
user 80m36.837s
sys 41m35.979s
pswpin: 29367639
pswpout: 50059254
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11116176
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6514064
pgpgin: 144593828
pgpgout: 209080468
*** Executing round 5 ***
real 7m53.806s
user 80m30.953s
sys 40m14.870s
pswpin: 28091760
pswpout: 48495748
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 10779720
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6244819
pgpgin: 138813124
pgpgout: 202885480
I guess it is due to the occurrence of numerous partial reads (about 10%, 3505537/35159852).
root@barry-desktop:~# cat /sys/block/zram0/multi_pages_debug_stat
zram_bio write/read multi_pages count:54452828 35159852zram_bio failed write/read multi_pages count 0 0zram_bio partial write/read multi_pages count 4 3505537multi_pages_miss_free 0
This workload doesn't cause fragmentation in the buddy allocator, so it’s likely due to the failure of MEMCG_CHARGE.
Quoted 9 lines
I know that it wont help if you have a lot of unmovable pages scattered everywhere, but were you able to compare the performance of defrag=always vs patch 4? I feel like if you have space for 4 folios then hopefully compaction should be able to do its job and you can directly fill the large folio if the unmovable pages are better placed. Johannes' series on preventing type mixing [1] would help.
I believe this could help, but defragmentation is a complex issue. Especially on phones, where various components like drivers, DMA-BUF, multimedia, and graphics utilize memory.
We observed that a fresh system could initially provide mTHP, but after a few hours, obtaining mTHP became very challenging. I'm happy to arrange a test of Johannes' series on phones (sometimes it is quite hard to backport to the Android kernel) to see if it brings any improvements.
Quoted 301 lines
Thanks,
UsamaQuoted 297 lines
mm/memory.c +186
-11+#define BATCH_SWPIN_COUNT (1 << BATCH_SWPIN_ORDER) +#define BATCH_SWPIN_SIZE (PAGE_SIZE << BATCH_SWPIN_ORDER) + +struct batch_swpin_buffer { +struct folio *folio; +struct mutex mutex; +}; +#ifdef CONFIG_TRANSPARENT_HUGEPAGE static inline int non_swapcache_batch (swp_entry_t entry,int max_nr) {@@ -4120,7 +4129,101 @@ static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset,return orders; } -static struct folio *alloc_swap_folio (struct vm_fault *vmf) +static DEFINE_PER_CPU(struct batch_swpin_buffer, swp_buf); + +static int __init batch_swpin_buffer_init (void ) +{ +int ret, cpu; +struct batch_swpin_buffer *buf; + +for_each_possible_cpu (cpu) { + buf =per_cpu_ptr (&swp_buf, cpu); + buf->folio = (struct folio *)alloc_pages_node (cpu_to_node (cpu), +GFP_KERNEL | __GFP_COMP,BATCH_SWPIN_ORDER ); +if (!buf->folio) { + ret = -ENOMEM ; + goto err; + } +mutex_init (&buf->mutex); + } +return 0 ; + +err: +for_each_possible_cpu (cpu) { + buf =per_cpu_ptr (&swp_buf, cpu); +if (buf->folio) { +folio_put (buf->folio); + buf->folio =NULL ; + } + } +return ret; +} +core_initcall (batch_swpin_buffer_init); + +static struct folio *alloc_batched_swap_folios (struct vm_fault *vmf, +struct batch_swpin_buffer **buf,struct folio **folios, +swp_entry_t entry) +{ +unsigned long haddr =ALIGN_DOWN (vmf->address,BATCH_SWPIN_SIZE ); +struct batch_swpin_buffer *sbuf =raw_cpu_ptr (&swp_buf); +struct folio *folio = sbuf->folio; +unsigned long addr; +int i; + +if (unlikely (!folio)) +return NULL ; + +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) { + addr = haddr + i *PAGE_SIZE ; + folios[i] =vma_alloc_folio (GFP_HIGHUSER_MOVABLE ,0 , vmf->vma, addr); +if (!folios[i]) + goto err; +if (mem_cgroup_swapin_charge_folio (folios[i], vmf->vma->vm_mm, +GFP_KERNEL , entry)) + goto err; + } + +mutex_lock (&sbuf->mutex); + *buf = sbuf; +#ifdef CONFIG_MEMCG + folio->memcg_data = (*folios)->memcg_data; +#endif +return folio; + +err: +for (i--; i >=0 ; i--) +folio_put (folios[i]); +return NULL ; +} + +static void fill_batched_swap_folios (struct vm_fault *vmf, +void *shadow,struct batch_swpin_buffer *buf, +struct folio *folio,struct folio **folios) +{ +unsigned long haddr =ALIGN_DOWN (vmf->address,BATCH_SWPIN_SIZE ); +unsigned long addr; +int i; + +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) { + addr = haddr + i *PAGE_SIZE ; +__folio_set_locked (folios[i]); +__folio_set_swapbacked (folios[i]); +if (shadow) +workingset_refault (folios[i], shadow); +folio_add_lru (folios[i]); +copy_user_highpage (&folios[i]->page,folio_page (folio, i), + addr, vmf->vma); +if (folio_test_uptodate (folio)) +folio_mark_uptodate (folios[i]); + } + + folio->flags &= ~(PAGE_FLAGS_CHECK_AT_PREP & ~(1UL << PG_head)); +mutex_unlock (&buf->mutex); +} + +static struct folio *alloc_swap_folio (struct vm_fault *vmf, +struct batch_swpin_buffer **buf, +struct folio **folios) {struct vm_area_struct *vma = vmf->vma;unsigned long orders;@@ -4180,6 +4283,9 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf)pte_unmap_unlock (pte, ptl); +if (!orders) + goto fallback; +/* Try allocating the highest of the remaining orders. */ gfp =vma_thp_gfp_mask (vma);while (orders) {@@ -4194,14 +4300,29 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf) order = next_order(&orders, order); } +/* +* During swap-out, a THP might have been compressed into multiple +* order-2 blocks to optimize CPU usage and compression ratio. +* Attempt to batch swap-in 4 smaller folios to ensure they are +* decompressed together as a single unit only once. +*/ +return alloc_batched_swap_folios (vmf, buf, folios, entry); + fallback:return __alloc_swap_folio (vmf); }#else /* !CONFIG_TRANSPARENT_HUGEPAGE */ -static struct folio *alloc_swap_folio (struct vm_fault *vmf) +static struct folio *alloc_swap_folio (struct vm_fault *vmf, +struct batch_swpin_buffer **buf, +struct folio **folios) {return __alloc_swap_folio (vmf); } +static inline void fill_batched_swap_folios (struct vm_fault *vmf, +void *shadow,struct batch_swpin_buffer *buf, +struct folio *folio,struct folio **folios) +{ +}#endif /* CONFIG_TRANSPARENT_HUGEPAGE */ static DECLARE_WAIT_QUEUE_HEAD (swapcache_wq);@@ -4216,6 +4337,8 @@ static DECLARE_WAIT_QUEUE_HEAD(swapcache_wq);*/ vm_fault_t do_swap_page (struct vm_fault *vmf) { +struct folio *folios[BATCH_SWPIN_COUNT ] = {NULL }; +struct batch_swpin_buffer *buf =NULL ;struct vm_area_struct *vma = vmf->vma;struct folio *swapcache, *folio =NULL ;DECLARE_WAITQUEUE (wait, current);@@ -4228,7 +4351,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)pte_t pte;vm_fault_t ret =0 ;void *shadow =NULL ; -int nr_pages; +int nr_pages, i;unsigned long page_idx;unsigned long address;pte_t *ptep;@@ -4296,7 +4419,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (data_race (si->flags &SWP_SYNCHRONOUS_IO ) &&__swap_count (entry) ==1 ) {/* skip swapcache */ - folio =alloc_swap_folio (vmf); + folio =alloc_swap_folio (vmf, &buf, folios);if (folio) {__folio_set_locked (folio);__folio_set_swapbacked (folio);@@ -4327,10 +4450,10 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)mem_cgroup_swapin_uncharge_swap (entry, nr_pages); shadow =get_shadow_from_swap_cache (entry); -if (shadow) +if (shadow && !buf)workingset_refault (folio, shadow); - -folio_add_lru (folio); +if (!buf) +folio_add_lru (folio);/* To provide entry to swap_read_folio() */ folio->swap = entry;@@ -4361,6 +4484,16 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)count_vm_event (PGMAJFAULT );count_memcg_event_mm (vma->vm_mm,PGMAJFAULT ); page =folio_file_page (folio,swp_offset (entry)); +/* +* Copy data into batched small folios from the large +* folio buffer +*/ +if (buf) { +fill_batched_swap_folios (vmf, shadow, buf, folio, folios); + folio = folios[0 ]; + page = &folios[0 ]->page; + goto do_map; + } }else if (PageHWPoison (page)) {/* * hwpoisoned dirty swapcache pages are kept for killing @@ -4415,6 +4548,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)lru_add_drain (); } +do_map:folio_throttle_swaprate (folio,GFP_KERNEL );/* @@ -4431,8 +4565,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) }/* allocated large folios for SWP_SYNCHRONOUS_IO */ -if (folio_test_large (folio) && !folio_test_swapcache (folio)) { -unsigned long nr =folio_nr_pages (folio); +if ((folio_test_large (folio) || buf) && !folio_test_swapcache (folio)) { +unsigned long nr = buf ?BATCH_SWPIN_COUNT :folio_nr_pages (folio);unsigned long folio_start =ALIGN_DOWN (vmf->address, nr *PAGE_SIZE );unsigned long idx = (vmf->address - folio_start) /PAGE_SIZE ;pte_t *folio_ptep = vmf->pte - idx;@@ -4527,6 +4661,42 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) } } +/* Batched mapping of allocated small folios for SWP_SYNCHRONOUS_IO */ +if (buf) { +for (i =0 ; i < nr_pages; i++) +arch_swap_restore (swp_entry (swp_type (entry), +swp_offset (entry) + i), folios[i]); +swap_free_nr (entry, nr_pages); +add_mm_counter (vma->vm_mm,MM_ANONPAGES , nr_pages); +add_mm_counter (vma->vm_mm,MM_SWAPENTS , -nr_pages); + rmap_flags |=RMAP_EXCLUSIVE ; +for (i =0 ; i < nr_pages; i++) { +unsigned long addr = address + i *PAGE_SIZE ; + + pte =mk_pte (&folios[i]->page, vma->vm_page_prot); +if (pte_swp_soft_dirty (vmf->orig_pte)) + pte =pte_mksoft_dirty (pte); +if (pte_swp_uffd_wp (vmf->orig_pte)) + pte =pte_mkuffd_wp (pte); +if ((vma->vm_flags &VM_WRITE ) && !userfaultfd_pte_wp (vma, pte) && + !pte_needs_soft_dirty_wp (vma, pte)) { + pte =pte_mkwrite (pte, vma); +if ((vmf->flags &FAULT_FLAG_WRITE ) && (i == page_idx)) { + pte =pte_mkdirty (pte); + vmf->flags &= ~FAULT_FLAG_WRITE ; + } + } +flush_icache_page (vma, &folios[i]->page); +folio_add_new_anon_rmap (folios[i], vma, addr, rmap_flags); +set_pte_at (vma->vm_mm, addr, ptep + i, pte); +arch_do_swap_page_nr (vma->vm_mm, vma, addr, pte, pte,1 ); +if (i == page_idx) + vmf->orig_pte = pte; +folio_unlock (folios[i]); + } + goto wp_page; + } +/* * Some architectures may have to restore extra metadata to the page * when reading from swap. This metadata may be indexed by swap entry @@ -4612,6 +4782,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)folio_put (swapcache); } +wp_page:if (vmf->flags &FAULT_FLAG_WRITE ) { ret |=do_wp_page (vmf);if (ret &VM_FAULT_ERROR )@@ -4638,9 +4809,19 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)if (vmf->pte)pte_unmap_unlock (vmf->pte, vmf->ptl); out_page: -folio_unlock (folio); +if (!buf) { +folio_unlock (folio); + }else { +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) +folio_unlock (folios[i]); + } out_release: -folio_put (folio); +if (!buf) {
Quoted 9 lines
mm/memory.c vm_fault_t do_swap_page(struct vm_fault *vmf) · line 4827
Quoted 8 lines
mm/memory.c +5
-0+folio_put (folio); + }else { +for (i =0 ; i <BATCH_SWPIN_COUNT ; i++) +folio_put (folios[i]); + }if (folio != swapcache && swapcache) {folio_unlock (swapcache);folio_put (swapcache);
Thanks
Barry
Re: [PATCH RFC v3 4/4] mm: fall back to four small folios if mTHP allocation fails
Quoted 89 lines · Barry Song
Quoted 46 lines · Usama Arif
Quoted 35 lines · Barry Song
From: Barry Song <[email protected]>
The swapfile can compress/decompress at 4 * PAGES granularity, reducing CPU usage and improving the compression ratio. However, if allocating an mTHP fails and we fall back to a single small folio, the entire large block must still be decompressed. This results in a 16 KiB area requiring 4 page faults, where each fault decompresses 16 KiB but retrieves only 4 KiB of data from the block. To address this inefficiency, we instead fall back to 4 small folios, ensuring that each decompression occurs only once.
Allowing
swap_read_folio()to decompress and read into an array of 4 folios would be extremely complex, requiring extensive changes throughout the stack, includingswap_read_folio, zeromap, zswap, and final swap implementations like zRAM. In contrast, having these components fill a large folio with 4 subpages is much simpler.To avoid a full-stack modification, we introduce a per-CPU order-2 large folio as a buffer. This buffer is used for
swap_read_folio(), after which the data is copied into the 4 small folios. Finally, indo_swap_page(), all these small folios are mapped.Co-developed-by Chuanhua Han <[email protected]>Signed-off-by Chuanhua Han <[email protected]>Signed-off-by Barry Song <[email protected]>--- mm/memory.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 192 insertions(+), 11 deletions(-)mm/memory.c +0
-0mm/memory.c static struct folio *__alloc_swap_folio(struct vm_fault *vmf) · line 4045
Quoted 4 lines
mm/memory.c +1
-0@@ -4042,6 +4042,15 @@ static struct folio *__alloc_swap_folio(struct vm_fault *vmf)return folio; } +#define BATCH_SWPIN_ORDER 2Hi Barry,
Quoted 5 lines
Thanks for the series and the numbers in the cover letter.
Just a few things.
Should
BATCH_SWPIN_ORDERbeZSMALLOC_MULTI_PAGES_ORDERinstead of 2?Technically, yes. I'm also considering removing
ZSMALLOC_MULTI_PAGES_ORDERand always setting it to 2, which is the minimum anonymous mTHP order. The main reason is that it may be difficult for users to select the appropriateKconfig?On the other hand, 16KB provides the most advantages for zstd compression and decompression with larger blocks. While increasing from 16KB to 32KB or 64KB can offer additional benefits, the improvement is not as significant as the jump from
4KB to 16KB.As I use zstd to compress and decompress the 'Beyond Compare' software package:
root@barry-desktop:~# ./zstd File size: 182502912 bytes 4KB Block: Compression time = 0.765915 seconds, Decompression time = 0.203366 seconds Original size: 182502912 bytes Compressed size: 66089193 bytes Compression ratio: 36.21% 16KB Block: Compression time = 0.558595 seconds, Decompression time = 0.153837 seconds Original size: 182502912 bytes Compressed size: 59159073 bytes Compression ratio: 32.42% 32KB Block: Compression time = 0.538106 seconds, Decompression time = 0.137768 seconds Original size: 182502912 bytes Compressed size: 57958701 bytes Compression ratio: 31.76% 64KB Block: Compression time = 0.532212 seconds, Decompression time = 0.127592 seconds Original size: 182502912 bytes Compressed size: 56700795 bytes Compression ratio: 31.07%
Quoted 2 lines
In that case, would we no longer need to rely on
ZSMALLOC_MULTI_PAGES_ORDER?
Yes, I think if there isn't a very significant benefit of using a larger order, then its better not to have this option. It would also simplify the code.
Quoted 111 lines
Quoted 2 lines
Did you check the performance difference with and without patch 4?
I retested after reverting patch 4, and the sys time increased to over 40 minutes
again, though it was slightly better than without the entire series.*** Executing round 1 ***
real 7m49.342s
user 80m53.675s
sys 42m28.393s
pswpin: 29965548
pswpout: 51127359
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11347712
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6641230
pgpgin: 147376000
pgpgout: 213343124*** Executing round 2 ***
real 7m41.331s
user 81m16.631s
sys 41m39.845s
pswpin: 29208867
pswpout: 50006026
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11104912
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6483827
pgpgin: 144057340
pgpgout: 208887688*** Executing round 3 ***
real 7m47.280s
user 78m36.767s
sys 37m32.210s
pswpin: 26426526
pswpout: 45420734
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 10104304
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 5884839
pgpgin: 132013648
pgpgout: 190537264*** Executing round 4 ***
real 7m56.723s
user 80m36.837s
sys 41m35.979s
pswpin: 29367639
pswpout: 50059254
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11116176
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6514064
pgpgin: 144593828
pgpgout: 209080468*** Executing round 5 ***
real 7m53.806s
user 80m30.953s
sys 40m14.870s
pswpin: 28091760
pswpout: 48495748
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 10779720
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6244819
pgpgin: 138813124
pgpgout: 202885480I guess it is due to the occurrence of numerous partial reads (about 10%, 3505537/35159852).
root@barry-desktop:~# cat /sys/block/zram0/multi_pages_debug_stat
zram_biowrite/readmulti_pagescount:54452828 35159852zram_biofailed write/readmulti_pagescount 0 0zram_biopartial write/readmulti_pagescount 4 3505537multi_pages_miss_free0This workload doesn't cause fragmentation in the buddy allocator, so it’s likely due to the failure of
MEMCG_CHARGE.Quoted 9 lines
I know that it wont help if you have a lot of unmovable pages scattered everywhere, but were you able to compare the performance of defrag=always vs patch 4? I feel like if you have space for 4 folios then hopefully compaction should be able to do its job and you can directly fill the large folio if the unmovable pages are better placed. Johannes' series on preventing type mixing [1] would help.
Quoted 9 lines
I believe this could help, but defragmentation is a complex issue. Especially on phones, where various components like drivers, DMA-BUF, multimedia, and graphics utilize memory.
We observed that a fresh system could initially provide mTHP, but after a few hours, obtaining mTHP became very challenging. I'm happy to arrange a test of Johannes' series on phones (sometimes it is quite hard to backport to the Android kernel) to see if it brings any improvements.
I think its definitely worth trying. If we can improve memory allocation/compaction instead of patch 4, then we should go for that. Maybe there won't be a need for TAO if allocation is done in a smarter way?
Just out of curiosity, what is the base kernel version you are testing with?
Thanks,
Usama
Re: [PATCH RFC v3 4/4] mm: fall back to four small folios if mTHP allocation fails
Quoted 220 lines · Usama Arif
Quoted 89 lines · Barry Song
Quoted 46 lines · Usama Arif
Quoted 35 lines · Barry Song
From: Barry Song <[email protected]>
The swapfile can compress/decompress at 4 * PAGES granularity, reducing CPU usage and improving the compression ratio. However, if allocating an mTHP fails and we fall back to a single small folio, the entire large block must still be decompressed. This results in a 16 KiB area requiring 4 page faults, where each fault decompresses 16 KiB but retrieves only 4 KiB of data from the block. To address this inefficiency, we instead fall back to 4 small folios, ensuring that each decompression occurs only once.
Allowing
swap_read_folio()to decompress and read into an array of 4 folios would be extremely complex, requiring extensive changes throughout the stack, includingswap_read_folio, zeromap, zswap, and final swap implementations like zRAM. In contrast, having these components fill a large folio with 4 subpages is much simpler.To avoid a full-stack modification, we introduce a per-CPU order-2 large folio as a buffer. This buffer is used for
swap_read_folio(), after which the data is copied into the 4 small folios. Finally, indo_swap_page(), all these small folios are mapped.Co-developed-by Chuanhua Han <[email protected]>Signed-off-by Chuanhua Han <[email protected]>Signed-off-by Barry Song <[email protected]>--- mm/memory.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 192 insertions(+), 11 deletions(-)mm/memory.c +0
-0mm/memory.c static struct folio *__alloc_swap_folio(struct vm_fault *vmf) · line 4045
Quoted 4 lines
mm/memory.c +1
-0@@ -4042,6 +4042,15 @@ static struct folio *__alloc_swap_folio(struct vm_fault *vmf)return folio; } +#define BATCH_SWPIN_ORDER 2Hi Barry,
Quoted 5 lines
Thanks for the series and the numbers in the cover letter.
Just a few things.
Should
BATCH_SWPIN_ORDERbeZSMALLOC_MULTI_PAGES_ORDERinstead of 2?Technically, yes. I'm also considering removing
ZSMALLOC_MULTI_PAGES_ORDERand always setting it to 2, which is the minimum anonymous mTHP order. The main reason is that it may be difficult for users to select the appropriateKconfig?On the other hand, 16KB provides the most advantages for zstd compression and decompression with larger blocks. While increasing from 16KB to 32KB or 64KB can offer additional benefits, the improvement is not as significant as the jump from
4KB to 16KB.As I use zstd to compress and decompress the 'Beyond Compare' software package:
root@barry-desktop:~# ./zstd File size: 182502912 bytes 4KB Block: Compression time = 0.765915 seconds, Decompression time = 0.203366 seconds Original size: 182502912 bytes Compressed size: 66089193 bytes Compression ratio: 36.21% 16KB Block: Compression time = 0.558595 seconds, Decompression time = 0.153837 seconds Original size: 182502912 bytes Compressed size: 59159073 bytes Compression ratio: 32.42% 32KB Block: Compression time = 0.538106 seconds, Decompression time = 0.137768 seconds Original size: 182502912 bytes Compressed size: 57958701 bytes Compression ratio: 31.76% 64KB Block: Compression time = 0.532212 seconds, Decompression time = 0.127592 seconds Original size: 182502912 bytes Compressed size: 56700795 bytes Compression ratio: 31.07%Quoted 2 lines
In that case, would we no longer need to rely on
ZSMALLOC_MULTI_PAGES_ORDER?Yes, I think if there isn't a very significant benefit of using a larger order, then its better not to have this option. It would also simplify the code.
Quoted 111 lines
Quoted 2 lines
Did you check the performance difference with and without patch 4?
I retested after reverting patch 4, and the sys time increased to over 40 minutes
again, though it was slightly better than without the entire series.*** Executing round 1 ***
real 7m49.342s
user 80m53.675s
sys 42m28.393s
pswpin: 29965548
pswpout: 51127359
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11347712
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6641230
pgpgin: 147376000
pgpgout: 213343124*** Executing round 2 ***
real 7m41.331s
user 81m16.631s
sys 41m39.845s
pswpin: 29208867
pswpout: 50006026
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11104912
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6483827
pgpgin: 144057340
pgpgout: 208887688*** Executing round 3 ***
real 7m47.280s
user 78m36.767s
sys 37m32.210s
pswpin: 26426526
pswpout: 45420734
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 10104304
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 5884839
pgpgin: 132013648
pgpgout: 190537264*** Executing round 4 ***
real 7m56.723s
user 80m36.837s
sys 41m35.979s
pswpin: 29367639
pswpout: 50059254
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 11116176
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6514064
pgpgin: 144593828
pgpgout: 209080468*** Executing round 5 ***
real 7m53.806s
user 80m30.953s
sys 40m14.870s
pswpin: 28091760
pswpout: 48495748
64kB-swpout: 0
32kB-swpout: 0
16kB-swpout: 10779720
64kB-swpin: 0
32kB-swpin: 0
16kB-swpin: 6244819
pgpgin: 138813124
pgpgout: 202885480I guess it is due to the occurrence of numerous partial reads (about 10%, 3505537/35159852).
root@barry-desktop:~# cat /sys/block/zram0/multi_pages_debug_stat
zram_biowrite/readmulti_pagescount:54452828 35159852zram_biofailed write/readmulti_pagescount 0 0zram_biopartial write/readmulti_pagescount 4 3505537multi_pages_miss_free0This workload doesn't cause fragmentation in the buddy allocator, so it’s likely due to the failure of
MEMCG_CHARGE.Quoted 9 lines
I know that it wont help if you have a lot of unmovable pages scattered everywhere, but were you able to compare the performance of defrag=always vs patch 4? I feel like if you have space for 4 folios then hopefully compaction should be able to do its job and you can directly fill the large folio if the unmovable pages are better placed. Johannes' series on preventing type mixing [1] would help.
Quoted 9 lines
I believe this could help, but defragmentation is a complex issue. Especially on phones, where various components like drivers, DMA-BUF, multimedia, and graphics utilize memory.
We observed that a fresh system could initially provide mTHP, but after a few hours, obtaining mTHP became very challenging. I'm happy to arrange a test of Johannes' series on phones (sometimes it is quite hard to backport to the Android kernel) to see if it brings any improvements.
Quoted 5 lines
I think its definitely worth trying. If we can improve memory allocation/compaction instead of patch 4, then we should go for that. Maybe there won't be a need for TAO if allocation is done in a smarter way?
Just out of curiosity, what is the base kernel version you are testing with?
This kernel build testing was conducted on my Intel PC running mm-unstable, which includes Johannes' series. As mentioned earlier, it still shows many partial
reads without patch 4.
For phones, we have to backport to android kernel such as 6.6, 6.1 etc:
https://android.googlesource.com/kernel/common/+refs
Testing new patchset can sometimes be quite a pain ....
Quoted 3 lines
Thanks,
Usama
Thanks
Barry
Sergey Senozhatsky
maintainerQuoted 11 lines · Barry Song
When large folios are compressed at a larger granularity, we observe a notable reduction in CPU usage and a significant improvement in compression ratios.
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_pages4KiB blocks.The granularity can be set using the
ZSMALLOC_MULTI_PAGES_ORDERsetting, where the default of 2 allows all anonymous THP to benefit.
I can't say that I'm in love with this part.
Looking at zsmalloc stats, your new size-classes are significantly further apart from each other than our tradition size classes. For example, with ZSMALLOC_CHAIN_SIZE of 10, some size-classes are more than 400 (that's almost 10% of PAGE_SIZE) bytes apart
// stripped
344 9792
348 10048
351 10240
353 10368
355 10496
361 10880
368 11328
370 11456
373 11648
377 11904
383 12288
387 12544
390 12736
395 13056
400 13376
404 13632
410 14016
415 14336
Which means that every objects of size, let's say, 10881 will go into 11328 size class and have 447 bytes of padding between each object.
And with ZSMALLOC_CHAIN_SIZE of 8, it seems, we have even larger padding gaps:
// stripped
348 10048
351 10240
353 10368
361 10880
370 11456
373 11648
377 11904
383 12288
390 12736
395 13056
404 13632
410 14016
415 14336
418 14528
447 16384
E.g. 13632 and 13056 are more than 500 bytes apart.
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%
These are not the only numbers to focus on, really important metrics
are: zsmalloc pages-used and zsmalloc max-pages-used. Then we can calculate the pool memory usage ratio (the size of compressed data vs the number of pages zsmalloc pool allocated to keep them).
More importantly, dealing with internal fragmentation in a size-class, let's say, of 14528 will be a little painful, as we'll need to move around 14K objects.
As, for the speed part, well, it's a little unusual to see that you are focusing on zstd. zstd is slower than any from the lzX family, sort of a fact, zstsd sports better compression ratio, but is slower. Do you use zstd in your smartphones? If speed is your main metrics, another option might be to just use a faster algorithm and then utilize post-processing (re-compression with zstd or writeback) for memory savings?
Do you happen to have some data (pool memory usage ratio, etc.) for lzo or lzo-rle, or lz4?
Sergey Senozhatsky
maintainerQuoted 3 lines · Sergey Senozhatsky
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%
I'm also sort of curious if you'd use zstd with pre-trained user dictionary [1] (e.g. based on a dump of your swap-file under most common workloads) would it give you desired compression ratio improvements (on current zram, that does single page compression).
[1] https://github.com/facebook/zstd?tab=readme-ov-file#the-case-for-small-data-compression
Quoted 6 lines · Sergey Senozhatsky
Quoted 3 lines · Sergey Senozhatsky
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%
Quoted 6 lines
I'm also sort of curious if you'd use zstd with pre-trained user dictionary [1] (e.g. based on a dump of your swap-file under most common workloads) would it give you desired compression ratio improvements (on current zram, that does single page compression).
[1] https://github.com/facebook/zstd?tab=readme-ov-file#the-case-for-small-data-compression
Not yet, but it might be worth trying. A key difference between servers and Android phones is that phones have millions of different applications downloaded from the Google Play Store or other sources. In this case, would using a dictionary be a feasible approach? Apologies if my question seems too naive.
On the other hand, the advantage of a pre-trained user dictionary doesn't outweigh the
benefits of large block compression? Can’t both be used together?
Thanks
Barry
Sergey Senozhatsky
maintainerQuoted 13 lines · Barry Song
Quoted 11 lines · Sergey Senozhatsky
Quoted 3 lines · Sergey Senozhatsky
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%I'm also sort of curious if you'd use zstd with pre-trained user dictionary [1] (e.g. based on a dump of your swap-file under most common workloads) would it give you desired compression ratio improvements (on current zram, that does single page compression).
Quoted 5 lines
Quoted 1 line
[1] https://github.com/facebook/zstd?tab=readme-ov-file#the-case-for-small-data-compression
Not yet, but it might be worth trying. A key difference between servers and Android phones is that phones have millions of different applications downloaded from the Google Play Store or other sources.
Maybe yes maybe not, I don't know. It could be that that 99% of users use the same 1% apps out of those millions.
Quoted 2 lines
In this case, would using a dictionary be a feasible approach? Apologies if my question seems too naive.
It's a good question, and there is probably only one way to answer it - through experiments, it's data dependent, so it's case-by-case.
Quoted 3 lines
On the other hand, the advantage of a pre-trained user dictionary doesn't outweigh the benefits of large block compression? Can’t both be used together?
Well, so far the approach has many unmeasured unknowns and corner cases, I don't think I personally even understand all of them to begin with. Not sure if I have a way to measure and analyze, that mTHP swapout seems like a relatively new thing and it also seems that you are still fixing some of its issues/shortcomings.
Quoted 21 lines · Sergey Senozhatsky
Quoted 13 lines · Barry Song
Quoted 11 lines · Sergey Senozhatsky
Quoted 3 lines · Sergey Senozhatsky
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%I'm also sort of curious if you'd use zstd with pre-trained user dictionary [1] (e.g. based on a dump of your swap-file under most common workloads) would it give you desired compression ratio improvements (on current zram, that does single page compression).
Quoted 5 lines
Quoted 1 line
[1] https://github.com/facebook/zstd?tab=readme-ov-file#the-case-for-small-data-compression
Not yet, but it might be worth trying. A key difference between servers and Android phones is that phones have millions of different applications downloaded from the Google Play Store or other sources.
Quoted 8 lines
Maybe yes maybe not, I don't know. It could be that that 99% of users use the same 1% apps out of those millions.
Quoted 2 lines
In this case, would using a dictionary be a feasible approach? Apologies if my question seems too naive.
It's a good question, and there is probably only one way to answer it - through experiments, it's data dependent, so it's case-by-case.
Sure, we may collect data on the most popular apps (e.g., the top 100) and train zstd using their anonymous data to identify patterns. We’ll follow up with you afterward.
Quoted 7 lines
Quoted 4 lines
On the other hand, the advantage of a pre-trained user dictionary doesn't outweigh the benefits of large block compression? Can’t both be used together?
Well, so far the approach has many unmeasured unknowns and corner cases, I don't think I personally even understand all of them to begin
I agree we can make an effort to dig deeper and collect more data, analyzing as many corner cases as possible but many unknowns are a common characteristic of new things :-)
Quoted 3 lines
with. Not sure if I have a way to measure and analyze, that mTHP swapout seems like a relatively new thing and it also seems that you are still fixing some of its issues/shortcomings.
A challenge is determining how to make mTHP fully transparent (e.g., not dependent
on sysfs controls for enabling/disabling) across various workloads. The default policy
may not always be optimal for all workloads.
Despite that, there are certainly benefits we can gain from mTHP within zsmalloc/zram.
Thanks
Barry
Quoted 67 lines · Sergey Senozhatsky
Quoted 11 lines · Barry Song
When large folios are compressed at a larger granularity, we observe a notable reduction in CPU usage and a significant improvement in compression ratios.
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_pages4KiB blocks.The granularity can be set using the
ZSMALLOC_MULTI_PAGES_ORDERsetting, where the default of 2 allows all anonymous THP to benefit.I can't say that I'm in love with this part.
Looking at zsmalloc stats, your new size-classes are significantly further apart from each other than our tradition size classes. For example, with
ZSMALLOC_CHAIN_SIZEof 10, some size-classes are more than 400 (that's almost 10% ofPAGE_SIZE) bytes apart// stripped
344 9792
348 10048
351 10240
353 10368
355 10496
361 10880
368 11328
370 11456
373 11648
377 11904
383 12288
387 12544
390 12736
395 13056
400 13376
404 13632
410 14016
415 14336Which means that every objects of size, let's say, 10881 will go into 11328 size class and have 447 bytes of padding between each object.
And with
ZSMALLOC_CHAIN_SIZEof 8, it seems, we have even larger padding gaps:// stripped
348 10048
351 10240
353 10368
361 10880
370 11456
373 11648
377 11904
383 12288
390 12736
395 13056
404 13632
410 14016
415 14336
418 14528
447 16384E.g. 13632 and 13056 are more than 500 bytes apart.
Quoted 8 lines
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%These are not the only numbers to focus on, really important metrics
are: zsmalloc pages-used and zsmalloc max-pages-used. Then we can calculate the pool memory usage ratio (the size of compressed data vs the number of pages zsmalloc pool allocated to keep them).
To address this, we plan to collect more data and get back to you afterwards. From my understanding, we still have an opportunity to refine the CHAIN SIZE?
Essentially, each small object might cause some waste within the original PAGE_SIZE. Now, with 4 * PAGE_SIZE, there could be a single instance of waste. If we can manage the ratio, this could be optimized?
Quoted 9 lines
More importantly, dealing with internal fragmentation in a size-class, let's say, of 14528 will be a little painful, as we'll need to move around 14K objects.
As, for the speed part, well, it's a little unusual to see that you are focusing on zstd. zstd is slower than any from the lzX family, sort of a fact, zstsd sports better compression ratio, but is slower. Do you use zstd in your smartphones? If speed is your main metrics,
Yes, essentially, zstd is too slow. However, with mTHP and this patch set, the swap-out/swap-in bandwidth has significantly improved. As a result, we are now using zstd directly on phones with two zRAM devices:
zRAM0: swap-out/swap-in small folios using lz4;
zRAM1: swap-out/swap-in large folios using zstd
Without large folios, the latency of zstd for small folios is unacceptable, which
is why zRAM0 uses lz4. On the other hand, zRAM1 strikes a balance by combining the acceptable speed of large folios with the memory savings provided by zstd.
Quoted 3 lines
another option might be to just use a faster algorithm and then utilize post-processing (re-compression with zstd or writeback) for memory savings?
The concern lies in power consumption, as re-compression would require decompressing LZ4 and recompressing it into Zstd. Mobile phones are particularly sensitive to both power consumption and standby time.
On the other hand, I don’t see any conflict between recompression and the large block compression proposed by this patchset. Even during recompression, the advantages of large block compression can be utilized to enhance speed.
Writeback is another approach we are exploring. The main concern is that it might require swapping in data from backend block devices. We need to ensure that only truly cold data is stored there; otherwise, it could significantly
impact app launch times when an app transitions from the background to the foreground.
Quoted 3 lines
Do you happen to have some data (pool memory usage ratio, etc.) for lzo or lzo-rle, or lz4?
TBH, I don't, because the current use case involves using zstd for large folios, which is our main focus. We are not using lzo or lz4 for large folios, but I can definitely collect some data on that.
Thanks
Barry
Sergey Senozhatsky
maintainerOn (24/11/27 09:20), Barry Song wrote:
[..]
Quoted 14 lines
Quoted 14 lines
390 12736 395 13056 404 13632 410 14016 415 14336 418 14528 447 16384E.g. 13632 and 13056 are more than 500 bytes apart.
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%
Quoted 8 lines
Quoted 4 lines
These are not the only numbers to focus on, really important metrics
are: zsmalloc pages-used and zsmalloc max-pages-used. Then we can calculate the pool memory usage ratio (the size of compressed data vs the number of pages zsmalloc pool allocated to keep them).To address this, we plan to collect more data and get back to you afterwards. From my understanding, we still have an opportunity to refine the CHAIN SIZE?
Do you mean changing the value? It's configurable.
Quoted 4 lines
Essentially, each small object might cause some waste within the original
PAGE_SIZE. Now, with 4 *PAGE_SIZE, there could be a single instance of waste. If we can manage the ratio, this could be optimized?
All size classes work the same and we merge size-classes with equal characteristics. So in the example above
395 13056 404 13632
size-classes #396-403 are merged with size-class #404. And #404 size-class splits zspage into 13632-byte chunks, any smaller objects (e.g. an object from size-class #396 (which can be just one byte larger than #395 objects)) takes that entire chunk and the rest of the space in the chunk is just padding.
CHAIN_SIZE is how we find the optimal balance. The larger the zspage the more likely we squeeze some space for extra objects, which otherwise would have been just a waste. With large CHAIN_SIZE we also change characteristics of many size classes so we merge less classes and have more clusters. The price, on the other hand, is more physical 0-order pages per zspage, which can be painful. On all the tests I ran 8 or 10 worked best.
[..]
Quoted 5 lines
Quoted 3 lines
another option might be to just use a faster algorithm and then utilize post-processing (re-compression with zstd or writeback) for memory savings?
The concern lies in power consumption
But the power consumption concern is also in "decompress just one middle page from very large object" case, and size-classes de-fragmentation which requires moving around lots of objects in order to form more full zspage and release empty zspages. There are concerns everywhere, how many of them are measured and analyzed and either ruled out or confirmed is another question.
Quoted 45 lines · Sergey Senozhatsky
On (24/11/27 09:20), Barry Song wrote:
[..]Quoted 14 lines
Quoted 14 lines
390 12736 395 13056 404 13632 410 14016 415 14336 418 14528 447 16384E.g. 13632 and 13056 are more than 500 bytes apart.
Quoted 3 lines
swap-out time(ms) 68711 49908 swap-in time(ms) 30687 20685 compression ratio 20.49% 16.9%Quoted 8 lines
Quoted 4 lines
These are not the only numbers to focus on, really important metrics
are: zsmalloc pages-used and zsmalloc max-pages-used. Then we can calculate the pool memory usage ratio (the size of compressed data vs the number of pages zsmalloc pool allocated to keep them).To address this, we plan to collect more data and get back to you afterwards. From my understanding, we still have an opportunity to refine the CHAIN SIZE?
Do you mean changing the value? It's configurable.
Quoted 4 lines
Essentially, each small object might cause some waste within the original
PAGE_SIZE. Now, with 4 *PAGE_SIZE, there could be a single instance of waste. If we can manage the ratio, this could be optimized?All size classes work the same and we merge size-classes with equal characteristics. So in the example above
395 13056 404 13632size-classes #396-403 are merged with size-class #404. And #404 size-class splits zspage into 13632-byte chunks, any smaller objects (e.g. an object from size-class #396 (which can be just one byte larger than #395 objects)) takes that entire chunk and the rest of the space in the chunk is just padding.
Quoted 7 lines
CHAIN_SIZEis how we find the optimal balance. The larger the zspage the more likely we squeeze some space for extra objects, which otherwise would have been just a waste. With largeCHAIN_SIZEwe also change characteristics of many size classes so we merge less classes and have more clusters. The price, on the other hand, is more physical 0-order pages per zspage, which can be painful. On all the tests I ran 8 or 10 worked best.
Thanks very much for the explanation. We’ll gather more data on this and follow up with you.
Quoted 10 lines
[..]
Quoted 5 lines
Quoted 3 lines
another option might be to just use a faster algorithm and then utilize post-processing (re-compression with zstd or writeback) for memory savings?
The concern lies in power consumption
But the power consumption concern is also in "decompress just one middle page from very large object" case, and size-classes de-fragmentation
That's why we have "[patch 4/4] mm: fall back to four small folios if mTHP allocation fails" to address the issue of "decompressing just one middle page from a very large object." I assume that recompression and writeback should also focus on large objects if the original compression involves multiple pages?
Quoted 2 lines
which requires moving around lots of objects in order to form more full zspage and release empty zspages. There are concerns everywhere, how
I assume the cost of defragmentation is M * N, where:
* M is the number of objects,
* N is the size of the objects.
With large objects, M is reduced to 1/4 of the original number of objects. Although
N increases, the overall M * N becomes slightly smaller than before, as N is just
under 4 times the size of the original objects?
Quoted 2 lines
many of them are measured and analyzed and either ruled out or confirmed is another question.
In phone scenarios, if recompression uses zstd and the original compression is based on lz4 with 4KB blocks, the cost to obtain zstd-compressed objects would be:
* A: Compression of 4 × 4KB using lz4
* B: Decompression of 4 × 4KB using lz4
* C: Compression of 4 × 4KB using zstd
By leveraging the speed advantages of mTHP swap and zstd's large-block compression,
the cost becomes:
D: Compression of 16KB using zstd
Since D is significantly smaller than C (D < C), it follows that:
D < A + B + C ?
Thanks
Barry