From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.52 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796103457; b=eUw2+OppXzeqhNxTweMAi62eO2oBq6sjc1PPfXIsfgI3f6zxWvUOrEz/Ja0niwaQ+jbl h8+08qG4UAJmg9OzLvMX1U7hIIrKemkrRwDQPBBhqHQ4OK2bMdsBCoFby2ASUkwydc1tl gm4zS69iUPseVDyxUNmrdUma5gu1Iq1i3X41wNd05kFCdxeHsqaAvk0gVV14Z/bANzcR8 mZXqDad7oHh4d0BBLA6Dt7BEvsbrYokzNroZ1fD2EQuB7tlGNiszOzoOryNBNjMVXK/Ug LMCpOBjv0RH6STZ3hoTtDu5VjkKeGxjak1ugl459/vwEappnCi5ZzDEkBQIzrTbDxYA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796103457; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Gm-Gg:X-Received:Received: From:To:Cc:Subject:Date:Message-Id:X-Mailer:In-Reply-To:References: MIME-Version:Content-Transfer-Encoding; bh=5Tqn7M9FANDx7ekHFDSCWG5rQ5nyBB0rhYYrOaq6j1M=; b=CqCrY8yKC5Q6IhHaSCR0ca9TYZVhLSfYI0wRL2IJNRPaD/IVD5PL9KjgU96gdH8VxKTA JHB3WLC1WWdSgaPCy03cB+fAncZbl5CmHtBWD7Pm7lpHRk/XgJGF1HDDDh2E3e7bwHvQs oEHg/octLWE3Qswg0rPXtWFFJYFn2+kJKKA9DZq//CPtcpREBs4Sv98bpSBystdospqw+ woNpQI3hYhOLpPzca7tjAXCtOUO0f3vSuolJTnGDV5Fw7yfxv5d/nkHWZsEkVRwluET9a ouetk5j62Lbg/sjBp5hqUkCqevjxd5fV4aVNKqyHPMgyI24npsuy45rHKJUcjdH4hVw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=bTyfMajp; arc=none smtp.remote-ip=74.125.82.52 Received: from mail-dl1-f52.google.com (mail-dl1-f52.google.com [74.125.82.52]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 7AAAE606A6B5 for ; Tue, 1 Dec 2026 05:37:36 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 7AAAE606A6B5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=bTyfMajp Received: by mail-dl1-f52.google.com with SMTP id a92af1059eb24-1b5b93bdc2dso1894537c88.0 for ; Mon, 30 Nov 2026 21:37:36 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796103456; x=1796708256; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=5Tqn7M9FANDx7ekHFDSCWG5rQ5nyBB0rhYYrOaq6j1M=; b=bTyfMajpWXaljukiLcVTkxw3fVsi/QdLZdDz3Q/h4YUARM9s6xDAmJupx3OLncHOhj 0+5OoYkZOLB7LMLiwXmRbe7eC+cwWIWnEyMgfTz/lT6J/QyegdFnehG1Cpf6GAMGeQI5 FnQgQsNF0AU40myvJ1ty+fLPzw6Mt7g76Xk645tz0qlnDc0uSAkTMwOzVjn0ZMQc9xer qHwLuuyOlUjAeJG+qyRVi62VH0jEUOtWLWTjycAedyYkcYeXcmyo4U+0Ch33iVSSB6mZ tFJdAwfybfzsaYzQ2JRUT8wpl2AIwA/y+DXKv/JkqpACFx8iPpwQEBAuI98irLud3Tik HGPw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796103456; x=1796708256; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=5Tqn7M9FANDx7ekHFDSCWG5rQ5nyBB0rhYYrOaq6j1M=; b=ehjvGvmHzbqRALMABjjfbQFrf7TGWXHyimyvvfOT6bBrbiLL7m9hzJpBLkN8MPIwKW SKiROEmtTvLF2sWgFTJuebOFHI+S4LR01GITuUAh7puC7JBYMNECV6BvfemUDuGQ4Qlw st7geinxulbLVCLijXMHkOrfS+4e/yiBn64XqDDAq+CfEOLk9xSOo1ddOYe2iU1tBf9X jdTguIml6OYevbxDVFukFM7BNn7z8a+8SoqeW4g+g1OHy0sdYH0ApnDRhSISlTgjVRRb WmtyIkmrua6m80LgOw73aMU5ZNAHrzDI4q2x7caoKcX0fUWStGFYpEpDUvi4ggQ6k0h0 B4/Q== X-Forwarded-Encrypted: i=1; AL+hErEorm03bGZ8o1EjY3ole305sj5w1QK4xboYa6aYmi5bHjhSR3EpyL0H/pNxxKwE1PFe1LdgJs3NwlQDLgw=@vger.kernel.org X-Gm-Message-State: APuU4Z9qRvLf4CZgPYly4uMZWZmL33s+4HpzyxHIWS4Q6KIkf10iIq1S g26ZHtvyATy6uHgm0hLopIA71da+y+G2/5G6IvRXB1+awX0NnCLVtaBm X-Gm-Gg: AZFdTZeYOJBfQVoHHbrabVYbiflVJFXcKeIZVJ4zCQcXzMxmdvTNgTfcPmGo34wObt4 bNPEIQRiBrVIYbsc8YKCsYVxEKplo508mykbSK5ZSIP/sTsiGgv8v0YtiZBq+fv6Ap/7vqZjEN4 Iqw1o6yn3Pk+TGvGrcvamSUi6lpK9ia7zPA6uAlaTKtZY/Ur+gf+xkdAQtxv8ioJ53JqnjbYCPx YMQumjzB1u/8xmHECrXCfAWfvBqF8Y2weaemilghAx2fnVNUJqw9sQME0xSVZcFaYtODswDAIAs f7+heSTqxN8CVlEK/lzdMAeKDUU11CtqBcj2kjAdj7jj5O8wr4Qk4B0EgX1/K7MKlrQoPKMqrK2 G6rVV2GmlezCLv4Zfh4pMUhi2XXHlWSm36R+jz4u3JfcA3Ppzx1sbhLoJbE3vzEykhJr1yJoc95 2WHb/ZOCZfeGE5Pmp0Og3ZBA4cK08N5LjdJ9481DczC2EDSXuaE9UswHrzTg7FTRSa2xvSFwKPM cnsqhhDvSZChOEXi/JGVHWiKOUCWoMmi0PO/Jn34zzb/ynnupXY2FgJpNZbNRVoeL1v+dqkwkNo 0WmieTn9nd0EOajPSJUnuQeKjjZXBzV/Ssqh+mJm5Q== X-Received: by 2002:a05:7022:b056:20b0:160:a80f:3ed2 with SMTP id a92af1059eb24-1b5568652e2mr36484777c88.10.1796103455151; Mon, 30 Nov 2026 21:37:35 -0800 (PST) Received: from penguin.lxd ([12.187.136.98]) by smtp.gmail.com with ESMTPSA id a92af1059eb24-1b5566c3052sm81183292c88.1.2026.11.30.21.37.33 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 30 Nov 2026 21:37:34 -0800 (PST) From: "Kanchana P. Sridhar" To: hannes@cmpxchg.org, yosry@kernel.org, nphamcs@gmail.com, chengming.zhou@linux.dev, akpm@linux-foundation.org, linux-mm@kvack.org, herbert@gondor.apana.org.au, davem@davemloft.net, linux-crypto@vger.kernel.org, kanchanapsridhar2026@gmail.com, linux-kernel@vger.kernel.org Cc: rientjes@google.com, willy@infradead.org, senozhatsky@chromium.org Subject: [PATCH v5 9/9] mm: zswap: Batched zswap_compress() for storing large folios in batches. Date: Mon, 30 Nov 2026 21:37:11 -0800 Message-Id: <20261201053711.8090-10-kanchanapsridhar2026@gmail.com> X-Mailer: git-send-email 2.39.5 In-Reply-To: <20261201053711.8090-1-kanchanapsridhar2026@gmail.com> References: <20261201053711.8090-1-kanchanapsridhar2026@gmail.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit A new batching implementation of zswap_compress() is provided for compressors that do and do not support batching. This eliminates code duplication and facilitates code maintainability with the introduction of compress batching. The vectorized implementation of calling the earlier zswap_compress() sequentially, one page at a time in zswap_store_pages(), is replaced with this new version of zswap_compress() that accepts multiple pages to compress as a batch. When the crypto_acomp is used to set up the per-CPU acomp_ctx during CPU onlining, the compressor's batch_size is obtained by calling: crypto_acomp_batch_size(acomp_ctx->acomp) This is bounded by ZSWAP_MAX_BATCH_SIZE to limit the memory overhead and to reflect the store batch constraint of max # of pages in a batch. The clamped batch_size is stored in the per-CPU acomp_ctx->comp.compr_batch_size. As noted in previous commits in this series, ZSWAP_MAX_BATCH_SIZE per-CPU compression buffers are available for sequential and batching compression algorithms. Regardless of compression batching, we always process large folios in batches of ZSWAP_MAX_BATCH_SIZE. If the compressor does not support batching, each page in the batch is compressed sequentially. For batching compressors, up to acomp_ctx->comp.compr_batch_size pages in the batch are compressed per call to crypto_acomp_compress(). The first phase of zswap_compress() thus only calls crypto_acomp_compress() until all pages in the batch have been compressed. When this finishes, the compressed buffers and compressed lengths for the batch are available in the acomp_ctx->comp.sg_table->sgl scatterlists. A new zswap_update_entries() then iterates through the (up to) ZSWAP_MAX_BATCH_SIZE SG lists in acomp_ctx->comp.sg_table->sgl, allocates zsmalloc memory and copies all compressed buffers to the compressed pool. All existing functionality on zswap writeback_enabled (or not) fallbacks under various error conditions denoted by the crypto_acomp_compress() return value [compression error is also stored in the individual acomp_ctx->comp.sg_table->sgl sg->lengths in the crypto_acomp_compress() fast path], is essentially preserved. A significant zswap architectural change is that the batched zswap_compress() incorporates Herbert's suggestion for SG lists to represent the batch's inputs/outputs to interface with the crypto API [1]. The introduction of zswap_update_entries() presents an opportunity to optimize the task of storing a batch of compressed buffers. Subsequent RFC patch series will be submitted to optimize this phase by replacing zsmalloc with the SLUB allocator to improve zswap_store()/zswap_load() latencies. The batching framework introduced in this series improves zswap_store() latency by a lot. Validation was done with mm-unstable as of 11-17-2026 and with this patch series. ======================================================================== PERFORMANCE TESTING PHASE 1 (ZSTD): Unmodified usemem30 with 100% over-commit: ======================================================================== Validation platform: Intel Xeon Sapphire Rapids bare-metal instance with 48 cores. Bare-metal instance specs: -------------------------- - 48 physical cores - 190G RAM - 200G SWAP disk partition Workload: 30 concurrent usemem processes, each allocates 10G: ------------------------------------------------------------- The vm-scalability "usemem" test (unmodified version) was run in a cgroup with memory.high fixed at 150G. There is no swap limit set for the cgroup. To quantify the performance benefit of zswap compress batching at scale, 30 usemem processes were run ("usemem30"), each allocating and writing 10G of memory, and sleeping for 10 sec before exiting. usemem -w -O -b 5 -s 10 -n 30 10g echo 0 > /sys/module/zswap/parameters/shrinker_enabled ZSTD is the zswap compressor. Performance validation methodology: ----------------------------------- These settings were used to minimize variation: - All cores were fixed to run at 2.4GHz with "performance" scaling governor. - Turbo boost was disabled. - CPU power-saving C-states restricted with: GRUB_CMDLINE_LINUX_DEFAULT="intel_idle.max_cstate=1 processor.max_cstate=1" The usemem30 experiments were run with the baseline mm-unstable as of 11-17-2026 (commit 866f761fd414) and with this patch-series. After booting into each kernel: 1) Constrain the cgroup's memory.high to 150G. 2) Run 2 warm-up iterations of usemem30. Don't use this data for benchmarking since sys time typically skews higher for initial runs. 3) Next, run 10 benchmarking iterations of usemem30: - Log these high-level metrics: Sys time and individual usemem throughput. 4) Sys time and Throughput metrics were gathered for three mTHP settings: - 2048kB - 1024kB - 64kB 5) Benchmark summary data includes Sys time and Throughput components from the 10 iterations of usemem30: - Total Samples - Mean Value - Std Deviation - CoV (Variance): Coefficient of variation (relative standard deviation) measures spread relative to the mean rather than statistical variance. An LLM was used to help generate the benchmarking and data processing scripts. usemem30 ZSTD Benchmarking Summary: =================================== ------------------------------------------------------------------ Improvement over mm-unstable with zswap compress batching ------------------------------------------------------------------ mTHP enabled: 2048kB 1024kB 64kB ------------------------------------------------------------------ Sys time: -13.87% -2.64% -1.72% Throughput: +3.85% +0.42% +1.31% ------------------------------------------------------------------ Detailed usemem30 ZSTD benchmarking data: ========================================= 1) 2048kB mTHP: =============== ----------------------------------------------------------------------- 2048kB mTHP usemem30 benchmark suite: 10 runs (Limit: 150G). ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (sec) batching (sec) ----------------------------------------------------------------------- [Run 1/10] Sys Time: 1581.414s 1356.252s [Run 2/10] Sys Time: 1642.874s 1478.929s [Run 3/10] Sys Time: 1594.458s 1411.252s [Run 4/10] Sys Time: 1580.988s 1380.959s [Run 5/10] Sys Time: 1579.654s 1380.609s [Run 6/10] Sys Time: 1627.765s 1345.582s [Run 7/10] Sys Time: 1593.872s 1334.485s [Run 8/10] Sys Time: 1623.189s 1405.471s [Run 9/10] Sys Time: 1661.954s 1433.365s [Run 10/10] Sys Time: 1602.098s 1329.813s ----------------------------------------------------------------------- ----------------------------------------------------------------------- METRIC: System CPU Time (Sys Time) : 2048kB mTHP ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (sec) batching (sec) ----------------------------------------------------------------------- Total Samples : 10 10 Mean Value : 1,608.83 1,385.67 Std Deviation : 28.67 47.47 CoV (Variance) : 1.78% 3.43% ----------------------------------------------------------------------- METRIC: Per-Process Throughput : 2048kB mTHP ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (KB/s) batching (KB/s) ----------------------------------------------------------------------- Total Samples : 300 300 Mean Value : 292,261 303,508 Std Deviation : 12,946 20,806 CoV (Variance) : 4.42% 6.86% ----------------------------------------------------------------------- 2) 1024kB mTHP: =============== ----------------------------------------------------------------------- 1024kB mTHP usemem30 benchmark suite: 10 runs (Limit: 150G). ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (sec) batching (sec) ----------------------------------------------------------------------- [Run 1/10] Sys Time: 1567.639s 1594.696s [Run 2/10] Sys Time: 1537.577s 1456.113s [Run 3/10] Sys Time: 1538.562s 1521.887s [Run 4/10] Sys Time: 1626.176s 1531.962s [Run 5/10] Sys Time: 1593.955s 1528.733s [Run 6/10] Sys Time: 1643.519s 1558.482s [Run 7/10] Sys Time: 1510.613s 1480.177s [Run 8/10] Sys Time: 1632.018s 1584.093s [Run 9/10] Sys Time: 1569.424s 1528.915s [Run 10/10] Sys Time: 1552.747s 1570.451s ----------------------------------------------------------------------- ----------------------------------------------------------------------- METRIC: System CPU Time (Sys Time) : 1024kB mTHP ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (sec) batching (sec) ----------------------------------------------------------------------- Total Samples : 10 10 Mean Value : 1,577.22 1,535.55 Std Deviation : 45.13 43.79 CoV (Variance) : 2.86% 2.85% ----------------------------------------------------------------------- METRIC: Per-Process Throughput : 1024kB mTHP ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (KB/s) batching (KB/s) ----------------------------------------------------------------------- Total Samples : 300 300 Mean Value : 289,904 291,114 Std Deviation : 15,385 14,553 CoV (Variance) : 5.31% 5.00% ----------------------------------------------------------------------- 3) 64kB mTHP: ============= ----------------------------------------------------------------------- 64kB mTHP usemem30 benchmark suite: 10 runs (Limit: 150G). ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (sec) batching (sec) ----------------------------------------------------------------------- [Run 1/10] Sys Time: 1914.525s 1878.483s [Run 2/10] Sys Time: 1869.412s 1863.177s [Run 3/10] Sys Time: 1944.049s 1863.502s [Run 4/10] Sys Time: 1942.757s 1900.144s [Run 5/10] Sys Time: 1866.505s 1887.285s [Run 6/10] Sys Time: 1877.716s 1861.668s [Run 7/10] Sys Time: 1861.741s 1868.788s [Run 8/10] Sys Time: 1904.735s 1816.372s [Run 9/10] Sys Time: 1891.074s 1850.435s [Run 10/10] Sys Time: 1893.366s 1849.747s ----------------------------------------------------------------------- ----------------------------------------------------------------------- METRIC: System CPU Time (Sys Time) : 64kB mTHP ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (sec) batching (sec) ----------------------------------------------------------------------- Total Samples : 10 10 Mean Value : 1,896.59 1,863.96 Std Deviation : 29.86 22.96 CoV (Variance) : 1.57% 1.23% ----------------------------------------------------------------------- METRIC: Per-Process Throughput : 64kB mTHP ----------------------------------------------------------------------- Baseline mm-unstable zswap compress (KB/s) batching (KB/s) ----------------------------------------------------------------------- Total Samples : 300 300 Mean Value : 239,114 242,254 Std Deviation : 9,090 6,419 CoV (Variance) : 3.80% 2.65% ----------------------------------------------------------------------- BPFTRACE of zswap_store() with ZSTD and PMD folios: =================================================== Performance validation Phases 2 and 3 measure the zswap_store() latency gains directly with bpftrace and co-relate this to Sys time improvements at the workload level. PMD folios are enabled for the usemem30 experiments. 1) Ran Unmodified Usemem and Usemem that reads in the Silesia compression dataset [2] for 10 iterations. 2) Gathered zswap_store() bpftrace kernel latencies for each iteration, with the help of LLM generated scripts: a) Each iteration reports Sys time along with cumulative zswap_store() latency for that iteration. b) bpftrace aggegrates nsec spent in zswap_store() calls. c) bpftrace uses lhist windows: Much better accuracy than log2 hist: PMD folios lhist: /* 10000 us - 25000 us in 15 us steps. */ @zswap_higher_order_folio_store_ns = lhist($lat, 10000000, 25000000, 15000); Order-0 folios lhist: /* 0 - 500 us in 500 ns steps. */ @zswap_order0_folio_store_ns = lhist($lat, 0, 500000, 500); 3) Ran without/with zswap shrinker enabled. Results and conclusions follow. ======================================================================= BPFTRACE PERFORMANCE TESTING PHASE 2 (ZSTD): Unmodified & Silesia usemem30 with 100% over-commit: without zswap shrinker: ======================================================================= zswap_compressor = ZSTD, zswap_shrinker = N: ======================================================================= Unmodified Usemem (100% over-commit): ======================================================================= usemem -w -O -b 5 -s 10 -n 30 10g cgroup memory.high = 150G zswap max_pool_percent = 20% (default) ----------------------------------------------------------------------- Baseline: ========= [+] Starting benchmark suite: 10 runs (Limit: 150G). ----------------------------------------------------------------------- [Run 1/10] Sys Time: 2082.624s | zswap_store: 1279.346867s [Run 2/10] Sys Time: 2076.123s | zswap_store: 1279.284415s [Run 3/10] Sys Time: 2067.660s | zswap_store: 1279.446595s [Run 4/10] Sys Time: 2087.806s | zswap_store: 1279.958761s [Run 5/10] Sys Time: 2105.170s | zswap_store: 1278.988750s [Run 6/10] Sys Time: 2059.407s | zswap_store: 1278.937106s [Run 7/10] Sys Time: 2076.392s | zswap_store: 1279.162205s [Run 8/10] Sys Time: 2078.407s | zswap_store: 1279.057718s [Run 9/10] Sys Time: 2074.148s | zswap_store: 1279.366872s [Run 10/10] Sys Time: 2045.885s | zswap_store: 1279.217773s ----------------------------------------------------------------------- zswap_compress_batching: ======================== [+] Starting benchmark suite: 10 runs (Limit: 150G). ----------------------------------------------------------------------- [Run 1/10] Sys Time: 1980.633s | zswap_store: 1274.292791s [Run 2/10] Sys Time: 2029.989s | zswap_store: 1274.619375s [Run 3/10] Sys Time: 1983.237s | zswap_store: 1274.533935s [Run 4/10] Sys Time: 2022.402s | zswap_store: 1274.328900s [Run 5/10] Sys Time: 1989.381s | zswap_store: 1275.065320s [Run 6/10] Sys Time: 1976.409s | zswap_store: 1274.698973s [Run 7/10] Sys Time: 1984.453s | zswap_store: 1274.511715s [Run 8/10] Sys Time: 1967.692s | zswap_store: 1274.588755s [Run 9/10] Sys Time: 1984.806s | zswap_store: 1274.987864s [Run 10/10] Sys Time: 1929.026s | zswap_store: 1274.268613s ----------------------------------------------------------------------- -------------------------------------------------------------------------------- Avg of 10 usemem30 baseline zswap compress Gain Gain iterations batching actual % -------------------------------------------------------------------------------- Avg Sys time (seconds) 2,075.3622 1,984.8028 -90.56 sec -4.36% Avg Throughput (KB/s) 248,769 249,663 894 KB/s 0.36% Avg zswap_store (seconds) 1,279.2767 1,274.5896 -4.6871 sec -0.37% cumulative latency from bpftrace -------------------------------------------------------------------------------- PMD folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 894,463 894,462 -1 Avg (us) 14,302.107 14,249.720 -52.387 us -0.37% p50 (us) 14,368.092 14,310.851 -57.241 us -0.40% p95 (us) 14,456.748 14,419.225 -37.523 us -0.26% p99 (us) 14,602.678 14,610.077 7.399 us 0.05% -------------------------------------------------------------------------------- Order-0 folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 3,516 3,532 16 Avg (us) 17.591 17.877 0.286 us 1.63% p50 (us) 14.797 15.197 0.400 us 2.70% p95 (us) 29.124 29.628 0.504 us 1.73% p99 (us) 57.710 65.340 7.630 us 13.22% -------------------------------------------------------------------------------- vmstats (includes 2 warm-up iterations) -------------------------------------------------------------------------------- pswpin 0 0 0 pswpout 0 0 0 zswpin 3,754 3,844 90 zswpout 549,561,421 549,560,490 -931 zswpwb 0 0 0 2048kB-alloc 1,843,260 1,843,260 0 2048kB-zswpout 1,073,354 1,073,352 -2 2048kB-swpout 0 0 0 2048kB-swpout-fallback 0 0 0 zswap_pool_limit_hit 0 0 0 zswap_written_back_pages 0 0 0 ================================================================================ ================================================================================ Usemem Silesia (100% over-commit): ================================================================================ usemem -w --read-silesia -O -b 5 -s 10 -n 30 6g cgroup memory.high = 90G zswap max_pool_percent = 50% Baseline: ========= [+] Starting benchmark suite: 10 runs of Usemem with Silesia Dataset (Limit: 90G). ---------------------------------------------------------------------------- [Run 1/10] Sys Time: 3843.464s | zswap_store: 2277.627313s [Run 2/10] Sys Time: 3836.637s | zswap_store: 2278.318722s [Run 3/10] Sys Time: 3856.074s | zswap_store: 2278.190603s [Run 4/10] Sys Time: 3823.647s | zswap_store: 2278.387886s [Run 5/10] Sys Time: 3813.093s | zswap_store: 2278.740563s [Run 6/10] Sys Time: 3788.743s | zswap_store: 2277.697021s [Run 7/10] Sys Time: 3868.892s | zswap_store: 2277.858950s [Run 8/10] Sys Time: 3797.672s | zswap_store: 2278.514745s [Run 9/10] Sys Time: 3865.027s | zswap_store: 2279.041594s [Run 10/10] Sys Time: 3789.124s | zswap_store: 2279.485606s ---------------------------------------------------------------------------- zswap_compress_batching: ======================== [+] Starting benchmark suite: 10 runs (Limit: 90G). ---------------------------------------------------------------------------- [Run 1/10] Sys Time: 3852.547s | zswap_store: 2266.829664s [Run 2/10] Sys Time: 3824.707s | zswap_store: 2267.232763s [Run 3/10] Sys Time: 3839.655s | zswap_store: 2266.313908s [Run 4/10] Sys Time: 3805.258s | zswap_store: 2265.486178s [Run 5/10] Sys Time: 3775.986s | zswap_store: 2266.747005s [Run 6/10] Sys Time: 3842.518s | zswap_store: 2266.647259s [Run 7/10] Sys Time: 3837.615s | zswap_store: 2266.726275s [Run 8/10] Sys Time: 3848.061s | zswap_store: 2266.902372s [Run 9/10] Sys Time: 3831.397s | zswap_store: 2266.195312s [Run 10/10] Sys Time: 3826.463s | zswap_store: 2267.386639s ---------------------------------------------------------------------------- -------------------------------------------------------------------------------- Avg of 10 usemem30 baseline zswap compress Gain Gain iterations batching actual % -------------------------------------------------------------------------------- Avg Sys time (seconds) 3,828.2373 3,828.4207 0.18 sec 0.00% Avg Throughput (KB/s) 61,506 61,383 -123 KB/s -0.20% Avg zswap_store (seconds) 2,278.3863 2,266.6467 -11.7396 sec -0.52% cumulative latency from bpftrace -------------------------------------------------------------------------------- PMD folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 922,600 922,601 1 Avg (us) 16,035.212 15,816.040 -219.172 us -1.37% p50 (us) 16,916.945 16,682.504 -234.441 us -1.39% p95 (us) 20,518.592 20,134.788 -383.804 us -1.87% p99 (us) 20,866.739 20,474.772 -391.967 us -1.88% -------------------------------------------------------------------------------- Order-0 folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 275,102,932 275,099,516 -3,416 Avg (us) 29.043 29.351 0.308 us 1.06% p50 (us) 28.975 29.273 0.298 us 1.03% p95 (us) 31.528 31.841 0.313 us 0.99% p99 (us) 33.273 33.523 0.250 us 0.75% -------------------------------------------------------------------------------- vmstats (includes 2 warm-up iterations) -------------------------------------------------------------------------------- pswpin 0 0 0 pswpout 0 0 0 zswpin 566,262,293 566,273,230 10,937 zswpout 1,446,525,371 896,978,740 -549,546,631 -37.99% zswpwb 0 0 0 2048kB-alloc 2,950,440 1,107,181 -1,843,259 -62.47% 2048kB-zswpout 2,180,497 1,107,145 -1,073,352 -49.23% 2048kB-swpout 0 0 0 2048kB-swpout-fallback 0 0 0 zswap_pool_limit_hit 0 0 0 zswap_written_back_pages 0 0 0 ================================================================================ ======================================================================= BPFTRACE PERFORMANCE TESTING PHASE 3 (ZSTD): Unmodified & Silesia usemem30 with 100% & 50% over-commit respectively: with zswap shrinker: ======================================================================= zswap_compressor = ZSTD, zswap_shrinker = Y: ================================================================================ Unmodified Usemem (100% over-commit): ================================================================================ usemem -w -O -b 5 -s 10 -n 30 10g cgroup memory.high = 150G zswap max_pool_percent = 20% (default) -------------------------------------------------------------------------------- Avg of 10 usemem30 baseline zswap compress Gain Gain iterations batching actual % -------------------------------------------------------------------------------- Avg Sys time (seconds) 1,798.0412 1,754.8673 -43.17 sec -2.40% Avg Throughput (KB/s) 35,794 36,239 445 KB/s 1.24% Avg zswap_store (seconds) 1,243.6329 1,229.9446 -13.6883 sec -1.10% cumulative latency from bpftrace -------------------------------------------------------------------------------- PMD folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 857,921 854,237 -3,684 Avg (us) 14,495.816 14,398.087 -97.729 us -0.67% p50 (us) 14,535.149 14,412.360 -122.789 us -0.84% p95 (us) 15,012.265 14,923.469 -88.796 us -0.59% p99 (us) 15,241.253 15,120.714 -120.539 us -0.79% -------------------------------------------------------------------------------- Order-0 folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 3,602 3,607 5 Avg (us) 17.660 18.530 0.870 us 4.93% p50 (us) 14.939 14.801 -0.138 us -0.92% p95 (us) 29.822 30.622 0.800 us 2.68% p99 (us) 58.990 182.465 123.475 us 209.32% -------------------------------------------------------------------------------- vmstats (includes 2 warm-up iterations) -------------------------------------------------------------------------------- pswpin 2,325 2,215 -110 pswpout 12,976,001 13,093,265 117,264 zswpin 1,881 1,952 71 zswpout 526,979,887 524,858,122 -2,121,765 -0.40% zswpwb 12,976,001 13,093,265 117,264 2048kB-alloc 1,843,259 1,843,258 -1 0.00% 2048kB-zswpout 1,029,249 1,025,105 -4,144 -0.40% 2048kB-swpout 0 0 0 2048kB-swpout-fallback 0 0 0 zswap_pool_limit_hit 0 0 0 zswap_written_back_pages 10,852,812 10,656,928 -195,884 -1.80% zswap_reject_reclaim_fail 2 0 -2 ================================================================================ ================================================================================ Usemem Silesia (50% over-commit): ================================================================================ usemem -w --read-silesia -O -b 5 -s 10 -n 30 3g cgroup memory.high = 60G zswap max_pool_percent = 50% -------------------------------------------------------------------------------- Avg of 10 usemem30 baseline zswap compress Gain Gain iterations batching actual % -------------------------------------------------------------------------------- Avg Sys time (seconds) 1,484.1499 1,423.1080 -61.04 sec -4.11% Avg Throughput (KB/s) 20,286 26,221 5,935 KB/s 29.26% Avg zswap_store (seconds) 931.9412 899.9983 -31.9429 sec -3.43% cumulative latency from bpftrace -------------------------------------------------------------------------------- PMD folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 443,054 442,711 -343 Avg (us) 16,133.793 15,843.956 -289.837 us -1.80% p50 (us) 16,995.086 16,690.560 -304.526 us -1.79% p95 (us) 20,599.966 20,175.044 -424.922 us -2.06% p99 (us) 20,985.086 20,519.836 -465.250 us -2.22% -------------------------------------------------------------------------------- Order-0 folios: zswap_store() latency distribution across 10 usemem30 iterations -------------------------------------------------------------------------------- Calls 72,463,111 65,014,011 -7,449,100 Avg (us) 29.964 30.542 0.578 us 1.93% p50 (us) 29.148 29.585 0.437 us 1.50% p95 (us) 40.240 41.857 1.617 us 4.02% p99 (us) 46.286 48.478 2.192 us 4.74% -------------------------------------------------------------------------------- vmstats (includes 2 warm-up iterations) -------------------------------------------------------------------------------- pswpin 16,738,539 15,222,068 -1,516,471 pswpout 17,397,394 15,573,879 -1,823,515 zswpin 255,766,769 253,289,826 -2,476,943 zswpout 364,661,348 349,709,030 -14,952,318 -4.10% zswpwb 17,397,394 15,573,879 -1,823,515 2048kB-alloc 554,218 554,266 48 0.01% 2048kB-zswpout 535,430 534,030 -1,400 -0.26% 2048kB-swpout 0 0 0 2048kB-swpout-fallback 0 0 0 zswap_pool_limit_hit 0 0 0 zswap_written_back_pages 14,180,330 12,753,257 -1,427,073 -10.06% zswap_reject_reclaim_fail 4 4 0 ================================================================================ Conclusions based on the BPFTRACE results: ========================================== 1) Gains in zswap_store() latency are unambiguously established with zswap compress batching, both, for unmodified usemem and usemem reading Silesia. 2) Gains in zswap_store() latency are seen without and with zswap shrinker enabled. 3) More significant zswap_store() latency gains are seen with the zswap shrinker: Unmodified usemem: Sys time -2.4%, zswap_store() total latency -1.10% Usemem with Silesia: Sys time -4.11%, zswap_store() total latency -3.43% 4) With zswap shrinker, up to 4.10% fewer zswpout and up to 10.06% fewer zswap_written_back_pages are observed with the patch-series wrt baseline. 5) Without zswap shrinker, the usemem30 Silesia experiments show 38% fewer zswpout, 62% fewer PMD folio allocations and 49% fewer PMD THP zswpouts, with 0 pswpout/zswpwb/pool_limit_hit. This is indicative of the zswap_store() speed-up resulting in less memory pressure. 6) zswap_store() bpftrace avg, p50, p95, p99 latency distributions improve consistently for PMD folios. Conclusions: ============ The data demonstrates how the low-level zswap_store() bptrace latency savings translate to performance improvements at the system level and workload level. Performance validation is done at scale with 30 concurrent usemem processes, with Sys time and Throughput being the key high-level metrics. Sys time measured across 10 consecutive iterations of usemem30 improves significantly with zswap compress batching, -13.87% lower than mm-unstable for PMD THP. Per-process Throughput increases by 3.85% for PMD folios. As this patch-series impacts batching within folios, the Sys time savings reduces for lower order folios. The immediate benefit of zswap compress batching is saving CPU compute cycles, that can imply lower power consumption and existing kernel optimizations with reduced CPU compute cycles spent in critical paths. There are also modest throughput improvements that this patch-series delivers. As other kernel components related to mTHP become more efficient, the net realized performance benefit can only be better with this patch-series than without, given the significant Sys time reduction with zswap store and compress batching. The batching framework established in this series allows us to make locking and bulk-processing improvements in each stage of zswap_store(). One of the ideas that has shown very promising results is to replace zsmalloc with SLUB compressed caches and an RFC will be submitted separately. This will be directly optimizing zswap_update_entries(), where compressed buffers can be binned based on size and bulk allocated from SLUB. The speedup with zswap store batching of large folios has a propelling effect on other parts of mm, especially, by enabling large folios to be swapped out without splitting, as the higher-order folio vmstat v4 data shows. This enables other mm components that are optimized for large folios, such as munmap(), folio refcounts/mapcounts updates, PTE invalidation upon freeing memory, zswap_invalidate(); which benefit from xarray offsets/range continuity. As a result, subsequent large folio swapouts are more likely to find contiguous swap slots, there are fewer large folio splits during reclaim and the cycle continues. As the data demonstrates, this directly contributes to more memory over-commit opportunity. Architectural considerations for the zswap batching framework: ============================================================== The zswap batching framework is designed to be hardware-agnostic. It can be leveraged by any hardware accelerator or software-based compressor. Potential future clients of the batching framework: =================================================== This patch-series demonstrates the performance benefits of compression batching when used in zswap_store() of large folios. Compression batching can be used for other use cases such as batching compression in zram, batch compression of different folios during reclaim, kcompressd, file systems, etc. Decompression batching can be used to improve efficiency of zswap writeback (Thanks Nhat for this idea), batching decompressions in zram, etc. [1]: https://lore.kernel.org/all/aJ7Fk6RpNc815Ivd@gondor.apana.org.au/T/#m99aea2ce3d284e6c5a3253061d97b08c4752a798 [2]: https://wanos.co/assets/silesia.tar Signed-off-by: Kanchana P Sridhar Signed-off-by: Kanchana P. Sridhar --- mm/zswap.c | 290 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 217 insertions(+), 73 deletions(-) diff --git a/mm/zswap.c b/mm/zswap.c index 8a80b6e8e235..f391edb38016 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -149,9 +149,14 @@ struct zswap_acomp_req { /* * The compression mutex also protects the output buffer(s). + * + * @compr_batch_size: The max batch size of the compression algorithm, + * bounded by ZSWAP_MAX_BATCH_SIZE. */ struct zswap_comp_ctx { struct zswap_acomp_req areq; + u8 compr_batch_size; + struct sg_table *sg_table; u8 **buffers; }; @@ -238,6 +243,8 @@ struct zswap_store_context { bool wb_enabled; int nid; u8 nr_pages; + struct zs_pool *zs_pool; + struct zswap_comp_ctx *comp_ctx; struct zswap_entry *entries[ZSWAP_MAX_BATCH_SIZE]; }; @@ -325,6 +332,13 @@ static void acomp_ctx_free(struct crypto_acomp_ctx *acomp_ctx) kfree(acomp_ctx->comp.buffers); } acomp_ctx->comp.buffers = NULL; + acomp_ctx->comp.compr_batch_size = 0; + + if (acomp_ctx->comp.sg_table) { + sg_free_table(acomp_ctx->comp.sg_table); + kfree(acomp_ctx->comp.sg_table); + } + acomp_ctx->comp.sg_table = NULL; } static struct zswap_pool *zswap_pool_create(char *compressor) @@ -901,6 +915,7 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node); struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu); int nid = cpu_to_node(cpu); + struct scatterlist *sg; int ret = -ENOMEM; u8 i; @@ -925,6 +940,13 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) goto fail; } + /* + * Constrain the crypto algorithm's batch size by ZSWAP_MAX_BATCH_SIZE, + * store this in the per-CPU zswap_comp_ctx's @compr_batch_size. + */ + acomp_ctx->comp.compr_batch_size = min(ZSWAP_MAX_BATCH_SIZE, + crypto_acomp_batch_size(acomp_ctx->acomp)); + ret = zswap_acomp_req_init(&acomp_ctx->comp.areq, acomp_ctx->acomp); if (ret) goto req_fail; @@ -947,6 +969,26 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) } } + acomp_ctx->comp.sg_table = kmalloc(sizeof(*acomp_ctx->comp.sg_table), + GFP_KERNEL); + if (!acomp_ctx->comp.sg_table) { + ret = -ENOMEM; + goto req_fail; + } + + if (sg_alloc_table(acomp_ctx->comp.sg_table, ZSWAP_MAX_BATCH_SIZE, + GFP_KERNEL)) { + ret = -ENOMEM; + goto req_fail; + } + + /* + * Statically map the per-CPU destination buffers to the per-CPU + * SG lists; crucial for performance. + */ + for_each_sg(acomp_ctx->comp.sg_table->sgl, sg, ZSWAP_MAX_BATCH_SIZE, i) + sg_set_buf(sg, acomp_ctx->comp.buffers[i], PAGE_SIZE); + /* Skip the per-CPU request when decompression can use the stack. */ if (acomp_is_async(acomp_ctx->acomp)) { ret = zswap_acomp_req_init(&acomp_ctx->decomp, acomp_ctx->acomp); @@ -963,88 +1005,181 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) return ret; } -static bool zswap_compress(struct folio *folio, long index, - struct zswap_entry *entry, struct zswap_pool *pool, - bool wb_enabled) +/* + * zswap_update_entries() is called only when all pages in a store batch have + * been successfully compressed (subsumes the writeback_enabled fallback in case + * of compress errors). The only error that can occur in this phase is zs_malloc + * allocation failure, upon which an error status is returned to + * zswap_store_pages(). + */ +static inline bool zswap_update_entries(struct zswap_store_context *zc) { - struct zswap_comp_ctx *comp_ctx; - struct scatterlist input, output; - int comp_ret = 0, alloc_ret = 0; - unsigned int dlen = PAGE_SIZE; - gfp_t gfp; - u8 *dst; - bool mapped = false; + gfp_t gfp = GFP_NOWAIT | __GFP_NORETRY | __GFP_HIGHMEM | __GFP_MOVABLE; + struct zswap_entry *entry; + struct scatterlist *sg; + unsigned int dlen; + u8 batch_iter; + u8 *buf; + int err; + + /* Called should ensure that each dst sg->length is > 0. */ + for_each_sg(zc->comp_ctx->sg_table->sgl, sg, zc->nr_pages, batch_iter) { + entry = zc->entries[batch_iter]; + dlen = sg->length; + + prefetchw(entry); + + if (unlikely(dlen == PAGE_SIZE)) { + buf = kmap_local_folio(zc->folio, + (zc->folio_start + batch_iter) * PAGE_SIZE); + err = zs_store(zc->zs_pool, &entry->handle, buf, dlen, gfp, zc->nid); + kunmap_local(buf); + } else { + buf = zc->comp_ctx->buffers[batch_iter]; + err = zs_store(zc->zs_pool, &entry->handle, buf, dlen, gfp, zc->nid); + } - comp_ctx = &raw_cpu_ptr(pool->acomp_ctx)->comp; - mutex_lock(&comp_ctx->areq.mutex); + if (unlikely(err)) { + if (err == -ENOSPC) + zswap_reject_compress_poor++; + else + zswap_reject_alloc_fail++; - dst = comp_ctx->buffers[0]; - sg_init_table(&input, 1); - sg_set_folio(&input, folio, PAGE_SIZE, index * PAGE_SIZE); + return false; + } + + entry->length = dlen; + } - sg_init_one(&output, dst, PAGE_SIZE); - acomp_request_set_params(comp_ctx->areq.req, &input, &output, - PAGE_SIZE, dlen); + return true; +} + +/* + * zswap_compress() batching implementation for sequential and batching + * compressors. + * + * Description: + * ============ + * Compress multiple @zc->nr_pages in @zc->folio starting from the + * @zc->folio_start index in batches of @nr_batch_pages; the latter + * representing the lesser of the @zc->nr_pages to be batch compressed and the + * compressor's batch size. + * + * @zc->nr_pages can be in (1, ZSWAP_MAX_BATCH_SIZE] even if the compressor does + * not support batching. + * + * If @nr_batch_pages is 1, each page is compressed sequentially. + * + * If @nr_batch_pages is > 1, the compressor may use batching to optimize + * compression. + * + * In all cases, the store processing that needs to happen post-compression + * occurs in batches of @zc->nr_pages. Error handling is minimal, mostly to + * update zswap statistics, with catch-all cleanup for the batch occuring in the + * @store_pages_failed label in zswap_store_pages(). + */ +static bool zswap_compress(struct zswap_store_context *zc) +{ + u8 nr_batch_pages, batch_start, comp_batch_iter; + struct scatterlist *sg, *dst_sg; + unsigned int slen; + int err; /* - * it maybe looks a little bit silly that we send an asynchronous request, - * then wait for its completion synchronously. This makes the process look - * synchronous in fact. - * Theoretically, acomp supports users send multiple acomp requests in one - * acomp instance, then get those requests done simultaneously. but in this - * case, zswap actually does store and load page by page, there is no - * existing method to send the second page before the first page is done - * in one thread doing zswap. - * but in different threads running on different cpu, we have different - * acomp instance, and compression and decompression use separate - * requests, so multiple threads can do (de)compression in parallel. + * @nr_batch_pages is constrained by the per-CPU comp_ctx's compressor + * batch size and the @zc->nr_pages in this store batch. @slen indicates + * the total source length bytes for @nr_batch_pages. */ - comp_ret = crypto_wait_req(crypto_acomp_compress(comp_ctx->areq.req), - &comp_ctx->areq.wait); - dlen = comp_ctx->areq.req->dlen; - if (!comp_ret) { - if (dlen == PAGE_SIZE) - comp_ret = -ENOSPC; - else if (WARN_ON_ONCE(!dlen || dlen > PAGE_SIZE)) - comp_ret = -EINVAL; - } + nr_batch_pages = min(zc->comp_ctx->compr_batch_size, zc->nr_pages); /* - * If a page cannot be compressed into a size smaller than PAGE_SIZE, - * save the content as is without a compression, to keep the LRU order - * of writebacks. If writeback is disabled, reject the page since it - * only adds metadata overhead. swap_writeout() will put the page back - * to the active LRU list in the case. + * Compress the @nr_pages in @folio starting at index @folio_start + * in batches of @nr_batch_pages. */ - if (comp_ret) { - if (!wb_enabled) - goto unlock; - comp_ret = 0; - dlen = PAGE_SIZE; - dst = kmap_local_folio(folio, index * PAGE_SIZE); - mapped = true; + for (batch_start = 0; batch_start < zc->nr_pages; + batch_start += nr_batch_pages) { + /* + * Clamp the last iteration's batch size if the compressor's + * batch_size does not evenly divide @zc->nr_pages. + */ + nr_batch_pages = min(nr_batch_pages, zc->nr_pages - batch_start); + slen = nr_batch_pages * PAGE_SIZE; + + /* + * Send @nr_batch_pages to crypto_acomp for compression: + * + * These pages are in @zc->folio's range of indices in the + * interval: + * [@zc->folio_start + @batch_start, + * @zc->folio_start + @batch_start + @nr_batch_pages). + * + * The source folio pages in the batch are directly submitted to + * crypto_acomp via acomp_request_set_src_folio(). + */ + acomp_request_set_src_folio(zc->comp_ctx->areq.req, zc->folio, + (zc->folio_start + batch_start) * PAGE_SIZE, + slen); + + dst_sg = zc->comp_ctx->sg_table->sgl + batch_start; + dst_sg->length = slen; + + /* + * The per-CPU @zc->comp_ctx->sg_table scatterlists are statically + * mapped to the per-CPU dst @buffers at pool creation time. + * There are ZSWAP_MAX_BATCH_SIZE per-CPU SG lists and dst + * buffers allocated for all compressors. + */ + acomp_request_set_dst_sg(zc->comp_ctx->areq.req, dst_sg, slen); + + err = crypto_wait_req(crypto_acomp_compress(zc->comp_ctx->areq.req), + &zc->comp_ctx->areq.wait); + + /* + * If a page cannot be compressed into a size smaller than + * PAGE_SIZE, save the content as is without a compression, to + * keep the LRU order of writebacks. If writeback is disabled, + * reject the page since it only adds metadata overhead. + * swap_writeout() will put the page back to the active LRU list + * in the case. + */ + if (err && !zc->wb_enabled) + goto compress_error; + + /* + * For each output SG list in @acomp_ctx->req->sg_table->sgl, + * the @sg->length should be set to either the page's compressed + * length (success), or it's negative value compression error. + */ + for_each_sg(dst_sg, sg, nr_batch_pages, comp_batch_iter) { + int dlen = (int)sg->length; + + if ((dlen <= 0) || (dlen >= PAGE_SIZE)) { + if (!zc->wb_enabled) { + if (dlen == PAGE_SIZE) + sg->length = -ENOSPC; + else if (WARN_ON_ONCE(!dlen || dlen > PAGE_SIZE)) + sg->length = -EINVAL; + goto compress_error; + } + + sg->length = PAGE_SIZE; + } + } } - gfp = GFP_NOWAIT | __GFP_NORETRY | __GFP_HIGHMEM | __GFP_MOVABLE; - alloc_ret = zs_store(pool->zs_pool, &entry->handle, dst, dlen, gfp, - folio_nid(folio)); - if (alloc_ret) - goto unlock; + return zswap_update_entries(zc); - entry->length = dlen; +compress_error: + for_each_sg(dst_sg, sg, nr_batch_pages, comp_batch_iter) { + if ((int)sg->length < 0) { + if ((int)sg->length == -ENOSPC) + zswap_reject_compress_poor++; + else + zswap_reject_compress_fail++; + } + } -unlock: - if (mapped) - kunmap_local(dst); - if (comp_ret == -ENOSPC || alloc_ret == -ENOSPC) - zswap_reject_compress_poor++; - else if (comp_ret) - zswap_reject_compress_fail++; - else if (alloc_ret) - zswap_reject_alloc_fail++; - - mutex_unlock(&comp_ctx->areq.mutex); - return comp_ret == 0 && alloc_ret == 0; + return false; } static bool __zswap_decompress(struct zswap_entry *entry, @@ -1764,11 +1899,19 @@ static bool zswap_store_pages(struct zswap_store_context *zc, zswap_init_entries(zc, pool, objcg); - for (i = 0; i < zc->nr_pages; ++i) { - if (!zswap_compress(zc->folio, zc->folio_start + i, - zc->entries[i], pool, zc->wb_enabled)) - goto store_pages_failed; - } + /* + * Locking the comp_ctx mutex once per store batch results in better + * performance as compared to locking per compress batch. + */ + zc->comp_ctx = &raw_cpu_ptr(pool->acomp_ctx)->comp; + mutex_lock(&zc->comp_ctx->areq.mutex); + + ret = zswap_compress(zc); + + mutex_unlock(&zc->comp_ctx->areq.mutex); + + if (unlikely(!ret)) + goto store_pages_failed; ret = zswap_tree_stores(zc, pool, objcg); @@ -1834,6 +1977,7 @@ bool zswap_store(struct folio *folio) mem_cgroup_put(memcg); } + zc.zs_pool = pool->zs_pool; rcu_read_lock(); zc.wb_enabled = mem_cgroup_zswap_writeback_enabled(folio_memcg(folio)); rcu_read_unlock(); -- 2.39.5