From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oi1-f180.google.com (mail-oi1-f180.google.com [209.85.167.180]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4784329D291 for ; Sun, 8 Feb 2026 21:58:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.180 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587926; cv=none; b=G6Ts7gIYRr64fbZ7I3Q9m60QutQeDzmTOy8NJ9cBhTSldK9RVmvpqC2CGKeGrMQ8CvLG7GfVdKaCMHbAjJpayq3YDRYcKQ8pzyWoy+i9uLnhz4sjP7sZouPiov3badFddX3anybmVLIV4JQeuIDai145d7zOLHq/Q2IYg3hbHdI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587926; c=relaxed/simple; bh=XKla6ndzrkm5T0nbvnQM0Lq6V58h2slMy3+aldpr8t8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=cWyP0p9AYeTZe6ztrNfMaN8j4AU30It6UnauyYVnCIn7wagtOJds3EfrAYumUCfY73GxAW+QMLzbcNJ5EeSERzwc7If9YsiWR5VXSFUE0ALjxbZIdhd16yWh+xKZH4h3kY1SYHQwhx8ZQ1pG/45NSrWHOPDO5YWNCBR/UM2WWiQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=IO/ilBHH; arc=none smtp.client-ip=209.85.167.180 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.b="IO/ilBHH" Received: by mail-oi1-f180.google.com with SMTP id 5614622812f47-45c7c841904so1649479b6e.3 for ; Sun, 08 Feb 2026 13:58:46 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587925; x=1771192725; 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; bh=abeNKnw9HZhmXwtM4WYbHzmXFL6kS93ajK1z2pegh8E=; b=IO/ilBHH7f6VxGTwxvUPtE0Camghg38rBFxjFucaF//pYVKUUfhEtiOhVIudh+Voa7 EZV7led2OHLGiAmeH427Ft7R2ZGCbdBxdUnvFxHxlsrCJ0BOpK9Cz+DkUy3XYrHtpTrU +4ppsEnkr8imveWCFe/1Bm69QM4CPArGs9ZP54/2jLNWmMebfEdJ3sZcl7+gSuFk9orn QmpRjk8fCcCEKNpZuF1jsXkw9S2Vm7/EGEDF0RKRq7CJBYYSDvh3c2iFlIEZ89jg5rM6 TNVlDLXYxWwq+dBCu0eqwyt8P8maXK0NUS3F6jv6hHBNmU64kfA5KKZzxCCCblhLjgxV pC2Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587925; x=1771192725; 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; bh=abeNKnw9HZhmXwtM4WYbHzmXFL6kS93ajK1z2pegh8E=; b=SDkPqUKFY4IwXfLSYhofVv1vyqykUdVA7Qm7K13vCvPHDkH0Pwp+lxwwKpYgwQm7n0 tuMeRAMSg9jhThSW4RJImaYb7L7Mz3xsuTRE1PTMxNj/QHNut2U+gKTSzJlbciVLSDqz 4iPZSHg6wwgkGk6fwMXaqCjUOWzkufqYITBHMdujWMToEWTyJB3VKJcdt/b0yofHqqAU t6iwxb0MM/PkS4WqMaByk/6ZqWAm0B/9wBIuTKXqOOjvnqAAPhA43l/kqAA4a85lzbZv k2jHda84iC5SgqOqXtp+2D/Tcj/WvVFywHrNBvVar8aNpQQdeA8NrSHSUQQ1nMeNpDxh YR1A== X-Forwarded-Encrypted: i=1; AJvYcCUnA9d8dD9g/fwu79fUlc4JLmbPUjyNaZhQU3S6a3szXMU7QGaxisbzpb2ftb0MZ9DaxAZMOi7ohX/i3KE=@vger.kernel.org X-Gm-Message-State: AOJu0Yx6TvIow4OEV8uoI4/4Q6/AafJwc7s66S1pQEADEZQ4PPM7QQDG vWz6IS3GGnthUqDTG+Wbw8R8IV8EuiZN6dBxlniWKCjhFnWDKtRhVJyI X-Gm-Gg: AZuq6aIRjK+TMLdCao5GT+B9Cam37/NljwjioF5E7+FHMhuQNYkgMsjttbV4FpqvaZE Lj7YcCB8nVhSs2uZxvUSKXalbqbcrF8wvX1j5RkSfPzut0wgq/yNXiZk3QnW237ZzRpNi4WJFYF 8MZLCbU13d8yyWvgLO+TpN2JaLdldtbYj7iCt3kWWVg8dGC0rS89mwuhna3feIjA8Oo6w93nefQ MiwJa4zcBAu1eBcY4cmcrXyMngeNCYD6yl09MeoylUFsvspD2zgCgvGXyMe2HyfFAVP2IvrOGeM 1Y9tyYrz4PsVhDNIZmhg6tN2rpK22XhdgbKW7oT+QhbV42r5Lb6kSYo9QtYddAJZAo9lDiPuxQI vk+XJ7ScIR/YLWsj86MZdrzeJquanPJMQByIHRyG7GeDtkh4YUTIz6LHTrOzZ1gJD39xZGwLe37 T6ZWnxt+5ouwyod5pW3iNIw/bbCZuvxaYWObcHTxSNGny+ X-Received: by 2002:a05:6808:2218:b0:45f:66f:a2be with SMTP id 5614622812f47-462fcb8ac2amr5107625b6e.47.1770587924951; Sun, 08 Feb 2026 13:58:44 -0800 (PST) Received: from localhost ([2a03:2880:10ff:70::]) by smtp.gmail.com with ESMTPSA id 586e51a60fabf-40a9978a3absm6452458fac.18.2026.02.08.13.58.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:43 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 01/20] mm/swap: decouple swap cache from physical swap infrastructure Date: Sun, 8 Feb 2026 13:58:14 -0800 Message-ID: <20260208215839.87595-2-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" When we virtualize the swap space, we will manage swap cache at the virtual swap layer. To prepare for this, decouple swap cache from physical swap infrastructure. We will also remove all the swap cache related helpers of swap table. We will keep the rest of the swap table infrastructure, which will be repurposed to serve as the rmap (physical -> virtual swap mapping) later. Note that with this patch, we will move to a single global lock to synchronize swap cache accesses. This is temporarily, as the swap cache will be re-partitioned in to (virtual) swap clusters once we move the swap cache to the soon-to-be-introduced virtual swap layer. Signed-off-by: Nhat Pham --- Documentation/mm/swap-table.rst | 69 ----------- mm/huge_memory.c | 11 +- mm/migrate.c | 13 +- mm/shmem.c | 7 +- mm/swap.h | 26 ++-- mm/swap_state.c | 205 +++++++++++++++++--------------- mm/swap_table.h | 78 +----------- mm/swapfile.c | 43 ++----- mm/vmscan.c | 9 +- 9 files changed, 158 insertions(+), 303 deletions(-) delete mode 100644 Documentation/mm/swap-table.rst diff --git a/Documentation/mm/swap-table.rst b/Documentation/mm/swap-table.= rst deleted file mode 100644 index da10bb7a0dc37..0000000000000 --- a/Documentation/mm/swap-table.rst +++ /dev/null @@ -1,69 +0,0 @@ -.. SPDX-License-Identifier: GPL-2.0 - -:Author: Chris Li , Kairui Song - -=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D -Swap Table -=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D - -Swap table implements swap cache as a per-cluster swap cache value array. - -Swap Entry ----------- - -A swap entry contains the information required to serve the anonymous page -fault. - -Swap entry is encoded as two parts: swap type and swap offset. - -The swap type indicates which swap device to use. -The swap offset is the offset of the swap file to read the page data from. - -Swap Cache ----------- - -Swap cache is a map to look up folios using swap entry as the key. The res= ult -value can have three possible types depending on which stage of this swap = entry -was in. - -1. NULL: This swap entry is not used. - -2. folio: A folio has been allocated and bound to this swap entry. This is - the transient state of swap out or swap in. The folio data can be in - the folio or swap file, or both. - -3. shadow: The shadow contains the working set information of the swapped - out folio. This is the normal state for a swapped out page. - -Swap Table Internals --------------------- - -The previous swap cache is implemented by XArray. The XArray is a tree -structure. Each lookup will go through multiple nodes. Can we do better? - -Notice that most of the time when we look up the swap cache, we are either -in a swap in or swap out path. We should already have the swap cluster, -which contains the swap entry. - -If we have a per-cluster array to store swap cache value in the cluster. -Swap cache lookup within the cluster can be a very simple array lookup. - -We give such a per-cluster swap cache value array a name: the swap table. - -A swap table is an array of pointers. Each pointer is the same size as a -PTE. The size of a swap table for one swap cluster typically matches a PTE -page table, which is one page on modern 64-bit systems. - -With swap table, swap cache lookup can achieve great locality, simpler, -and faster. - -Locking -------- - -Swap table modification requires taking the cluster lock. If a folio -is being added to or removed from the swap table, the folio must be -locked prior to the cluster lock. After adding or removing is done, the -folio shall be unlocked. - -Swap table lookup is protected by RCU and atomic read. If the lookup -returns a folio, the user must lock the folio before use. diff --git a/mm/huge_memory.c b/mm/huge_memory.c index 40cf59301c21a..21215ac870144 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -3783,7 +3783,6 @@ static int __folio_freeze_and_split_unmapped(struct f= olio *folio, unsigned int n /* Prevent deferred_split_scan() touching ->_refcount */ ds_queue =3D folio_split_queue_lock(folio); if (folio_ref_freeze(folio, folio_cache_ref_count(folio) + 1)) { - struct swap_cluster_info *ci =3D NULL; struct lruvec *lruvec; =20 if (old_order > 1) { @@ -3826,7 +3825,7 @@ static int __folio_freeze_and_split_unmapped(struct f= olio *folio, unsigned int n return -EINVAL; } =20 - ci =3D swap_cluster_get_and_lock(folio); + swap_cache_lock(); } =20 /* lock lru list/PageCompound, ref frozen by page_ref_freeze */ @@ -3862,8 +3861,8 @@ static int __folio_freeze_and_split_unmapped(struct f= olio *folio, unsigned int n * Anonymous folio with swap cache. * NOTE: shmem in swap cache is not supported yet. */ - if (ci) { - __swap_cache_replace_folio(ci, folio, new_folio); + if (folio_test_swapcache(folio)) { + __swap_cache_replace_folio(folio, new_folio); continue; } =20 @@ -3901,8 +3900,8 @@ static int __folio_freeze_and_split_unmapped(struct f= olio *folio, unsigned int n if (do_lru) unlock_page_lruvec(lruvec); =20 - if (ci) - swap_cluster_unlock(ci); + if (folio_test_swapcache(folio)) + swap_cache_unlock(); } else { split_queue_unlock(ds_queue); return -EAGAIN; diff --git a/mm/migrate.c b/mm/migrate.c index 4688b9e38cd2f..11d9b43dff5d8 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -571,7 +571,6 @@ static int __folio_migrate_mapping(struct address_space= *mapping, struct folio *newfolio, struct folio *folio, int expected_count) { XA_STATE(xas, &mapping->i_pages, folio->index); - struct swap_cluster_info *ci =3D NULL; struct zone *oldzone, *newzone; int dirty; long nr =3D folio_nr_pages(folio); @@ -601,13 +600,13 @@ static int __folio_migrate_mapping(struct address_spa= ce *mapping, newzone =3D folio_zone(newfolio); =20 if (folio_test_swapcache(folio)) - ci =3D swap_cluster_get_and_lock_irq(folio); + swap_cache_lock_irq(); else xas_lock_irq(&xas); =20 if (!folio_ref_freeze(folio, expected_count)) { - if (ci) - swap_cluster_unlock_irq(ci); + if (folio_test_swapcache(folio)) + swap_cache_unlock_irq(); else xas_unlock_irq(&xas); return -EAGAIN; @@ -640,7 +639,7 @@ static int __folio_migrate_mapping(struct address_space= *mapping, } =20 if (folio_test_swapcache(folio)) - __swap_cache_replace_folio(ci, folio, newfolio); + __swap_cache_replace_folio(folio, newfolio); else xas_store(&xas, newfolio); =20 @@ -652,8 +651,8 @@ static int __folio_migrate_mapping(struct address_space= *mapping, folio_ref_unfreeze(folio, expected_count - nr); =20 /* Leave irq disabled to prevent preemption while updating stats */ - if (ci) - swap_cluster_unlock(ci); + if (folio_test_swapcache(folio)) + swap_cache_unlock(); else xas_unlock(&xas); =20 diff --git a/mm/shmem.c b/mm/shmem.c index 79af5f9f8b908..1db97ef2d14eb 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2133,7 +2133,6 @@ static int shmem_replace_folio(struct folio **foliop,= gfp_t gfp, struct shmem_inode_info *info, pgoff_t index, struct vm_area_struct *vma) { - struct swap_cluster_info *ci; struct folio *new, *old =3D *foliop; swp_entry_t entry =3D old->swap; int nr_pages =3D folio_nr_pages(old); @@ -2166,12 +2165,12 @@ static int shmem_replace_folio(struct folio **folio= p, gfp_t gfp, new->swap =3D entry; folio_set_swapcache(new); =20 - ci =3D swap_cluster_get_and_lock_irq(old); - __swap_cache_replace_folio(ci, old, new); + swap_cache_lock_irq(); + __swap_cache_replace_folio(old, new); mem_cgroup_replace_folio(old, new); shmem_update_stats(new, nr_pages); shmem_update_stats(old, -nr_pages); - swap_cluster_unlock_irq(ci); + swap_cache_unlock_irq(); =20 folio_add_lru(new); *foliop =3D new; diff --git a/mm/swap.h b/mm/swap.h index 1bd466da30393..8726b587a5b5d 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -199,6 +199,11 @@ void __swap_writepage(struct folio *folio, struct swap= _iocb **swap_plug); =20 /* linux/mm/swap_state.c */ extern struct address_space swap_space __read_mostly; +void swap_cache_lock_irq(void); +void swap_cache_unlock_irq(void); +void swap_cache_lock(void); +void swap_cache_unlock(void); + static inline struct address_space *swap_address_space(swp_entry_t entry) { return &swap_space; @@ -247,14 +252,12 @@ static inline bool folio_matches_swap_entry(const str= uct folio *folio, */ struct folio *swap_cache_get_folio(swp_entry_t entry); void *swap_cache_get_shadow(swp_entry_t entry); -void swap_cache_add_folio(struct folio *folio, swp_entry_t entry, void **s= hadow); +int swap_cache_add_folio(struct folio *folio, swp_entry_t entry, gfp_t gfp= , void **shadow); void swap_cache_del_folio(struct folio *folio); -/* Below helpers require the caller to lock and pass in the swap cluster. = */ -void __swap_cache_del_folio(struct swap_cluster_info *ci, - struct folio *folio, swp_entry_t entry, void *shadow); -void __swap_cache_replace_folio(struct swap_cluster_info *ci, - struct folio *old, struct folio *new); -void __swap_cache_clear_shadow(swp_entry_t entry, int nr_ents); +/* Below helpers require the caller to lock the swap cache. */ +void __swap_cache_del_folio(struct folio *folio, swp_entry_t entry, void *= shadow); +void __swap_cache_replace_folio(struct folio *old, struct folio *new); +void swap_cache_clear_shadow(swp_entry_t entry, int nr_ents); =20 void show_swap_cache_info(void); void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int n= r); @@ -411,21 +414,20 @@ static inline void *swap_cache_get_shadow(swp_entry_t= entry) return NULL; } =20 -static inline void swap_cache_add_folio(struct folio *folio, swp_entry_t e= ntry, void **shadow) +static inline int swap_cache_add_folio(struct folio *folio, swp_entry_t en= try, gfp_t gfp, void **shadow) { + return 0; } =20 static inline void swap_cache_del_folio(struct folio *folio) { } =20 -static inline void __swap_cache_del_folio(struct swap_cluster_info *ci, - struct folio *folio, swp_entry_t entry, void *shadow) +static inline void __swap_cache_del_folio(struct folio *folio, swp_entry_t= entry, void *shadow) { } =20 -static inline void __swap_cache_replace_folio(struct swap_cluster_info *ci, - struct folio *old, struct folio *new) +static inline void __swap_cache_replace_folio(struct folio *old, struct fo= lio *new) { } =20 diff --git a/mm/swap_state.c b/mm/swap_state.c index 44d228982521e..34c9d9b243a74 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -22,8 +22,8 @@ #include #include #include +#include #include "internal.h" -#include "swap_table.h" #include "swap.h" =20 /* @@ -41,6 +41,28 @@ struct address_space swap_space __read_mostly =3D { .a_ops =3D &swap_aops, }; =20 +static DEFINE_XARRAY(swap_cache); + +void swap_cache_lock_irq(void) +{ + xa_lock_irq(&swap_cache); +} + +void swap_cache_unlock_irq(void) +{ + xa_unlock_irq(&swap_cache); +} + +void swap_cache_lock(void) +{ + xa_lock(&swap_cache); +} + +void swap_cache_unlock(void) +{ + xa_unlock(&swap_cache); +} + static bool enable_vma_readahead __read_mostly =3D true; =20 #define SWAP_RA_ORDER_CEILING 5 @@ -86,17 +108,22 @@ void show_swap_cache_info(void) */ struct folio *swap_cache_get_folio(swp_entry_t entry) { - unsigned long swp_tb; + void *entry_val; struct folio *folio; =20 for (;;) { - swp_tb =3D swap_table_get(__swap_entry_to_cluster(entry), - swp_cluster_offset(entry)); - if (!swp_tb_is_folio(swp_tb)) + rcu_read_lock(); + entry_val =3D xa_load(&swap_cache, entry.val); + if (!entry_val || xa_is_value(entry_val)) { + rcu_read_unlock(); return NULL; - folio =3D swp_tb_to_folio(swp_tb); - if (likely(folio_try_get(folio))) + } + folio =3D entry_val; + if (likely(folio_try_get(folio))) { + rcu_read_unlock(); return folio; + } + rcu_read_unlock(); } =20 return NULL; @@ -112,12 +139,14 @@ struct folio *swap_cache_get_folio(swp_entry_t entry) */ void *swap_cache_get_shadow(swp_entry_t entry) { - unsigned long swp_tb; + void *entry_val; + + rcu_read_lock(); + entry_val =3D xa_load(&swap_cache, entry.val); + rcu_read_unlock(); =20 - swp_tb =3D swap_table_get(__swap_entry_to_cluster(entry), - swp_cluster_offset(entry)); - if (swp_tb_is_shadow(swp_tb)) - return swp_tb_to_shadow(swp_tb); + if (xa_is_value(entry_val)) + return entry_val; return NULL; } =20 @@ -132,46 +161,58 @@ void *swap_cache_get_shadow(swp_entry_t entry) * with reference count or locks. * The caller also needs to update the corresponding swap_map slots with * SWAP_HAS_CACHE bit to avoid race or conflict. + * + * Return: 0 on success, negative error code on failure. */ -void swap_cache_add_folio(struct folio *folio, swp_entry_t entry, void **s= hadowp) +int swap_cache_add_folio(struct folio *folio, swp_entry_t entry, gfp_t gfp= , void **shadowp) { - void *shadow =3D NULL; - unsigned long old_tb, new_tb; - struct swap_cluster_info *ci; - unsigned int ci_start, ci_off, ci_end; + XA_STATE_ORDER(xas, &swap_cache, entry.val, folio_order(folio)); unsigned long nr_pages =3D folio_nr_pages(folio); + unsigned long i; + void *old; =20 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio); VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio); =20 - new_tb =3D folio_to_swp_tb(folio); - ci_start =3D swp_cluster_offset(entry); - ci_end =3D ci_start + nr_pages; - ci_off =3D ci_start; - ci =3D swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry)); - do { - old_tb =3D __swap_table_xchg(ci, ci_off, new_tb); - WARN_ON_ONCE(swp_tb_is_folio(old_tb)); - if (swp_tb_is_shadow(old_tb)) - shadow =3D swp_tb_to_shadow(old_tb); - } while (++ci_off < ci_end); - folio_ref_add(folio, nr_pages); folio_set_swapcache(folio); folio->swap =3D entry; - swap_cluster_unlock(ci); =20 - node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages); - lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages); + do { + xas_lock_irq(&xas); + xas_create_range(&xas); + if (xas_error(&xas)) + goto unlock; + for (i =3D 0; i < nr_pages; i++) { + VM_BUG_ON_FOLIO(xas.xa_index !=3D entry.val + i, folio); + old =3D xas_load(&xas); + if (old && !xa_is_value(old)) { + VM_WARN_ON_ONCE_FOLIO(1, folio); + xas_set_err(&xas, -EEXIST); + goto unlock; + } + if (shadowp && xa_is_value(old) && !*shadowp) + *shadowp =3D old; + xas_store(&xas, folio); + xas_next(&xas); + } + node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages); + lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages); +unlock: + xas_unlock_irq(&xas); + } while (xas_nomem(&xas, gfp)); =20 - if (shadowp) - *shadowp =3D shadow; + if (!xas_error(&xas)) + return 0; + + folio_clear_swapcache(folio); + folio_ref_sub(folio, nr_pages); + return xas_error(&xas); } =20 /** * __swap_cache_del_folio - Removes a folio from the swap cache. - * @ci: The locked swap cluster. * @folio: The folio. * @entry: The first swap entry that the folio corresponds to. * @shadow: shadow value to be filled in the swap cache. @@ -180,30 +221,23 @@ void swap_cache_add_folio(struct folio *folio, swp_en= try_t entry, void **shadowp * This won't put the folio's refcount. The caller has to do that. * * Context: Caller must ensure the folio is locked and in the swap cache - * using the index of @entry, and lock the cluster that holds the entries. + * using the index of @entry, and lock the swap cache xarray. */ -void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *fo= lio, - swp_entry_t entry, void *shadow) +void __swap_cache_del_folio(struct folio *folio, swp_entry_t entry, void *= shadow) { - unsigned long old_tb, new_tb; - unsigned int ci_start, ci_off, ci_end; - unsigned long nr_pages =3D folio_nr_pages(folio); + long nr_pages =3D folio_nr_pages(folio); + XA_STATE(xas, &swap_cache, entry.val); + int i; =20 - VM_WARN_ON_ONCE(__swap_entry_to_cluster(entry) !=3D ci); VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio); =20 - new_tb =3D shadow_swp_to_tb(shadow); - ci_start =3D swp_cluster_offset(entry); - ci_end =3D ci_start + nr_pages; - ci_off =3D ci_start; - do { - /* If shadow is NULL, we sets an empty shadow */ - old_tb =3D __swap_table_xchg(ci, ci_off, new_tb); - WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || - swp_tb_to_folio(old_tb) !=3D folio); - } while (++ci_off < ci_end); + for (i =3D 0; i < nr_pages; i++) { + void *old =3D xas_store(&xas, shadow); + VM_WARN_ON_FOLIO(old !=3D folio, folio); + xas_next(&xas); + } =20 folio->swap.val =3D 0; folio_clear_swapcache(folio); @@ -223,12 +257,11 @@ void __swap_cache_del_folio(struct swap_cluster_info = *ci, struct folio *folio, */ void swap_cache_del_folio(struct folio *folio) { - struct swap_cluster_info *ci; swp_entry_t entry =3D folio->swap; =20 - ci =3D swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry)); - __swap_cache_del_folio(ci, folio, entry, NULL); - swap_cluster_unlock(ci); + xa_lock_irq(&swap_cache); + __swap_cache_del_folio(folio, entry, NULL); + xa_unlock_irq(&swap_cache); =20 put_swap_folio(folio, entry); folio_ref_sub(folio, folio_nr_pages(folio)); @@ -236,7 +269,6 @@ void swap_cache_del_folio(struct folio *folio) =20 /** * __swap_cache_replace_folio - Replace a folio in the swap cache. - * @ci: The locked swap cluster. * @old: The old folio to be replaced. * @new: The new folio. * @@ -246,39 +278,23 @@ void swap_cache_del_folio(struct folio *folio) * the starting offset to override all slots covered by the new folio. * * Context: Caller must ensure both folios are locked, and lock the - * cluster that holds the old folio to be replaced. + * swap cache xarray. */ -void __swap_cache_replace_folio(struct swap_cluster_info *ci, - struct folio *old, struct folio *new) +void __swap_cache_replace_folio(struct folio *old, struct folio *new) { swp_entry_t entry =3D new->swap; unsigned long nr_pages =3D folio_nr_pages(new); - unsigned int ci_off =3D swp_cluster_offset(entry); - unsigned int ci_end =3D ci_off + nr_pages; - unsigned long old_tb, new_tb; + XA_STATE(xas, &swap_cache, entry.val); + int i; =20 VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new)); VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new)); VM_WARN_ON_ONCE(!entry.val); =20 - /* Swap cache still stores N entries instead of a high-order entry */ - new_tb =3D folio_to_swp_tb(new); - do { - old_tb =3D __swap_table_xchg(ci, ci_off, new_tb); - WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || swp_tb_to_folio(old_tb) !=3D ol= d); - } while (++ci_off < ci_end); - - /* - * If the old folio is partially replaced (e.g., splitting a large - * folio, the old folio is shrunk, and new split sub folios replace - * the shrunk part), ensure the new folio doesn't overlap it. - */ - if (IS_ENABLED(CONFIG_DEBUG_VM) && - folio_order(old) !=3D folio_order(new)) { - ci_off =3D swp_cluster_offset(old->swap); - ci_end =3D ci_off + folio_nr_pages(old); - while (ci_off++ < ci_end) - WARN_ON_ONCE(swp_tb_to_folio(__swap_table_get(ci, ci_off)) !=3D old); + for (i =3D 0; i < nr_pages; i++) { + void *old_entry =3D xas_store(&xas, new); + WARN_ON_ONCE(!old_entry || xa_is_value(old_entry) || old_entry !=3D old); + xas_next(&xas); } } =20 @@ -287,20 +303,20 @@ void __swap_cache_replace_folio(struct swap_cluster_i= nfo *ci, * @entry: The starting index entry. * @nr_ents: How many slots need to be cleared. * - * Context: Caller must ensure the range is valid, all in one single clust= er, - * not occupied by any folio, and lock the cluster. + * Context: Caller must ensure the range is valid and all in one single cl= uster, + * not occupied by any folio. */ -void __swap_cache_clear_shadow(swp_entry_t entry, int nr_ents) +void swap_cache_clear_shadow(swp_entry_t entry, int nr_ents) { - struct swap_cluster_info *ci =3D __swap_entry_to_cluster(entry); - unsigned int ci_off =3D swp_cluster_offset(entry), ci_end; - unsigned long old; + XA_STATE(xas, &swap_cache, entry.val); + int i; =20 - ci_end =3D ci_off + nr_ents; - do { - old =3D __swap_table_xchg(ci, ci_off, null_to_swp_tb()); - WARN_ON_ONCE(swp_tb_is_folio(old)); - } while (++ci_off < ci_end); + xas_lock(&xas); + for (i =3D 0; i < nr_ents; i++) { + xas_store(&xas, NULL); + xas_next(&xas); + } + xas_unlock(&xas); } =20 /* @@ -480,7 +496,10 @@ struct folio *__read_swap_cache_async(swp_entry_t entr= y, gfp_t gfp_mask, if (mem_cgroup_swapin_charge_folio(new_folio, NULL, gfp_mask, entry)) goto fail_unlock; =20 - swap_cache_add_folio(new_folio, entry, &shadow); + /* May fail (-ENOMEM) if XArray node allocation failed. */ + if (swap_cache_add_folio(new_folio, entry, gfp_mask & GFP_RECLAIM_MASK, &= shadow)) + goto fail_unlock; + memcg1_swapin(entry, 1); =20 if (shadow) diff --git a/mm/swap_table.h b/mm/swap_table.h index ea244a57a5b7a..ad2cb2ef46903 100644 --- a/mm/swap_table.h +++ b/mm/swap_table.h @@ -13,71 +13,6 @@ struct swap_table { =20 #define SWP_TABLE_USE_PAGE (sizeof(struct swap_table) =3D=3D PAGE_SIZE) =20 -/* - * A swap table entry represents the status of a swap slot on a swap - * (physical or virtual) device. The swap table in each cluster is a - * 1:1 map of the swap slots in this cluster. - * - * Each swap table entry could be a pointer (folio), a XA_VALUE - * (shadow), or NULL. - */ - -/* - * Helpers for casting one type of info into a swap table entry. - */ -static inline unsigned long null_to_swp_tb(void) -{ - BUILD_BUG_ON(sizeof(unsigned long) !=3D sizeof(atomic_long_t)); - return 0; -} - -static inline unsigned long folio_to_swp_tb(struct folio *folio) -{ - BUILD_BUG_ON(sizeof(unsigned long) !=3D sizeof(void *)); - return (unsigned long)folio; -} - -static inline unsigned long shadow_swp_to_tb(void *shadow) -{ - BUILD_BUG_ON((BITS_PER_XA_VALUE + 1) !=3D - BITS_PER_BYTE * sizeof(unsigned long)); - VM_WARN_ON_ONCE(shadow && !xa_is_value(shadow)); - return (unsigned long)shadow; -} - -/* - * Helpers for swap table entry type checking. - */ -static inline bool swp_tb_is_null(unsigned long swp_tb) -{ - return !swp_tb; -} - -static inline bool swp_tb_is_folio(unsigned long swp_tb) -{ - return !xa_is_value((void *)swp_tb) && !swp_tb_is_null(swp_tb); -} - -static inline bool swp_tb_is_shadow(unsigned long swp_tb) -{ - return xa_is_value((void *)swp_tb); -} - -/* - * Helpers for retrieving info from swap table. - */ -static inline struct folio *swp_tb_to_folio(unsigned long swp_tb) -{ - VM_WARN_ON(!swp_tb_is_folio(swp_tb)); - return (void *)swp_tb; -} - -static inline void *swp_tb_to_shadow(unsigned long swp_tb) -{ - VM_WARN_ON(!swp_tb_is_shadow(swp_tb)); - return (void *)swp_tb; -} - /* * Helpers for accessing or modifying the swap table of a cluster, * the swap cluster must be locked. @@ -92,17 +27,6 @@ static inline void __swap_table_set(struct swap_cluster_= info *ci, atomic_long_set(&table[off], swp_tb); } =20 -static inline unsigned long __swap_table_xchg(struct swap_cluster_info *ci, - unsigned int off, unsigned long swp_tb) -{ - atomic_long_t *table =3D rcu_dereference_protected(ci->table, true); - - lockdep_assert_held(&ci->lock); - VM_WARN_ON_ONCE(off >=3D SWAPFILE_CLUSTER); - /* Ordering is guaranteed by cluster lock, relax */ - return atomic_long_xchg_relaxed(&table[off], swp_tb); -} - static inline unsigned long __swap_table_get(struct swap_cluster_info *ci, unsigned int off) { @@ -122,7 +46,7 @@ static inline unsigned long swap_table_get(struct swap_c= luster_info *ci, =20 rcu_read_lock(); table =3D rcu_dereference(ci->table); - swp_tb =3D table ? atomic_long_read(&table[off]) : null_to_swp_tb(); + swp_tb =3D table ? atomic_long_read(&table[off]) : 0; rcu_read_unlock(); =20 return swp_tb; diff --git a/mm/swapfile.c b/mm/swapfile.c index 46d2008e4b996..cacfafa9a540d 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -474,7 +474,7 @@ static void swap_cluster_free_table(struct swap_cluster= _info *ci) lockdep_assert_held(&ci->lock); VM_WARN_ON_ONCE(!cluster_is_empty(ci)); for (ci_off =3D 0; ci_off < SWAPFILE_CLUSTER; ci_off++) - VM_WARN_ON_ONCE(!swp_tb_is_null(__swap_table_get(ci, ci_off))); + VM_WARN_ON_ONCE(__swap_table_get(ci, ci_off)); table =3D (void *)rcu_dereference_protected(ci->table, true); rcu_assign_pointer(ci->table, NULL); =20 @@ -843,26 +843,6 @@ static bool cluster_scan_range(struct swap_info_struct= *si, return true; } =20 -/* - * Currently, the swap table is not used for count tracking, just - * do a sanity check here to ensure nothing leaked, so the swap - * table should be empty upon freeing. - */ -static void swap_cluster_assert_table_empty(struct swap_cluster_info *ci, - unsigned int start, unsigned int nr) -{ - unsigned int ci_off =3D start % SWAPFILE_CLUSTER; - unsigned int ci_end =3D ci_off + nr; - unsigned long swp_tb; - - if (IS_ENABLED(CONFIG_DEBUG_VM)) { - do { - swp_tb =3D __swap_table_get(ci, ci_off); - VM_WARN_ON_ONCE(!swp_tb_is_null(swp_tb)); - } while (++ci_off < ci_end); - } -} - static bool cluster_alloc_range(struct swap_info_struct *si, struct swap_c= luster_info *ci, unsigned int start, unsigned char usage, unsigned int order) @@ -882,7 +862,6 @@ static bool cluster_alloc_range(struct swap_info_struct= *si, struct swap_cluster ci->order =3D order; =20 memset(si->swap_map + start, usage, nr_pages); - swap_cluster_assert_table_empty(ci, start, nr_pages); swap_range_alloc(si, nr_pages); ci->count +=3D nr_pages; =20 @@ -1275,7 +1254,7 @@ static void swap_range_free(struct swap_info_struct *= si, unsigned long offset, swap_slot_free_notify(si->bdev, offset); offset++; } - __swap_cache_clear_shadow(swp_entry(si->type, begin), nr_entries); + swap_cache_clear_shadow(swp_entry(si->type, begin), nr_entries); =20 /* * Make sure that try_to_unuse() observes si->inuse_pages reaching 0 @@ -1423,6 +1402,7 @@ int folio_alloc_swap(struct folio *folio) unsigned int order =3D folio_order(folio); unsigned int size =3D 1 << order; swp_entry_t entry =3D {}; + int err; =20 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio); @@ -1457,19 +1437,23 @@ int folio_alloc_swap(struct folio *folio) } =20 /* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */ - if (mem_cgroup_try_charge_swap(folio, entry)) + if (mem_cgroup_try_charge_swap(folio, entry)) { + err =3D -ENOMEM; goto out_free; + } =20 if (!entry.val) return -ENOMEM; =20 - swap_cache_add_folio(folio, entry, NULL); + err =3D swap_cache_add_folio(folio, entry, __GFP_HIGH | __GFP_NOMEMALLOC = | __GFP_NOWARN, NULL); + if (err) + goto out_free; =20 return 0; =20 out_free: put_swap_folio(folio, entry); - return -ENOMEM; + return err; } =20 static struct swap_info_struct *_swap_info_get(swp_entry_t entry) @@ -1729,7 +1713,6 @@ static void swap_entries_free(struct swap_info_struct= *si, =20 mem_cgroup_uncharge_swap(entry, nr_pages); swap_range_free(si, offset, nr_pages); - swap_cluster_assert_table_empty(ci, offset, nr_pages); =20 if (!ci->count) free_cluster(si, ci); @@ -4057,9 +4040,9 @@ static int __init swapfile_init(void) swapfile_maximum_size =3D arch_max_swapfile_size(); =20 /* - * Once a cluster is freed, it's swap table content is read - * only, and all swap cache readers (swap_cache_*) verifies - * the content before use. So it's safe to use RCU slab here. + * Once a cluster is freed, it's swap table content is read only, and + * all swap table readers verify the content before use. So it's safe to + * use RCU slab here. */ if (!SWP_TABLE_USE_PAGE) swap_table_cachep =3D kmem_cache_create("swap_table", diff --git a/mm/vmscan.c b/mm/vmscan.c index 614ccf39fe3fa..558ff7f413786 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -707,13 +707,12 @@ static int __remove_mapping(struct address_space *map= ping, struct folio *folio, { int refcount; void *shadow =3D NULL; - struct swap_cluster_info *ci; =20 BUG_ON(!folio_test_locked(folio)); BUG_ON(mapping !=3D folio_mapping(folio)); =20 if (folio_test_swapcache(folio)) { - ci =3D swap_cluster_get_and_lock_irq(folio); + swap_cache_lock_irq(); } else { spin_lock(&mapping->host->i_lock); xa_lock_irq(&mapping->i_pages); @@ -758,9 +757,9 @@ static int __remove_mapping(struct address_space *mappi= ng, struct folio *folio, =20 if (reclaimed && !mapping_exiting(mapping)) shadow =3D workingset_eviction(folio, target_memcg); - __swap_cache_del_folio(ci, folio, swap, shadow); + __swap_cache_del_folio(folio, swap, shadow); memcg1_swapout(folio, swap); - swap_cluster_unlock_irq(ci); + swap_cache_unlock_irq(); put_swap_folio(folio, swap); } else { void (*free_folio)(struct folio *); @@ -799,7 +798,7 @@ static int __remove_mapping(struct address_space *mappi= ng, struct folio *folio, =20 cannot_free: if (folio_test_swapcache(folio)) { - swap_cluster_unlock_irq(ci); + swap_cache_unlock_irq(); } else { xa_unlock_irq(&mapping->i_pages); spin_unlock(&mapping->host->i_lock); --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oo1-f47.google.com (mail-oo1-f47.google.com [209.85.161.47]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2DDC834FF69 for ; Sun, 8 Feb 2026 21:58:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.161.47 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587929; cv=none; b=CFS++6A4sPLxrbl/mysTABMV90kPBKdaF2WzvNllj7ctouy27CRYyquKvLL/2ycAyU/8GD5MAhk/UINKYGAQWTr3wFhtD2PJLm3fab5a4UA6BunlTRXDPaD7rKb+IPupEs4XrgDTid9xVFQVx1mrmJlZEw6dwyWIMKUljihF52o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587929; c=relaxed/simple; bh=ygHLVQvf13Cv8oj9q9pBIyTvrB7Fok7pLI1My4ZIj50=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=RuHFqyGEjAVoLC4wCf+EzW0e7855o2OstIyGx644quN6ILNzynsViN9vZLvFLz+fKxoLkOWW3q6RAMcpf0dK2QoJ0DToky9t2ku/qAxNiW6nxs2f5ycMDNYS2gBaZPpN2L+jJLff3gaAIgH+ZtwGjbJzYpKx4bou3MBox0Esymg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=K23cYOG3; arc=none smtp.client-ip=209.85.161.47 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.b="K23cYOG3" Received: by mail-oo1-f47.google.com with SMTP id 006d021491bc7-6610b05b37dso3223768eaf.2 for ; Sun, 08 Feb 2026 13:58:48 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587928; x=1771192728; 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; bh=bdck4kEatqeWpIk5x4ugOl36FqvjbgCoyttMgxaBORw=; b=K23cYOG3uBJ//B+ooZw/JR7ZMb4vKfan8dQhrBwUXhcADUEs+pw25TNDO88bc92ACw oIMKRe467U3MkVWa14TBdEe/cyWSTHZu/YjX6N0O4ip/YjQhj9vIeaAY8BM6B9eMZeC3 nVQ7FR0SxEdgAty9DzTKDHriSusE5b6Me1nlrYRKDlvQEXhPkWV35DgCqWVkIN5pDPe0 ptJcKn+QARKmbxST9rlAQ1rxRp/otXfPjrK/uDTNCequcJtX2ZkLdROdbEtt+fknwspt wvO2b5+uTE8lCmtjX87nC6icbAD2HmfqgVmQtG+C2H3qOF/1q/m2FCzdgialr7uxYFK6 3YZQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587928; x=1771192728; 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; bh=bdck4kEatqeWpIk5x4ugOl36FqvjbgCoyttMgxaBORw=; b=iIqEs6RICZgj8lzfM/+N4NdGV00dS/aZLTr4ACvZT+tLlcjf3lh3r9ZLYHZekhDP3V XugPg37cEmdhWbuESryB909U3GkeD6Bvvfsd05gQ64w4fZ7fmfhREFCv5RNCD+DNt2kb EeOIvtgEmt8BeqgcMYQKNZrmL0VnpJz+Whs1w3xk2dF/DsCYIW6Zd0mktI+M9fIIku5h Y8j0dobaSJ9kZIZj83R41wi0itouNJRvH8BP4+v5KkZBmrxLvb1S0DoIrTb+++3NenM4 Rbuf7pjfo5MDpvbaAyQqsG6XiJolUQTV6dUyXtB6AsjtfChkNELIZBRS9XGIjP83UZoA W3uQ== X-Forwarded-Encrypted: i=1; AJvYcCUxDDSjFRtcqW4P3Bm+hlsHAzhjXm4wIPEwgSYH2TlaMa3/biN3eBk6jiweCl2oaQSA6Tjo7o7g1sqRlfg=@vger.kernel.org X-Gm-Message-State: AOJu0YyuCXrUCNQ88udrG+4Pez0qKRuXe/lQ5wDyUp5Jj4/nyz/J8PC1 d7kUWwKUo0KqPpqxD2yB1oW7hAnhsFWJ3ni3s/xYRVNGpgdHUzkeLMwV X-Gm-Gg: AZuq6aKqBA3fiapJ/FguJ3XjYFCebKxR4zBCSNyEFUVsQ+siPM7L9bd162Fuhg+148d vjLlTDWfDHEzOH4imaQC9tFoGHmMXsEAEe5jlxb7uXbF9IUs2WFt2i2SOmRcBmQ+qKqW9dOHXO5 roHSD91DN927uRYKbiYR9K7iVg/KvnWC3wZHHIu0D3BerEMm3xqB6LATjVJy5oXOuUmRpZ0ZPew oQZBHo2nFjZRIWTE4yPVFmh+2fdgysQ+jZfVDEiqGhv81QOg6IgU++WvI4X6zLOm02xXK+tQu9u 3j8ilqtqJ/xPdb0v7dOM4dH1+t310x6Doujw7+gLpYuWP/fk7ewPjslTavKOClzeBgHNMF2CD6a P7LnTgQIw1VIlaf6/m64gs9UD6xZRYPH9bqWha+b5KBiB2T3t2KnoegEpfLva//VYIMpsLU0DEM lekgZuwnYoWypPSJq7t2yexxSng0fzr737Am9ETBcTn54= X-Received: by 2002:a05:6820:986:b0:65f:6655:9db3 with SMTP id 006d021491bc7-66d3262bbfamr4616076eaf.5.1770587927690; Sun, 08 Feb 2026 13:58:47 -0800 (PST) Received: from localhost ([2a03:2880:10ff:5::]) by smtp.gmail.com with ESMTPSA id 006d021491bc7-670c3849609sm832927eaf.0.2026.02.08.13.58.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:46 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 02/20] swap: rearrange the swap header file Date: Sun, 8 Feb 2026 13:58:15 -0800 Message-ID: <20260208215839.87595-3-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" In the swap header file (include/linux/swap.h), group the swap API into the following categories: 1. Lifecycle swap functions (i.e the function that changes the reference count of the swap entry). 2. Swap cache API. 3. Physical swapfile allocator and swap device API. Also remove extern in the functions that are rearranged. This is purely a clean up. No functional change intended. Signed-off-by: Nhat Pham --- include/linux/swap.h | 53 +++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 38ca3df687160..aa29d8ac542d1 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -423,20 +423,34 @@ extern void __meminit kswapd_stop(int nid); =20 #ifdef CONFIG_SWAP =20 -int add_swap_extent(struct swap_info_struct *sis, unsigned long start_page, - unsigned long nr_pages, sector_t start_block); -int generic_swapfile_activate(struct swap_info_struct *, struct file *, - sector_t *); - +/* Lifecycle swap API (mm/swapfile.c) */ +int folio_alloc_swap(struct folio *folio); +bool folio_free_swap(struct folio *folio); +void put_swap_folio(struct folio *folio, swp_entry_t entry); +void swap_shmem_alloc(swp_entry_t, int); +int swap_duplicate(swp_entry_t); +int swapcache_prepare(swp_entry_t entry, int nr); +void swap_free_nr(swp_entry_t entry, int nr_pages); +void free_swap_and_cache_nr(swp_entry_t entry, int nr); +int __swap_count(swp_entry_t entry); +bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry); +int swp_swapcount(swp_entry_t entry); + +/* Swap cache API (mm/swap_state.c) */ static inline unsigned long total_swapcache_pages(void) { return global_node_page_state(NR_SWAPCACHE); } - -void free_swap_cache(struct folio *folio); void free_folio_and_swap_cache(struct folio *folio); void free_pages_and_swap_cache(struct encoded_page **, int); -/* linux/mm/swapfile.c */ +void free_swap_cache(struct folio *folio); + +/* Physical swap allocator and swap device API (mm/swapfile.c) */ +int add_swap_extent(struct swap_info_struct *sis, unsigned long start_page, + unsigned long nr_pages, sector_t start_block); +int generic_swapfile_activate(struct swap_info_struct *, struct file *, + sector_t *); + extern atomic_long_t nr_swap_pages; extern long total_swap_pages; extern atomic_t nr_rotate_swap; @@ -452,26 +466,15 @@ static inline long get_nr_swap_pages(void) return atomic_long_read(&nr_swap_pages); } =20 -extern void si_swapinfo(struct sysinfo *); -int folio_alloc_swap(struct folio *folio); -bool folio_free_swap(struct folio *folio); -void put_swap_folio(struct folio *folio, swp_entry_t entry); -extern swp_entry_t get_swap_page_of_type(int); -extern int add_swap_count_continuation(swp_entry_t, gfp_t); -extern void swap_shmem_alloc(swp_entry_t, int); -extern int swap_duplicate(swp_entry_t); -extern int swapcache_prepare(swp_entry_t entry, int nr); -extern void swap_free_nr(swp_entry_t entry, int nr_pages); -extern void free_swap_and_cache_nr(swp_entry_t entry, int nr); +void si_swapinfo(struct sysinfo *); +swp_entry_t get_swap_page_of_type(int); +int add_swap_count_continuation(swp_entry_t, gfp_t); int swap_type_of(dev_t device, sector_t offset); int find_first_swap(dev_t *device); -extern unsigned int count_swap_pages(int, int); -extern sector_t swapdev_block(int, pgoff_t); -extern int __swap_count(swp_entry_t entry); -extern bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t en= try); -extern int swp_swapcount(swp_entry_t entry); +unsigned int count_swap_pages(int, int); +sector_t swapdev_block(int, pgoff_t); struct backing_dev_info; -extern struct swap_info_struct *get_swap_device(swp_entry_t entry); +struct swap_info_struct *get_swap_device(swp_entry_t entry); sector_t swap_folio_sector(struct folio *folio); =20 static inline void put_swap_device(struct swap_info_struct *si) --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oo1-f54.google.com (mail-oo1-f54.google.com [209.85.161.54]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F02A3344DB0 for ; Sun, 8 Feb 2026 21:58:50 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.161.54 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587931; cv=none; b=tQMo004A7E4mc9wWE8PwwJurfAKUuD3WCYKVn3Iyg+qKqwWaRwTpkW62KmpZjJ/n2jJ9Jxj3eivmpKjwjPvr26+i6GlmF0Ej8W7HEwsg175OomtPguChwxyLHc6h8iRpANk9a0XSuAY/jd4eqOJZIXFFZSxEDs5MwiO6m+mdp3c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587931; c=relaxed/simple; bh=GETDChp4MZA6lB2IvMCiWU0XpNLogukkMxKKyzcImvk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=VOXdWKHL5nZJ6rIT+5E8gRjMTZ0DskQM/dp/9NFIZz9GQrH0fFg6qQhyisSErIVOuWd5vcsenM2Odfpbc92XTJ9+HlYHxoBH7bkdmrygMToTJ7/w+icRerDkK2rofAfG2hDXaVLrTdsCZOx+YWdtG3v5gwAn3zsGkUsorYzX/xw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=d0EZ3oZM; arc=none smtp.client-ip=209.85.161.54 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.b="d0EZ3oZM" Received: by mail-oo1-f54.google.com with SMTP id 006d021491bc7-66f3e7d9eccso600077eaf.1 for ; Sun, 08 Feb 2026 13:58:50 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587930; x=1771192730; 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; bh=bkTf0BqWuQBW5wS4SMRRzp+y8TABCQWi3klTIzIW13I=; b=d0EZ3oZMJ/bjUA73w0evJ3XIgId+dorjCIjtMM/OWb+GQBzymPrAYB2o+edrZjUmS9 AwiuQYjvTBKpffwSCOLFEN+lKo/vIwWOgMzlTko8FcxPo/ZDw64rhM1HnchHBXQqNoJV hrroEIZCpdDVUh0kgTWRjhVr58FoFRkVR/bfK7qigDDZBKWlNRgo/9DDzP7daAygPuh0 J1JlFxRi/VEUIdrN6L9ikBRU/nltJ4wpUCnoQqvVYi15GOcxzGpyLSn8g/Q0rUUbjRoj rhSBrTDI5rr6RpUViHqRwIYQIh7TWPdPm+ca/ts8OrTDUcyWz0+Z97DVPPEeAVu4WVwx 1/gQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587930; x=1771192730; 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; bh=bkTf0BqWuQBW5wS4SMRRzp+y8TABCQWi3klTIzIW13I=; b=jDiLGdE093rC+8fYzb11wGgruImEOq9SJnKKRS5XoqiQmtSv7bSwQtAHYXdUVflCB0 mGI3cumdjQrI3JZxI0jFK0E6smphUETcFlxlhHPVZWdQuSVP1HI9x68GPWghah4FISbC yDviaASeDqQZA4Pt9syWQGgfH5ehoZtjPtWQaRQFWMnXLts9nWuAZZyEbLbNTLhdgZoC Hi5nboxbab9vCoKccjCEw3PkMQQy9cfCE186dzPuBSEKyjdXS3XM5G1O0uPO8LR/a61k 2+tuv8bOKbm2qiLr9fMjYPldu6OmW8b/amsSgngE0HpO3R6n+NwVQ00XaSseli5gfL3m Z0EQ== X-Forwarded-Encrypted: i=1; AJvYcCV+RIpcUNLmaqKc3o9oM9xhVzzn0rMzm9UnlE7c+PwUTpuIxC7PsahZrsMsAPHX0H+6WimIGa20bew3/Wo=@vger.kernel.org X-Gm-Message-State: AOJu0YwiFIwIFMFenRMc4beA1ObGtQxWt/H0akwNnFiFUixcloRC2bdO FUvdgh9fraqIkwUXtqBL9XDOlnMkQSF0y/hfsLIVDxVwrtv+tTH50t32 X-Gm-Gg: AZuq6aJGXrpOw0zL0X6wkskFSJcH+2fJFzanlbVp4GesZeF+YVJCeaST14BRz25d9HS BhvOvOjJZ3PVBhc/RGguBqEGzQktEbgkpYHZ4vUKRcJSoSxBow262L3O22JfYt0jANw2EfHYJSi o4eTbcinzzXSdltyq4OQYCzwcHtkCMcKV8WnnSZa3LOMFwyyax9Cc0mLehVKOZKbITnkbb+i4Fj QVOpkTdzipv5LnloE5bKb2FzW0FkUfJc9u63Xl6cflYGNFlSN1+OSsUVJFXE4LLLrRaN3EE+tkd fyovabhgMPEm5TqZf5mFZ9lQp7KVuA8qrMHCDnC4+hJu2UAmnKe1C6jlvjFocJPrWgsL12DMbLs OFRu5dX4xgONFXoav+QA+/x6JsGhRBzMJFFX6L5iGktpWkcb7QyOwi4AgHx1/0nB42ZrWlWf9fD 8dipQQKr/I8V98rR1TiiqVOhUvmdmO20gluw== X-Received: by 2002:a05:6820:3088:b0:663:888:6093 with SMTP id 006d021491bc7-66d0ce25452mr4103771eaf.70.1770587929794; Sun, 08 Feb 2026 13:58:49 -0800 (PST) Received: from localhost ([2a03:2880:10ff:56::]) by smtp.gmail.com with ESMTPSA id 006d021491bc7-66d391ae639sm4736638eaf.7.2026.02.08.13.58.48 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:49 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 03/20] mm: swap: add an abstract API for locking out swapoff Date: Sun, 8 Feb 2026 13:58:16 -0800 Message-ID: <20260208215839.87595-4-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Currently, we get a reference to the backing swap device in order to prevent swapoff from freeing the metadata of a swap entry. This does not make sense in the new virtual swap design, especially after the swap backends are decoupled - a swap entry might not have any backing swap device at all, and its backend might change at any time during its lifetime. In preparation for this, abstract away the swapoff locking out behavior into a generic API. Signed-off-by: Nhat Pham --- include/linux/swap.h | 17 +++++++++++++++++ mm/memory.c | 13 +++++++------ mm/mincore.c | 15 +++------------ mm/shmem.c | 12 ++++++------ mm/swap_state.c | 14 +++++++------- mm/userfaultfd.c | 15 +++++++++------ mm/zswap.c | 5 ++--- 7 files changed, 51 insertions(+), 40 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index aa29d8ac542d1..3da637b218baf 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -659,5 +659,22 @@ static inline bool mem_cgroup_swap_full(struct folio *= folio) } #endif =20 +static inline bool tryget_swap_entry(swp_entry_t entry, + struct swap_info_struct **sip) +{ + struct swap_info_struct *si =3D get_swap_device(entry); + + if (sip) + *sip =3D si; + + return si; +} + +static inline void put_swap_entry(swp_entry_t entry, + struct swap_info_struct *si) +{ + put_swap_device(si); +} + #endif /* __KERNEL__*/ #endif /* _LINUX_SWAP_H */ diff --git a/mm/memory.c b/mm/memory.c index da360a6eb8a48..90031f833f52e 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4630,6 +4630,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) struct swap_info_struct *si =3D NULL; rmap_t rmap_flags =3D RMAP_NONE; bool need_clear_cache =3D false; + bool swapoff_locked =3D false; bool exclusive =3D false; softleaf_t entry; pte_t pte; @@ -4698,8 +4699,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) } =20 /* Prevent swapoff from happening to us. */ - si =3D get_swap_device(entry); - if (unlikely(!si)) + swapoff_locked =3D tryget_swap_entry(entry, &si); + if (unlikely(!swapoff_locked)) goto out; =20 folio =3D swap_cache_get_folio(entry); @@ -5047,8 +5048,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) if (waitqueue_active(&swapcache_wq)) wake_up(&swapcache_wq); } - if (si) - put_swap_device(si); + if (swapoff_locked) + put_swap_entry(entry, si); return ret; out_nomap: if (vmf->pte) @@ -5066,8 +5067,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) if (waitqueue_active(&swapcache_wq)) wake_up(&swapcache_wq); } - if (si) - put_swap_device(si); + if (swapoff_locked) + put_swap_entry(entry, si); return ret; } =20 diff --git a/mm/mincore.c b/mm/mincore.c index e5d13eea92347..f3eb771249d67 100644 --- a/mm/mincore.c +++ b/mm/mincore.c @@ -77,19 +77,10 @@ static unsigned char mincore_swap(swp_entry_t entry, bo= ol shmem) if (!softleaf_is_swap(entry)) return !shmem; =20 - /* - * Shmem mapping lookup is lockless, so we need to grab the swap - * device. mincore page table walk locks the PTL, and the swap - * device is stable, avoid touching the si for better performance. - */ - if (shmem) { - si =3D get_swap_device(entry); - if (!si) - return 0; - } + if (!tryget_swap_entry(entry, &si)) + return 0; folio =3D swap_cache_get_folio(entry); - if (shmem) - put_swap_device(si); + put_swap_entry(entry, si); /* The swap cache space contains either folio, shadow or NULL */ if (folio && !xa_is_value(folio)) { present =3D folio_test_uptodate(folio); diff --git a/mm/shmem.c b/mm/shmem.c index 1db97ef2d14eb..b40be22fa5f09 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2307,7 +2307,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, softleaf_t index_entry; struct swap_info_struct *si; struct folio *folio =3D NULL; - bool skip_swapcache =3D false; + bool swapoff_locked, skip_swapcache =3D false; int error, nr_pages, order; pgoff_t offset; =20 @@ -2319,16 +2319,16 @@ static int shmem_swapin_folio(struct inode *inode, = pgoff_t index, if (softleaf_is_poison_marker(index_entry)) return -EIO; =20 - si =3D get_swap_device(index_entry); + swapoff_locked =3D tryget_swap_entry(index_entry, &si); order =3D shmem_confirm_swap(mapping, index, index_entry); - if (unlikely(!si)) { + if (unlikely(!swapoff_locked)) { if (order < 0) return -EEXIST; else return -EINVAL; } if (unlikely(order < 0)) { - put_swap_device(si); + put_swap_entry(index_entry, si); return -EEXIST; } =20 @@ -2448,7 +2448,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, } folio_mark_dirty(folio); swap_free_nr(swap, nr_pages); - put_swap_device(si); + put_swap_entry(swap, si); =20 *foliop =3D folio; return 0; @@ -2466,7 +2466,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, swapcache_clear(si, folio->swap, folio_nr_pages(folio)); if (folio) folio_put(folio); - put_swap_device(si); + put_swap_entry(swap, si); =20 return error; } diff --git a/mm/swap_state.c b/mm/swap_state.c index 34c9d9b243a74..bece18eb540fa 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -538,8 +538,7 @@ struct folio *read_swap_cache_async(swp_entry_t entry, = gfp_t gfp_mask, pgoff_t ilx; struct folio *folio; =20 - si =3D get_swap_device(entry); - if (!si) + if (!tryget_swap_entry(entry, &si)) return NULL; =20 mpol =3D get_vma_policy(vma, addr, 0, &ilx); @@ -550,7 +549,7 @@ struct folio *read_swap_cache_async(swp_entry_t entry, = gfp_t gfp_mask, if (page_allocated) swap_read_folio(folio, plug); =20 - put_swap_device(si); + put_swap_entry(entry, si); return folio; } =20 @@ -763,6 +762,7 @@ static struct folio *swap_vma_readahead(swp_entry_t tar= g_entry, gfp_t gfp_mask, for (addr =3D start; addr < end; ilx++, addr +=3D PAGE_SIZE) { struct swap_info_struct *si =3D NULL; softleaf_t entry; + bool swapoff_locked =3D false; =20 if (!pte++) { pte =3D pte_offset_map(vmf->pmd, addr); @@ -781,14 +781,14 @@ static struct folio *swap_vma_readahead(swp_entry_t t= arg_entry, gfp_t gfp_mask, * holding a reference to, try to grab a reference, or skip. */ if (swp_type(entry) !=3D swp_type(targ_entry)) { - si =3D get_swap_device(entry); - if (!si) + swapoff_locked =3D tryget_swap_entry(entry, &si); + if (!swapoff_locked) continue; } folio =3D __read_swap_cache_async(entry, gfp_mask, mpol, ilx, &page_allocated, false); - if (si) - put_swap_device(si); + if (swapoff_locked) + put_swap_entry(entry, si); if (!folio) continue; if (page_allocated) { diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index e6dfd5f28acd7..25f89eba0438c 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -1262,9 +1262,11 @@ static long move_pages_ptes(struct mm_struct *mm, pm= d_t *dst_pmd, pmd_t *src_pmd pte_t *dst_pte =3D NULL; pmd_t dummy_pmdval; pmd_t dst_pmdval; + softleaf_t entry; struct folio *src_folio =3D NULL; struct mmu_notifier_range range; long ret =3D 0; + bool swapoff_locked =3D false; =20 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, src_addr, src_addr + len); @@ -1429,7 +1431,7 @@ static long move_pages_ptes(struct mm_struct *mm, pmd= _t *dst_pmd, pmd_t *src_pmd len); } else { /* !pte_present() */ struct folio *folio =3D NULL; - const softleaf_t entry =3D softleaf_from_pte(orig_src_pte); + entry =3D softleaf_from_pte(orig_src_pte); =20 if (softleaf_is_migration(entry)) { pte_unmap(src_pte); @@ -1449,8 +1451,8 @@ static long move_pages_ptes(struct mm_struct *mm, pmd= _t *dst_pmd, pmd_t *src_pmd goto out; } =20 - si =3D get_swap_device(entry); - if (unlikely(!si)) { + swapoff_locked =3D tryget_swap_entry(entry, &si); + if (unlikely(!swapoff_locked)) { ret =3D -EAGAIN; goto out; } @@ -1480,8 +1482,9 @@ static long move_pages_ptes(struct mm_struct *mm, pmd= _t *dst_pmd, pmd_t *src_pmd pte_unmap(src_pte); pte_unmap(dst_pte); src_pte =3D dst_pte =3D NULL; - put_swap_device(si); + put_swap_entry(entry, si); si =3D NULL; + swapoff_locked =3D false; /* now we can block and wait */ folio_lock(src_folio); goto retry; @@ -1507,8 +1510,8 @@ static long move_pages_ptes(struct mm_struct *mm, pmd= _t *dst_pmd, pmd_t *src_pmd if (dst_pte) pte_unmap(dst_pte); mmu_notifier_invalidate_range_end(&range); - if (si) - put_swap_device(si); + if (swapoff_locked) + put_swap_entry(entry, si); =20 return ret; } diff --git a/mm/zswap.c b/mm/zswap.c index ac9b7a60736bc..315e4d0d08311 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -1009,14 +1009,13 @@ static int zswap_writeback_entry(struct zswap_entry= *entry, int ret =3D 0; =20 /* try to allocate swap cache folio */ - si =3D get_swap_device(swpentry); - if (!si) + if (!tryget_swap_entry(swpentry, &si)) return -EEXIST; =20 mpol =3D get_task_policy(current); folio =3D __read_swap_cache_async(swpentry, GFP_KERNEL, mpol, NO_INTERLEAVE_INDEX, &folio_was_allocated, true); - put_swap_device(si); + put_swap_entry(swpentry, si); if (!folio) return -ENOMEM; =20 --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-ot1-f44.google.com (mail-ot1-f44.google.com [209.85.210.44]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2199134FF7F for ; Sun, 8 Feb 2026 21:58:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.44 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587932; cv=none; b=H8O04T6VeKkLztVtpZCyvk/xXYBdzoN4hCZjc/eWteVUdqVQ/Fct4sLlknVfFjmbSvgTtBfAlQCBQw+bYdolhEem+luqyDdXzuXQ7SOUbuuTLJGGo2ehWv+JgX8lMkFhUWleU5jQFl7yqxlodjH+JCMquhVkJBq020EXJq6QJeM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587932; c=relaxed/simple; bh=ODJpTK6yx8sL3Yjx3SR46wf2FGw+h0vJmlVT0y2AyfQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=m5DoWipOp/bDGa0Yq0G4YGdHqXwBCQ54NHtJ30GsdZptD3tQUQcHzrATtABvL7gDD5QPTTvBqlaKYt4tqgShbW8q4xRHENq2VNWV1KAVT9EIApcZO/BeYhoyeR5M/UFZgpTPityMn9oQN4Xhg88noJ4xVSsi4Gefm5AL661GM4A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=dG9qI0kY; arc=none smtp.client-ip=209.85.210.44 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.b="dG9qI0kY" Received: by mail-ot1-f44.google.com with SMTP id 46e09a7af769-7d196a2334fso3286672a34.1 for ; Sun, 08 Feb 2026 13:58:52 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587931; x=1771192731; 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; bh=HpwswEDlCandEKSEcjjhsX6vu11jfmhgbFRVqdS0y6A=; b=dG9qI0kYQmhW6JNCk95pxW7PPQil8zbjJFz87Ku7Nkh86EZVGIPPfNKoiPpKUmt7ah Ca/uVBL1FGUlsicpkOLBKVBeF8Tm6yKbgdvfnUokxsG2Jwl0ef/NyQXx2j9P4TrIDzYQ +hAZaq5nvpUYgyR3rDhRKvq/tpfPLSaLXoa3qfqak/nQGQwtpqJUL34fGjOXlW2V5v8E OfF4NhluWoIili8uqIAamc0ElWDSY4pF9uaYeCuv36FG7XyWD1YlHXboNTxwbZ/CfZ0q R8EKETELmcXLN8hUii6EH7dj+Z/os38EJ6fiUWe+uTIzESMFDTcEh+te/nqiVJyE429D 7Ajg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587931; x=1771192731; 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; bh=HpwswEDlCandEKSEcjjhsX6vu11jfmhgbFRVqdS0y6A=; b=DAbVfdnjcUP3cg2DlvJXl3lWjI5PbUi0k+z3aScdofOpPRK8oSu7LqTmZGFs1w+fFn PpMMwybFyWxqNYaiCHpdfoD8RBXvPGcpaHHp9+dJ79v4REswX//1wC4s1yHrJcsAZeyM q2awsiO/kp2bYkSv2jCN7AGylfOnqdKoT/+c3IPxrvJ366Yp5mYcV9F47Is23P/trIEz 96j5FVCLg71z+Wr+tPsg2hADM3CRksREdzsX4APncYKzuVIUvr7d2pCdI7zQI5ZC5zhh sEAYSn9b2Fqn7ld2CoDpFESTaWPr4OeTsOD6ZmuN6IDbWFQWHdehGWJOcgRycS3PLwn0 k4CA== X-Forwarded-Encrypted: i=1; AJvYcCVNsgt4Fe08HCSG1UtGbuLxWCfGkKpxfcCO6crBy7ub/AyCOVpvoIg1CEHI9b5tAjg+bTECmeYb0+GTa5k=@vger.kernel.org X-Gm-Message-State: AOJu0YwNeDjWhJRFqRX6FmPx/V8JP9UyMLxeNE0cfbzK5UbFNe1BSPFj nBidT3WDFmbqhZ3fHKzaW+pYFu1XoS25JcHP41T8psHei1bRlpdzGpJw X-Gm-Gg: AZuq6aIdB0X9QG5nfHHRsmfI1Cbm6XqZUT08HL7fpkPGCjStDIyEiGkmz/4Jx3vcu3/ saZrc9o8cKgmsGInvlUzfWpKB023BvigunJ10wfa494j2RffAdbU0puRznvTFWLB1Dq23/luElJ BninikHwIH5MgpKngVvT8w5yc3kKgFIhvX9XKDk9XQtmEIkSjgHTOREb7EzB2vtgR6eaGJutBZ1 JwxIrCDBYGLb44mvlFpPABzLHuEE5G2O56BCPxliFlAFz302RsKxTnckpu0IaapxyGQuo6eFaKf jH956vkMsCodqeHzlsa1bEQKtfMyJWNcQ6R0Ks8H2R/Azm17dWsks58OoHMttnCpLgB3rGbYhqV QrJ6X/UkT62dkZE3b1v+7QN+ZEgOiVmlUZ1TWKKVe3RGbTxul+dcmpwoS3EVYTmVKt2tAF8qTs5 sLdUqPTOBEE+oZsuuZht88MNdMUDHzvI2h/g== X-Received: by 2002:a05:6830:828c:b0:7d1:93ea:5bc0 with SMTP id 46e09a7af769-7d4633df66dmr5296308a34.9.1770587931097; Sun, 08 Feb 2026 13:58:51 -0800 (PST) Received: from localhost ([2a03:2880:10ff:70::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d4646fb89fsm6346653a34.1.2026.02.08.13.58.50 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:50 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 04/20] zswap: add new helpers for zswap entry operations Date: Sun, 8 Feb 2026 13:58:17 -0800 Message-ID: <20260208215839.87595-5-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add new helper functions to abstract away zswap entry operations, in order to facilitate re-implementing these functions when swap is virtualized. Signed-off-by: Nhat Pham --- mm/zswap.c | 59 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/mm/zswap.c b/mm/zswap.c index 315e4d0d08311..a5a3f068bd1a6 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -234,6 +234,38 @@ static inline struct xarray *swap_zswap_tree(swp_entry= _t swp) >> ZSWAP_ADDRESS_SPACE_SHIFT]; } =20 +static inline void *zswap_entry_store(swp_entry_t swpentry, + struct zswap_entry *entry) +{ + struct xarray *tree =3D swap_zswap_tree(swpentry); + pgoff_t offset =3D swp_offset(swpentry); + + return xa_store(tree, offset, entry, GFP_KERNEL); +} + +static inline void *zswap_entry_load(swp_entry_t swpentry) +{ + struct xarray *tree =3D swap_zswap_tree(swpentry); + pgoff_t offset =3D swp_offset(swpentry); + + return xa_load(tree, offset); +} + +static inline void *zswap_entry_erase(swp_entry_t swpentry) +{ + struct xarray *tree =3D swap_zswap_tree(swpentry); + pgoff_t offset =3D swp_offset(swpentry); + + return xa_erase(tree, offset); +} + +static inline bool zswap_empty(swp_entry_t swpentry) +{ + struct xarray *tree =3D swap_zswap_tree(swpentry); + + return xa_empty(tree); +} + #define zswap_pool_debug(msg, p) \ pr_debug("%s pool %s\n", msg, (p)->tfm_name) =20 @@ -1000,8 +1032,6 @@ static bool zswap_decompress(struct zswap_entry *entr= y, struct folio *folio) static int zswap_writeback_entry(struct zswap_entry *entry, swp_entry_t swpentry) { - struct xarray *tree; - pgoff_t offset =3D swp_offset(swpentry); struct folio *folio; struct mempolicy *mpol; bool folio_was_allocated; @@ -1040,8 +1070,7 @@ static int zswap_writeback_entry(struct zswap_entry *= entry, * old compressed data. Only when this is successful can the entry * be dereferenced. */ - tree =3D swap_zswap_tree(swpentry); - if (entry !=3D xa_load(tree, offset)) { + if (entry !=3D zswap_entry_load(swpentry)) { ret =3D -ENOMEM; goto out; } @@ -1051,7 +1080,7 @@ static int zswap_writeback_entry(struct zswap_entry *= entry, goto out; } =20 - xa_erase(tree, offset); + zswap_entry_erase(swpentry); =20 count_vm_event(ZSWPWB); if (entry->objcg) @@ -1427,9 +1456,7 @@ static bool zswap_store_page(struct page *page, if (!zswap_compress(page, entry, pool)) goto compress_failed; =20 - old =3D xa_store(swap_zswap_tree(page_swpentry), - swp_offset(page_swpentry), - entry, GFP_KERNEL); + old =3D zswap_entry_store(page_swpentry, entry); if (xa_is_err(old)) { int err =3D xa_err(old); =20 @@ -1563,11 +1590,9 @@ bool zswap_store(struct folio *folio) unsigned type =3D swp_type(swp); pgoff_t offset =3D swp_offset(swp); struct zswap_entry *entry; - struct xarray *tree; =20 for (index =3D 0; index < nr_pages; ++index) { - tree =3D swap_zswap_tree(swp_entry(type, offset + index)); - entry =3D xa_erase(tree, offset + index); + entry =3D zswap_entry_erase(swp_entry(type, offset + index)); if (entry) zswap_entry_free(entry); } @@ -1599,9 +1624,7 @@ bool zswap_store(struct folio *folio) int zswap_load(struct folio *folio) { swp_entry_t swp =3D folio->swap; - pgoff_t offset =3D swp_offset(swp); bool swapcache =3D folio_test_swapcache(folio); - struct xarray *tree =3D swap_zswap_tree(swp); struct zswap_entry *entry; =20 VM_WARN_ON_ONCE(!folio_test_locked(folio)); @@ -1619,7 +1642,7 @@ int zswap_load(struct folio *folio) return -EINVAL; } =20 - entry =3D xa_load(tree, offset); + entry =3D zswap_entry_load(swp); if (!entry) return -ENOENT; =20 @@ -1648,7 +1671,7 @@ int zswap_load(struct folio *folio) */ if (swapcache) { folio_mark_dirty(folio); - xa_erase(tree, offset); + zswap_entry_erase(swp); zswap_entry_free(entry); } =20 @@ -1658,14 +1681,12 @@ int zswap_load(struct folio *folio) =20 void zswap_invalidate(swp_entry_t swp) { - pgoff_t offset =3D swp_offset(swp); - struct xarray *tree =3D swap_zswap_tree(swp); struct zswap_entry *entry; =20 - if (xa_empty(tree)) + if (zswap_empty(swp)) return; =20 - entry =3D xa_erase(tree, offset); + entry =3D zswap_entry_erase(swp); if (entry) zswap_entry_free(entry); } --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oo1-f44.google.com (mail-oo1-f44.google.com [209.85.161.44]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 36AB835EDC1 for ; Sun, 8 Feb 2026 21:58:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.161.44 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587934; cv=none; b=FvCAbLOtJGTF2ztE/9G+kpeJdOk5tkbfhAjx/fXbuxhFJGwdfgrrjRYy3l6MAAHWWcMEacYKeIM5KYmreTZhkntyx3aSuBuYztezRCH1xznpSTZKVXXYoTjSIJeYE/LQWan+TybSwFTPhr5BhshvVdTFLNzF2yBlkUhia3RtMRs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587934; c=relaxed/simple; bh=0Qlnn/0vz2JKpfqCrEGnXX7iDLpsICWEjt16tSDKWL0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=mn3s3xZSRJTkYKh/n0k8MnVe859VR5JtFuSeVm2BIAKqVHBr5uZXLhTKw5O5HYqPWfE4jw8E23OHNG7We4zetlHVP+226i5xyNBgLYdmZGGGbsJkkRsf7aArY/Ra+ug/+bwu0iUR3UG6F36fEkgewSGzKldm8zzH8COAd0knfzo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=auk1PhKB; arc=none smtp.client-ip=209.85.161.44 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.b="auk1PhKB" Received: by mail-oo1-f44.google.com with SMTP id 006d021491bc7-6611c3b147eso1664680eaf.2 for ; Sun, 08 Feb 2026 13:58:54 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587933; x=1771192733; 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; bh=YCzAnUs0VtYcvzowlURB7PfVAQtyZ2LBB9m2XBAedLE=; b=auk1PhKBsxYRqxltOAaKXLjVDOEyDZzUzj+JtX9LUrCIFQF6bPF3dQtuyKXu9m81lc HU+U6FZm+FVJ7ReOUrZAre86MqCAZb/GWCrca75duv26SnzT71VUJnKRguKo1lW3OXQt qxO8f76iq2LmBt1xinTij06Pzn15DXRbB5RXImlM+jtUNmH7VfG62r2fwqeqCr2ez6Au UW99SgG2RwT3UbOka+bzbjE+lVI8DwwGce1GtXmergMXXhvOyG+bygae8VqilBkx+lTZ koeL0xYPYb5/+oH3vf1joCTAIPEM2KhGvxfcMDDlsxPNmZUlpsrS9IpF/nBNswO0DEWb eAuA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587933; x=1771192733; 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; bh=YCzAnUs0VtYcvzowlURB7PfVAQtyZ2LBB9m2XBAedLE=; b=KvXAGjSjA6vKVcauMEKziAIOi/5B/MTlm7VD6tOqVp9Nx87HZi8GYFrPmxME6yz/PL ezv8t5Hy1tZnp5B/Ng8zAGUFRkWa9zg5y4RINrpa6PvJEaFyEsWOjZj46UF2CBOOSAWL wN+IQsQyX2y3f5zpGyfX5XlM/qIjrdW5UF7vo+h7vy/zbq2LuNF9bWWwVdkcKElnXORu 8YA3etMIikXDo35A5ipfe0Rs4ge/885VJjNjGOORO4FEpnAgysmOhNGnPYF5iWtAXVjZ QLoXJ4AXtn8hUUXnlD7ahlDmzVSLRJz/mTlq/BiSP5ZhEQPdfG+jUBBKpGrz7bHOMu/k ULew== X-Forwarded-Encrypted: i=1; AJvYcCWqmtk3cZD46qMjJTQzF0LT7WP6NWApco3euNXidMHflkerjWJa6E7K/4XZmwxtPMqKuBfc2DQ6aelSeiY=@vger.kernel.org X-Gm-Message-State: AOJu0YzhlqY2kUfU08px+VycVoVJqAPHCA9F9Stvk1W+SRZ0B5ta6n5N egUgFEjpj2TN8oOsyzzQu0stp+RC2ZXbPoVS0WnAzMEwOpn32GNntvJY X-Gm-Gg: AZuq6aKVx90V9BzvMn7K5hHD9giAqa4+0/IKObje237JrlLLXjxjD5gH0d3KUAfUkS3 cynzZ91jkXp6jBTwCE+zp8TZskmkJgVGV5mWCbm4MiX7tbSfs41zbdp4FQSGMvoTnvZ2aOBlsia /TLaMsqYqYOq99f6FJkzGiWFjU4AlxwK8rViY3WWNg7ELm2aSqIHbE79TZ4XnfVCWaXbNogrUsq Wo9NPlbqUQGf8wuBMwxaAub4WR6cxrV1sc3heHvVaBfgXluV1F2GO++UwH6q2esGIri2AGegp1E QPXtqZk7LW9a2nRtcpcu1w4SZZtPulGJuDprMwQU/zf0OS39XmApiW0eNFXGex830VMeObyiKM8 cvGyPiSey6Whsg+VlefKu8ZppkS9KUD7YWcW/GKsuYEaof9oSfnOA29ixzlc/Jot02nLX2y2n4J wKK5pdFi9VE65xHPQLlv9vQgCnwSZ3GZeN5g== X-Received: by 2002:a05:6820:1514:b0:662:c369:8af1 with SMTP id 006d021491bc7-66d0d5e38b6mr4727396eaf.78.1770587933119; Sun, 08 Feb 2026 13:58:53 -0800 (PST) Received: from localhost ([2a03:2880:10ff:73::]) by smtp.gmail.com with ESMTPSA id 006d021491bc7-66d3adcae3csm5051168eaf.9.2026.02.08.13.58.51 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:52 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 05/20] mm/swap: add a new function to check if a swap entry is in swap cached. Date: Sun, 8 Feb 2026 13:58:18 -0800 Message-ID: <20260208215839.87595-6-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Userfaultfd checks whether a swap entry is in swapcache. This is currently done by directly looking at the swapfile's swap map - however, the swap cached state will soon be managed at the virtual swap layer. Abstract away this function. Signed-off-by: Nhat Pham --- include/linux/swap.h | 6 ++++++ mm/swapfile.c | 15 +++++++++++++++ mm/userfaultfd.c | 3 +-- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 3da637b218baf..f91a442ac0e82 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -435,6 +435,7 @@ void free_swap_and_cache_nr(swp_entry_t entry, int nr); int __swap_count(swp_entry_t entry); bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry); int swp_swapcount(swp_entry_t entry); +bool is_swap_cached(swp_entry_t entry); =20 /* Swap cache API (mm/swap_state.c) */ static inline unsigned long total_swapcache_pages(void) @@ -554,6 +555,11 @@ static inline int swp_swapcount(swp_entry_t entry) return 0; } =20 +static inline bool is_swap_cached(swp_entry_t entry) +{ + return false; +} + static inline int folio_alloc_swap(struct folio *folio) { return -EINVAL; diff --git a/mm/swapfile.c b/mm/swapfile.c index cacfafa9a540d..3c89dedbd5718 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -194,6 +194,21 @@ static bool swap_only_has_cache(struct swap_info_struc= t *si, return true; } =20 +/** + * is_swap_cached - check if the swap entry is cached + * @entry: swap entry to check + * + * Check swap_map directly to minimize overhead, READ_ONCE is sufficient. + * + * Returns true if the swap entry is cached, false otherwise. + */ +bool is_swap_cached(swp_entry_t entry) +{ + struct swap_info_struct *si =3D __swap_entry_to_info(entry); + + return READ_ONCE(si->swap_map[swp_offset(entry)]) & SWAP_HAS_CACHE; +} + static bool swap_is_last_map(struct swap_info_struct *si, unsigned long offset, int nr_pages, bool *has_cache) { diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 25f89eba0438c..98be764fb3ecd 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -1190,7 +1190,6 @@ static int move_swap_pte(struct mm_struct *mm, struct= vm_area_struct *dst_vma, * Check if the swap entry is cached after acquiring the src_pte * lock. Otherwise, we might miss a newly loaded swap cache folio. * - * Check swap_map directly to minimize overhead, READ_ONCE is sufficient. * We are trying to catch newly added swap cache, the only possible case= is * when a folio is swapped in and out again staying in swap cache, using= the * same entry before the PTE check above. The PTL is acquired and releas= ed @@ -1200,7 +1199,7 @@ static int move_swap_pte(struct mm_struct *mm, struct= vm_area_struct *dst_vma, * cache, or during the tiny synchronization window between swap cache a= nd * swap_map, but it will be gone very quickly, worst result is retry jit= ters. */ - if (READ_ONCE(si->swap_map[swp_offset(entry)]) & SWAP_HAS_CACHE) { + if (is_swap_cached(entry)) { double_pt_unlock(dst_ptl, src_ptl); return -EAGAIN; } --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oa1-f48.google.com (mail-oa1-f48.google.com [209.85.160.48]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6C070341AB6 for ; Sun, 8 Feb 2026 21:58:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.48 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587937; cv=none; b=FPRUs9jinKVQ9LHTG55/638rXLr/HL/NIoJ5xfUAyHqnK7Q7z3Ym5MNcLq0pbDVGaKH1upXXsAzLioE2kbuvXvo6ooLWmjY2twr2NI2mIO5FNShkYZR1c3CkNN4uy+GM+eoLBOqb+mybiGCrW1HlAzj8sLDdhbbwbFmo650gZ5M= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587937; c=relaxed/simple; bh=5bC6faUaLGy/PHu5yuTmAWzwC4vvMLZWKbDbaPI2Z88=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Ut+ozCy3joIf93GdDMLOAmbhbcLgXy2PT7rLzJHq9C/9/JRFdjrFcZpAFnrlAnvAnjRyceYiP0jbi53+x/rAH1AFwasPS9Kwcqs/98sps3OUhcn0TnvAcB1D1zytO7oh7vj5rGj+09UgO6GHhf/1PDGjzBU3QAW0KL8pqEJ6Phw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=XjCEo7po; arc=none smtp.client-ip=209.85.160.48 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.b="XjCEo7po" Received: by mail-oa1-f48.google.com with SMTP id 586e51a60fabf-4044d3ff57bso835135fac.0 for ; Sun, 08 Feb 2026 13:58:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587936; x=1771192736; 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; bh=eTZcPotpU0ERl3GaGoQbZ01AvvkCTOsuVIuaEZ1XAS4=; b=XjCEo7poFH2QJRxUaSgn9Lt6vVWp7Feynki2IRS9ML6vuNM8eC9K1AQdo3Ll1YyWQS hsW9lN2AzYNSyqnk6havaJUbOHPJ5shhcnXSGXpVz7ly7Ll4LoWlHytNSczq8aSLRE0+ c5slcD3y2x7NAaGaCDiAbGzES8ZTMNl0ojh6BAJZgxOJdSCva7JfJZbTSl9rz+vi0fkq D877w1kVO9zLMofOZ6cBZVHgG8TgH3Dvep27GC4VzhLkYiX9YVpmDPlPKdxiSNAEDGTW EO7eTPC3lQVgSUZB2NO96Q5BMjo4Cr4zVfBIrvoUikxU6Kls+pRVjBFzwjRj/twu/ZPf +0Ow== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587936; x=1771192736; 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; bh=eTZcPotpU0ERl3GaGoQbZ01AvvkCTOsuVIuaEZ1XAS4=; b=uKbrKyRuLcNBDE39IYv9OAzJKgGikYHC1vBMLXkk0pKzNB2G0T8sFe2eMXe9CUiQs1 hqUh6RWWZ6l5ZgJsj6wOVwbVeCR/Z8Cqo2jz4XicKEP66jcp8ZWKAV2MJ7eomjEmiuPR zOz9VHz3zVMVUAYmICHVYRNHJQd4Sl9gGH1Mvak8GHm/E31wMbZDBJx7PUVKOT//XERX FOXVs0aBHnPBZSA/MDMewow5i0ADXu2/rqkNqFWBGzx0ONKlyRAsdn/KrpR/6az4FbVQ HDve9fjTJ5Z4os1QzLhOK0oAdA0Knp7aZHzdHi0FQvWiNitBJCydd74d6m88kH1B+/vi +GiQ== X-Forwarded-Encrypted: i=1; AJvYcCVXVABsAUdYjFQFxvkcmXOkAd0ZeSt0P37FnLGPGi2YL3FRXbnKmDLl6mvQ2WlHJI2DA9Ah9VB8HqeW1QU=@vger.kernel.org X-Gm-Message-State: AOJu0Yx63HPRxxeaMQ22P3+8ZA9+Is7LNEUJtgZaNCPWMBkX4CdYdfWu v2ZYNwMuyuIqm4Q3gljppteyO53i80aaWGNpwZ51BkhN84HiUhDWDz52 X-Gm-Gg: AZuq6aKBYkP8hLj3Ot41lYMlzEW98aEGKRNjypRrwqcBVjY0N6/TxH4ruBoUZN3h7V0 yaMnlCE5dhoLcjOVzxStQpThEFU0zPJ3NlSbszjz6CU7UD8DqHx/MkAkL03Fnex/eZp+XzccFqu Piwezws97GzzZBzdIHwcv3gBGMXE3DFOtNHSRT91a0rqL0MhbtiK4rymwXzdzrftlkKQdaicGR4 eEzMaNqSaXMfsU/366ls9Zk43j6qg7qTwj04/4bmwyy0mJGGgccZTWsblhP/9YvL1VQjN3y2DSj UC0jAKJJYagHXSIT5mimif8mfDvdBWfDKi+X8g27xrrGjj1RN22QfwF34Piz3isjsuJ6L5WiFvv 5MZQZDc7qSLXbP3cwVviAjhVMWWVuNoWDz6KoUYNGYzGk7t/F5+LNi5XbZNhtpZoL58NBpVW5xo x5Fo4dn3PSLo/sz74+wAg94+Wk3yl9Z1tw X-Received: by 2002:a05:6820:207:b0:662:c684:f44b with SMTP id 006d021491bc7-66d09abcb4bmr3800043eaf.1.1770587936113; Sun, 08 Feb 2026 13:58:56 -0800 (PST) Received: from localhost ([2a03:2880:10ff:5::]) by smtp.gmail.com with ESMTPSA id 006d021491bc7-66d3b2a5aefsm4654492eaf.13.2026.02.08.13.58.53 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:54 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 06/20] mm: swap: add a separate type for physical swap slots Date: Sun, 8 Feb 2026 13:58:19 -0800 Message-ID: <20260208215839.87595-7-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" In preparation for swap virtualization, add a new type to represent the physical swap slots of swapfile. This allows us to separates: 1. The logical view of the swap entry (i.e what is stored in page table entries and used to index into the swap cache), represented by the old swp_entry_t type. from: 2. Its physical backing state (i.e the actual backing slot on the swap device), represented by the new swp_slot_t type. The functions that operate at the physical level (i.e on the swp_slot_t types) are also renamed where appropriate (prefixed with swp_slot_* for e.g). Note that we have not made any behavioral change - the mapping between the two types is the identity mapping. In later patches, we shall dynamically allocate a virtual swap slot (of type swp_entry_t) for each swapped out page to store in the page table entry, and associate it with a backing store. A physical swap slot (i.e a slot on a physical swap device) is one of the backing options. Signed-off-by: Nhat Pham --- include/linux/mm_types.h | 16 +++ include/linux/swap.h | 47 ++++-- include/linux/swapops.h | 25 ++++ kernel/power/swap.c | 6 +- mm/internal.h | 10 +- mm/page_io.c | 33 +++-- mm/shmem.c | 19 ++- mm/swap.h | 52 +++---- mm/swap_cgroup.c | 18 +-- mm/swap_state.c | 32 +++-- mm/swapfile.c | 300 ++++++++++++++++++++++----------------- 11 files changed, 352 insertions(+), 206 deletions(-) diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h index 78950eb8926dc..bffde812decc5 100644 --- a/include/linux/mm_types.h +++ b/include/linux/mm_types.h @@ -279,6 +279,13 @@ static __always_inline unsigned long encoded_nr_pages(= struct encoded_page *page) } =20 /* + * Virtual swap slot. + * + * This type is used to represent a virtual swap slot, i.e an identifier of + * a swap entry. This is stored in PTEs that originally refer to the swapp= ed + * out page, and is used to index into various swap architectures (swap ca= che, + * zswap tree, swap cgroup array, etc.). + * * A swap entry has to fit into a "unsigned long", as the entry is hidden * in the "index" field of the swapper address space. */ @@ -286,6 +293,15 @@ typedef struct { unsigned long val; } swp_entry_t; =20 +/* + * Physical swap slot. + * + * This type is used to represent a PAGE_SIZED slot on a swapfile. + */ +typedef struct { + unsigned long val; +} swp_slot_t; + /** * typedef softleaf_t - Describes a page table software leaf entry, abstra= cted * from its architecture-specific encoding. diff --git a/include/linux/swap.h b/include/linux/swap.h index f91a442ac0e82..918b47da55f44 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -241,7 +241,7 @@ enum { * cluster to which it belongs being marked free. Therefore 0 is safe to u= se as * a sentinel to indicate an entry is not valid. */ -#define SWAP_ENTRY_INVALID 0 +#define SWAP_SLOT_INVALID 0 =20 #ifdef CONFIG_THP_SWAP #define SWAP_NR_ORDERS (PMD_ORDER + 1) @@ -442,11 +442,14 @@ static inline unsigned long total_swapcache_pages(voi= d) { return global_node_page_state(NR_SWAPCACHE); } + void free_folio_and_swap_cache(struct folio *folio); void free_pages_and_swap_cache(struct encoded_page **, int); void free_swap_cache(struct folio *folio); =20 /* Physical swap allocator and swap device API (mm/swapfile.c) */ +void swap_slot_free_nr(swp_slot_t slot, int nr_pages); + int add_swap_extent(struct swap_info_struct *sis, unsigned long start_page, unsigned long nr_pages, sector_t start_block); int generic_swapfile_activate(struct swap_info_struct *, struct file *, @@ -468,28 +471,28 @@ static inline long get_nr_swap_pages(void) } =20 void si_swapinfo(struct sysinfo *); -swp_entry_t get_swap_page_of_type(int); +swp_slot_t swap_slot_alloc_of_type(int); int add_swap_count_continuation(swp_entry_t, gfp_t); int swap_type_of(dev_t device, sector_t offset); int find_first_swap(dev_t *device); unsigned int count_swap_pages(int, int); sector_t swapdev_block(int, pgoff_t); struct backing_dev_info; -struct swap_info_struct *get_swap_device(swp_entry_t entry); +struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot_t slot); sector_t swap_folio_sector(struct folio *folio); =20 -static inline void put_swap_device(struct swap_info_struct *si) +static inline void swap_slot_put_swap_info(struct swap_info_struct *si) { percpu_ref_put(&si->users); } =20 #else /* CONFIG_SWAP */ -static inline struct swap_info_struct *get_swap_device(swp_entry_t entry) +static inline struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot= _t slot) { return NULL; } =20 -static inline void put_swap_device(struct swap_info_struct *si) +static inline void swap_slot_put_swap_info(struct swap_info_struct *si) { } =20 @@ -536,7 +539,7 @@ static inline void swap_free_nr(swp_entry_t entry, int = nr_pages) { } =20 -static inline void put_swap_folio(struct folio *folio, swp_entry_t swp) +static inline void put_swap_folio(struct folio *folio, swp_entry_t entry) { } =20 @@ -576,6 +579,7 @@ static inline int add_swap_extent(struct swap_info_stru= ct *sis, { return -EINVAL; } + #endif /* CONFIG_SWAP */ =20 static inline void free_swap_and_cache(swp_entry_t entry) @@ -665,10 +669,35 @@ static inline bool mem_cgroup_swap_full(struct folio = *folio) } #endif =20 +/** + * swp_entry_to_swp_slot - look up the physical swap slot corresponding to= a + * virtual swap slot. + * @entry: the virtual swap slot. + * + * Return: the physical swap slot corresponding to the virtual swap slot. + */ +static inline swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry) +{ + return (swp_slot_t) { entry.val }; +} + +/** + * swp_slot_to_swp_entry - look up the virtual swap slot corresponding to a + * physical swap slot. + * @slot: the physical swap slot. + * + * Return: the virtual swap slot corresponding to the physical swap slot. + */ +static inline swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot) +{ + return (swp_entry_t) { slot.val }; +} + static inline bool tryget_swap_entry(swp_entry_t entry, struct swap_info_struct **sip) { - struct swap_info_struct *si =3D get_swap_device(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + struct swap_info_struct *si =3D swap_slot_tryget_swap_info(slot); =20 if (sip) *sip =3D si; @@ -679,7 +708,7 @@ static inline bool tryget_swap_entry(swp_entry_t entry, static inline void put_swap_entry(swp_entry_t entry, struct swap_info_struct *si) { - put_swap_device(si); + swap_slot_put_swap_info(si); } =20 #endif /* __KERNEL__*/ diff --git a/include/linux/swapops.h b/include/linux/swapops.h index 8cfc966eae48e..9e41c35664a95 100644 --- a/include/linux/swapops.h +++ b/include/linux/swapops.h @@ -360,5 +360,30 @@ static inline pmd_t swp_entry_to_pmd(swp_entry_t entry) =20 #endif /* CONFIG_ARCH_ENABLE_THP_MIGRATION */ =20 +/* Physical swap slots operations */ + +/* + * Store a swap device type + offset into a swp_slot_t handle. + */ +static inline swp_slot_t swp_slot(unsigned long type, pgoff_t offset) +{ + swp_slot_t ret; + + ret.val =3D (type << SWP_TYPE_SHIFT) | (offset & SWP_OFFSET_MASK); + return ret; +} + +/* Extract the `type' field from a swp_slot_t. */ +static inline unsigned swp_slot_type(swp_slot_t slot) +{ + return (slot.val >> SWP_TYPE_SHIFT); +} + +/* Extract the `offset' field from a swp_slot_t. */ +static inline pgoff_t swp_slot_offset(swp_slot_t slot) +{ + return slot.val & SWP_OFFSET_MASK; +} + #endif /* CONFIG_MMU */ #endif /* _LINUX_SWAPOPS_H */ diff --git a/kernel/power/swap.c b/kernel/power/swap.c index 8050e51828351..0129c5ffa649d 100644 --- a/kernel/power/swap.c +++ b/kernel/power/swap.c @@ -174,10 +174,10 @@ sector_t alloc_swapdev_block(int swap) * Allocate a swap page and register that it has been allocated, so that * it can be freed in case of an error. */ - offset =3D swp_offset(get_swap_page_of_type(swap)); + offset =3D swp_slot_offset(swap_slot_alloc_of_type(swap)); if (offset) { if (swsusp_extents_insert(offset)) - swap_free(swp_entry(swap, offset)); + swap_slot_free_nr(swp_slot(swap, offset), 1); else return swapdev_block(swap, offset); } @@ -197,7 +197,7 @@ void free_all_swap_pages(int swap) =20 ext =3D rb_entry(node, struct swsusp_extent, node); rb_erase(node, &swsusp_extents); - swap_free_nr(swp_entry(swap, ext->start), + swap_slot_free_nr(swp_slot(swap, ext->start), ext->end - ext->start + 1); =20 kfree(ext); diff --git a/mm/internal.h b/mm/internal.h index f35dbcf99a86b..e739e8cac5b55 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -334,9 +334,13 @@ unsigned int folio_pte_batch(struct folio *folio, pte_= t *ptep, pte_t pte, */ static inline pte_t pte_move_swp_offset(pte_t pte, long delta) { - const softleaf_t entry =3D softleaf_from_pte(pte); - pte_t new =3D __swp_entry_to_pte(__swp_entry(swp_type(entry), - (swp_offset(entry) + delta))); + softleaf_t entry =3D softleaf_from_pte(pte), new_entry; + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + pte_t new; + + new_entry =3D swp_slot_to_swp_entry(swp_slot(swp_slot_type(slot), + swp_slot_offset(slot) + delta)); + new =3D swp_entry_to_pte(new_entry); =20 if (pte_swp_soft_dirty(pte)) new =3D pte_swp_mksoft_dirty(new); diff --git a/mm/page_io.c b/mm/page_io.c index 3c342db77ce38..0b02bcc85e2a8 100644 --- a/mm/page_io.c +++ b/mm/page_io.c @@ -204,14 +204,17 @@ static bool is_folio_zero_filled(struct folio *folio) static void swap_zeromap_folio_set(struct folio *folio) { struct obj_cgroup *objcg =3D get_obj_cgroup_from_folio(folio); - struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); + struct swap_info_struct *sis =3D + __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); int nr_pages =3D folio_nr_pages(folio); swp_entry_t entry; + swp_slot_t slot; unsigned int i; =20 for (i =3D 0; i < folio_nr_pages(folio); i++) { entry =3D page_swap_entry(folio_page(folio, i)); - set_bit(swp_offset(entry), sis->zeromap); + slot =3D swp_entry_to_swp_slot(entry); + set_bit(swp_slot_offset(slot), sis->zeromap); } =20 count_vm_events(SWPOUT_ZERO, nr_pages); @@ -223,13 +226,16 @@ static void swap_zeromap_folio_set(struct folio *foli= o) =20 static void swap_zeromap_folio_clear(struct folio *folio) { - struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); + struct swap_info_struct *sis =3D + __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); swp_entry_t entry; + swp_slot_t slot; unsigned int i; =20 for (i =3D 0; i < folio_nr_pages(folio); i++) { entry =3D page_swap_entry(folio_page(folio, i)); - clear_bit(swp_offset(entry), sis->zeromap); + slot =3D swp_entry_to_swp_slot(entry); + clear_bit(swp_slot_offset(slot), sis->zeromap); } } =20 @@ -357,7 +363,8 @@ static void sio_write_complete(struct kiocb *iocb, long= ret) * messages. */ pr_err_ratelimited("Write error %ld on dio swapfile (%llu)\n", - ret, swap_dev_pos(page_swap_entry(page))); + ret, + swap_slot_pos(swp_entry_to_swp_slot(page_swap_entry(page)))); for (p =3D 0; p < sio->pages; p++) { page =3D sio->bvec[p].bv_page; set_page_dirty(page); @@ -374,9 +381,10 @@ static void sio_write_complete(struct kiocb *iocb, lon= g ret) static void swap_writepage_fs(struct folio *folio, struct swap_iocb **swap= _plug) { struct swap_iocb *sio =3D swap_plug ? *swap_plug : NULL; - struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); + swp_slot_t slot =3D swp_entry_to_swp_slot(folio->swap); + struct swap_info_struct *sis =3D __swap_slot_to_info(slot); struct file *swap_file =3D sis->swap_file; - loff_t pos =3D swap_dev_pos(folio->swap); + loff_t pos =3D swap_slot_pos(slot); =20 count_swpout_vm_event(folio); folio_start_writeback(folio); @@ -446,7 +454,8 @@ static void swap_writepage_bdev_async(struct folio *fol= io, =20 void __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug) { - struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); + struct swap_info_struct *sis =3D + __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); =20 VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio); /* @@ -537,9 +546,10 @@ static bool swap_read_folio_zeromap(struct folio *foli= o) =20 static void swap_read_folio_fs(struct folio *folio, struct swap_iocb **plu= g) { - struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); + swp_slot_t slot =3D swp_entry_to_swp_slot(folio->swap); + struct swap_info_struct *sis =3D __swap_slot_to_info(slot); struct swap_iocb *sio =3D NULL; - loff_t pos =3D swap_dev_pos(folio->swap); + loff_t pos =3D swap_slot_pos(slot); =20 if (plug) sio =3D *plug; @@ -608,7 +618,8 @@ static void swap_read_folio_bdev_async(struct folio *fo= lio, =20 void swap_read_folio(struct folio *folio, struct swap_iocb **plug) { - struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); + struct swap_info_struct *sis =3D + __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); bool synchronous =3D sis->flags & SWP_SYNCHRONOUS_IO; bool workingset =3D folio_test_workingset(folio); unsigned long pflags; diff --git a/mm/shmem.c b/mm/shmem.c index b40be22fa5f09..400e2fa8e77cb 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -1442,6 +1442,7 @@ static unsigned int shmem_find_swap_entries(struct ad= dress_space *mapping, XA_STATE(xas, &mapping->i_pages, start); struct folio *folio; swp_entry_t entry; + swp_slot_t slot; =20 rcu_read_lock(); xas_for_each(&xas, folio, ULONG_MAX) { @@ -1452,11 +1453,13 @@ static unsigned int shmem_find_swap_entries(struct = address_space *mapping, continue; =20 entry =3D radix_to_swp_entry(folio); + slot =3D swp_entry_to_swp_slot(entry); + /* * swapin error entries can be found in the mapping. But they're * deliberately ignored here as we've done everything we can do. */ - if (swp_type(entry) !=3D type) + if (swp_slot_type(slot) !=3D type) continue; =20 indices[folio_batch_count(fbatch)] =3D xas.xa_index; @@ -2224,6 +2227,7 @@ static int shmem_split_large_entry(struct inode *inod= e, pgoff_t index, XA_STATE_ORDER(xas, &mapping->i_pages, index, 0); int split_order =3D 0; int i; + swp_slot_t slot =3D swp_entry_to_swp_slot(swap); =20 /* Convert user data gfp flags to xarray node gfp flags */ gfp &=3D GFP_RECLAIM_MASK; @@ -2264,13 +2268,16 @@ static int shmem_split_large_entry(struct inode *in= ode, pgoff_t index, */ for (i =3D 0; i < 1 << cur_order; i +=3D (1 << split_order)) { - swp_entry_t tmp; + swp_entry_t tmp_entry; + swp_slot_t tmp_slot; + + tmp_slot =3D + swp_slot(swp_slot_type(slot), + swp_slot_offset(slot) + swap_offset + i); + tmp_entry =3D swp_slot_to_swp_entry(tmp_slot); =20 - tmp =3D swp_entry(swp_type(swap), - swp_offset(swap) + swap_offset + - i); __xa_store(&mapping->i_pages, aligned_index + i, - swp_to_radix_entry(tmp), 0); + swp_to_radix_entry(tmp_entry), 0); } cur_order =3D split_order; split_order =3D xas_try_split_min_order(split_order); diff --git a/mm/swap.h b/mm/swap.h index 8726b587a5b5d..bdf7aca146643 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -10,10 +10,10 @@ extern int page_cluster; =20 #ifdef CONFIG_THP_SWAP #define SWAPFILE_CLUSTER HPAGE_PMD_NR -#define swap_entry_order(order) (order) +#define swap_slot_order(order) (order) #else #define SWAPFILE_CLUSTER 256 -#define swap_entry_order(order) 0 +#define swap_slot_order(order) 0 #endif =20 extern struct swap_info_struct *swap_info[]; @@ -57,9 +57,9 @@ enum swap_cluster_flags { #include /* for swp_offset */ #include /* for bio_end_io_t */ =20 -static inline unsigned int swp_cluster_offset(swp_entry_t entry) +static inline unsigned int swp_cluster_offset(swp_slot_t slot) { - return swp_offset(entry) % SWAPFILE_CLUSTER; + return swp_slot_offset(slot) % SWAPFILE_CLUSTER; } =20 /* @@ -75,9 +75,9 @@ static inline struct swap_info_struct *__swap_type_to_inf= o(int type) return si; } =20 -static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t en= try) +static inline struct swap_info_struct *__swap_slot_to_info(swp_slot_t slot) { - return __swap_type_to_info(swp_type(entry)); + return __swap_type_to_info(swp_slot_type(slot)); } =20 static inline struct swap_cluster_info *__swap_offset_to_cluster( @@ -88,10 +88,10 @@ static inline struct swap_cluster_info *__swap_offset_t= o_cluster( return &si->cluster_info[offset / SWAPFILE_CLUSTER]; } =20 -static inline struct swap_cluster_info *__swap_entry_to_cluster(swp_entry_= t entry) +static inline struct swap_cluster_info *__swap_slot_to_cluster(swp_slot_t = slot) { - return __swap_offset_to_cluster(__swap_entry_to_info(entry), - swp_offset(entry)); + return __swap_offset_to_cluster(__swap_slot_to_info(slot), + swp_slot_offset(slot)); } =20 static __always_inline struct swap_cluster_info *__swap_cluster_lock( @@ -120,7 +120,7 @@ static __always_inline struct swap_cluster_info *__swap= _cluster_lock( /** * swap_cluster_lock - Lock and return the swap cluster of given offset. * @si: swap device the cluster belongs to. - * @offset: the swap entry offset, pointing to a valid slot. + * @offset: the swap slot offset, pointing to a valid slot. * * Context: The caller must ensure the offset is in the valid range and * protect the swap device with reference count or locks. @@ -134,10 +134,12 @@ static inline struct swap_cluster_info *swap_cluster_= lock( static inline struct swap_cluster_info *__swap_cluster_get_and_lock( const struct folio *folio, bool irq) { + swp_slot_t slot =3D swp_entry_to_swp_slot(folio->swap); + VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); - return __swap_cluster_lock(__swap_entry_to_info(folio->swap), - swp_offset(folio->swap), irq); + return __swap_cluster_lock(__swap_slot_to_info(slot), + swp_slot_offset(slot), irq); } =20 /* @@ -209,12 +211,10 @@ static inline struct address_space *swap_address_spac= e(swp_entry_t entry) return &swap_space; } =20 -/* - * Return the swap device position of the swap entry. - */ -static inline loff_t swap_dev_pos(swp_entry_t entry) +/* Return the swap device position of the swap slot. */ +static inline loff_t swap_slot_pos(swp_slot_t slot) { - return ((loff_t)swp_offset(entry)) << PAGE_SHIFT; + return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT; } =20 /** @@ -276,7 +276,9 @@ void swap_update_readahead(struct folio *folio, struct = vm_area_struct *vma, =20 static inline unsigned int folio_swap_flags(struct folio *folio) { - return __swap_entry_to_info(folio->swap)->flags; + swp_slot_t swp_slot =3D swp_entry_to_swp_slot(folio->swap); + + return __swap_slot_to_info(swp_slot)->flags; } =20 /* @@ -287,8 +289,9 @@ static inline unsigned int folio_swap_flags(struct foli= o *folio) static inline int swap_zeromap_batch(swp_entry_t entry, int max_nr, bool *is_zeromap) { - struct swap_info_struct *sis =3D __swap_entry_to_info(entry); - unsigned long start =3D swp_offset(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + struct swap_info_struct *sis =3D __swap_slot_to_info(slot); + unsigned long start =3D swp_slot_offset(slot); unsigned long end =3D start + max_nr; bool first_bit; =20 @@ -306,8 +309,9 @@ static inline int swap_zeromap_batch(swp_entry_t entry,= int max_nr, =20 static inline int non_swapcache_batch(swp_entry_t entry, int max_nr) { - struct swap_info_struct *si =3D __swap_entry_to_info(entry); - pgoff_t offset =3D swp_offset(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + struct swap_info_struct *si =3D __swap_slot_to_info(slot); + pgoff_t offset =3D swp_slot_offset(slot); int i; =20 /* @@ -326,7 +330,7 @@ static inline int non_swapcache_batch(swp_entry_t entry= , int max_nr) #else /* CONFIG_SWAP */ struct swap_iocb; static inline struct swap_cluster_info *swap_cluster_lock( - struct swap_info_struct *si, pgoff_t offset, bool irq) + struct swap_info_struct *si, unsigned long offset) { return NULL; } @@ -351,7 +355,7 @@ static inline void swap_cluster_unlock_irq(struct swap_= cluster_info *ci) { } =20 -static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t en= try) +static inline struct swap_info_struct *__swap_slot_to_info(swp_slot_t slot) { return NULL; } diff --git a/mm/swap_cgroup.c b/mm/swap_cgroup.c index de779fed8c210..77ce1d66c318d 100644 --- a/mm/swap_cgroup.c +++ b/mm/swap_cgroup.c @@ -65,13 +65,14 @@ void swap_cgroup_record(struct folio *folio, unsigned s= hort id, swp_entry_t ent) { unsigned int nr_ents =3D folio_nr_pages(folio); + swp_slot_t slot =3D swp_entry_to_swp_slot(ent); struct swap_cgroup *map; pgoff_t offset, end; unsigned short old; =20 - offset =3D swp_offset(ent); + offset =3D swp_slot_offset(slot); end =3D offset + nr_ents; - map =3D swap_cgroup_ctrl[swp_type(ent)].map; + map =3D swap_cgroup_ctrl[swp_slot_type(slot)].map; =20 do { old =3D __swap_cgroup_id_xchg(map, offset, id); @@ -92,13 +93,13 @@ void swap_cgroup_record(struct folio *folio, unsigned s= hort id, */ unsigned short swap_cgroup_clear(swp_entry_t ent, unsigned int nr_ents) { - pgoff_t offset, end; + swp_slot_t slot =3D swp_entry_to_swp_slot(ent); + pgoff_t offset =3D swp_slot_offset(slot); + pgoff_t end =3D offset + nr_ents; struct swap_cgroup *map; unsigned short old, iter =3D 0; =20 - offset =3D swp_offset(ent); - end =3D offset + nr_ents; - map =3D swap_cgroup_ctrl[swp_type(ent)].map; + map =3D swap_cgroup_ctrl[swp_slot_type(slot)].map; =20 do { old =3D __swap_cgroup_id_xchg(map, offset, 0); @@ -119,12 +120,13 @@ unsigned short swap_cgroup_clear(swp_entry_t ent, uns= igned int nr_ents) unsigned short lookup_swap_cgroup_id(swp_entry_t ent) { struct swap_cgroup_ctrl *ctrl; + swp_slot_t slot =3D swp_entry_to_swp_slot(ent); =20 if (mem_cgroup_disabled()) return 0; =20 - ctrl =3D &swap_cgroup_ctrl[swp_type(ent)]; - return __swap_cgroup_id_lookup(ctrl->map, swp_offset(ent)); + ctrl =3D &swap_cgroup_ctrl[swp_slot_type(slot)]; + return __swap_cgroup_id_lookup(ctrl->map, swp_slot_offset(slot)); } =20 int swap_cgroup_swapon(int type, unsigned long max_pages) diff --git a/mm/swap_state.c b/mm/swap_state.c index bece18eb540fa..e2e9f55bea3bb 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -421,7 +421,8 @@ struct folio *__read_swap_cache_async(swp_entry_t entry= , gfp_t gfp_mask, struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated, bool skip_if_exists) { - struct swap_info_struct *si =3D __swap_entry_to_info(entry); + struct swap_info_struct *si =3D + __swap_slot_to_info(swp_entry_to_swp_slot(entry)); struct folio *folio; struct folio *new_folio =3D NULL; struct folio *result =3D NULL; @@ -636,11 +637,12 @@ struct folio *swap_cluster_readahead(swp_entry_t entr= y, gfp_t gfp_mask, struct mempolicy *mpol, pgoff_t ilx) { struct folio *folio; - unsigned long entry_offset =3D swp_offset(entry); - unsigned long offset =3D entry_offset; + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + unsigned long slot_offset =3D swp_slot_offset(slot); + unsigned long offset =3D slot_offset; unsigned long start_offset, end_offset; unsigned long mask; - struct swap_info_struct *si =3D __swap_entry_to_info(entry); + struct swap_info_struct *si =3D __swap_slot_to_info(slot); struct blk_plug plug; struct swap_iocb *splug =3D NULL; bool page_allocated; @@ -661,13 +663,13 @@ struct folio *swap_cluster_readahead(swp_entry_t entr= y, gfp_t gfp_mask, for (offset =3D start_offset; offset <=3D end_offset ; offset++) { /* Ok, do the async read-ahead now */ folio =3D __read_swap_cache_async( - swp_entry(swp_type(entry), offset), + swp_slot_to_swp_entry(swp_slot(swp_slot_type(slot), offset)), gfp_mask, mpol, ilx, &page_allocated, false); if (!folio) continue; if (page_allocated) { swap_read_folio(folio, &splug); - if (offset !=3D entry_offset) { + if (offset !=3D slot_offset) { folio_set_readahead(folio); count_vm_event(SWAP_RA); } @@ -779,16 +781,20 @@ static struct folio *swap_vma_readahead(swp_entry_t t= arg_entry, gfp_t gfp_mask, /* * Readahead entry may come from a device that we are not * holding a reference to, try to grab a reference, or skip. + * + * XXX: for now, always try to pin the swap entries in the + * readahead window to avoid the annoying conversion to physical + * swap slots. Once we move all swap metadata to virtual swap + * layer, we can simply compare the clusters of the target + * swap entry and the current swap entry, and pin the latter + * swap entry's cluster if it differ from the former's. */ - if (swp_type(entry) !=3D swp_type(targ_entry)) { - swapoff_locked =3D tryget_swap_entry(entry, &si); - if (!swapoff_locked) - continue; - } + swapoff_locked =3D tryget_swap_entry(entry, &si); + if (!swapoff_locked) + continue; folio =3D __read_swap_cache_async(entry, gfp_mask, mpol, ilx, &page_allocated, false); - if (swapoff_locked) - put_swap_entry(entry, si); + put_swap_entry(entry, si); if (!folio) continue; if (page_allocated) { diff --git a/mm/swapfile.c b/mm/swapfile.c index 3c89dedbd5718..4b4126d4e2769 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -53,9 +53,9 @@ static bool swap_count_continued(struct swap_info_struct *, pgoff_t, unsigned char); static void free_swap_count_continuations(struct swap_info_struct *); -static void swap_entries_free(struct swap_info_struct *si, +static void swap_slots_free(struct swap_info_struct *si, struct swap_cluster_info *ci, - swp_entry_t entry, unsigned int nr_pages); + swp_slot_t slot, unsigned int nr_pages); static void swap_range_alloc(struct swap_info_struct *si, unsigned int nr_entries); static bool folio_swapcache_freeable(struct folio *folio); @@ -126,7 +126,7 @@ struct percpu_swap_cluster { =20 static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) =3D= { .si =3D { NULL }, - .offset =3D { SWAP_ENTRY_INVALID }, + .offset =3D { SWAP_SLOT_INVALID }, .lock =3D INIT_LOCAL_LOCK(), }; =20 @@ -139,9 +139,9 @@ static struct swap_info_struct *swap_type_to_info(int t= ype) } =20 /* May return NULL on invalid entry, caller must check for NULL return */ -static struct swap_info_struct *swap_entry_to_info(swp_entry_t entry) +static struct swap_info_struct *swap_slot_to_info(swp_slot_t slot) { - return swap_type_to_info(swp_type(entry)); + return swap_type_to_info(swp_slot_type(slot)); } =20 static inline unsigned char swap_count(unsigned char ent) @@ -204,9 +204,11 @@ static bool swap_only_has_cache(struct swap_info_struc= t *si, */ bool is_swap_cached(swp_entry_t entry) { - struct swap_info_struct *si =3D __swap_entry_to_info(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + struct swap_info_struct *si =3D swap_slot_to_info(slot); + unsigned long offset =3D swp_slot_offset(slot); =20 - return READ_ONCE(si->swap_map[swp_offset(entry)]) & SWAP_HAS_CACHE; + return READ_ONCE(si->swap_map[offset]) & SWAP_HAS_CACHE; } =20 static bool swap_is_last_map(struct swap_info_struct *si, @@ -236,7 +238,9 @@ static bool swap_is_last_map(struct swap_info_struct *s= i, static int __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset, unsigned long flags) { - const swp_entry_t entry =3D swp_entry(si->type, offset); + const swp_entry_t entry =3D + swp_slot_to_swp_entry(swp_slot(si->type, offset)); + swp_slot_t slot; struct swap_cluster_info *ci; struct folio *folio; int ret, nr_pages; @@ -268,7 +272,8 @@ static int __try_to_reclaim_swap(struct swap_info_struc= t *si, folio_put(folio); goto again; } - offset =3D swp_offset(folio->swap); + slot =3D swp_entry_to_swp_slot(folio->swap); + offset =3D swp_slot_offset(slot); =20 need_reclaim =3D ((flags & TTRS_ANYWAY) || ((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) || @@ -368,12 +373,12 @@ offset_to_swap_extent(struct swap_info_struct *sis, u= nsigned long offset) =20 sector_t swap_folio_sector(struct folio *folio) { - struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); + swp_slot_t slot =3D swp_entry_to_swp_slot(folio->swap); + struct swap_info_struct *sis =3D __swap_slot_to_info(slot); struct swap_extent *se; sector_t sector; - pgoff_t offset; + pgoff_t offset =3D swp_slot_offset(slot); =20 - offset =3D swp_offset(folio->swap); se =3D offset_to_swap_extent(sis, offset); sector =3D se->start_block + (offset - se->start_page); return sector << (PAGE_SHIFT - 9); @@ -890,7 +895,7 @@ static unsigned int alloc_swap_scan_cluster(struct swap= _info_struct *si, unsigned int order, unsigned char usage) { - unsigned int next =3D SWAP_ENTRY_INVALID, found =3D SWAP_ENTRY_INVALID; + unsigned int next =3D SWAP_SLOT_INVALID, found =3D SWAP_SLOT_INVALID; unsigned long start =3D ALIGN_DOWN(offset, SWAPFILE_CLUSTER); unsigned long end =3D min(start + SWAPFILE_CLUSTER, si->max); unsigned int nr_pages =3D 1 << order; @@ -947,7 +952,7 @@ static unsigned int alloc_swap_scan_list(struct swap_in= fo_struct *si, unsigned char usage, bool scan_all) { - unsigned int found =3D SWAP_ENTRY_INVALID; + unsigned int found =3D SWAP_SLOT_INVALID; =20 do { struct swap_cluster_info *ci =3D isolate_lock_cluster(si, list); @@ -1017,11 +1022,11 @@ static void swap_reclaim_work(struct work_struct *w= ork) * Try to allocate swap entries with specified order and try set a new * cluster for current CPU too. */ -static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,= int order, +static unsigned long cluster_alloc_swap_slot(struct swap_info_struct *si, = int order, unsigned char usage) { struct swap_cluster_info *ci; - unsigned int offset =3D SWAP_ENTRY_INVALID, found =3D SWAP_ENTRY_INVALID; + unsigned int offset =3D SWAP_SLOT_INVALID, found =3D SWAP_SLOT_INVALID; =20 /* * Swapfile is not block device so unable @@ -1034,7 +1039,7 @@ static unsigned long cluster_alloc_swap_entry(struct = swap_info_struct *si, int o /* Serialize HDD SWAP allocation for each device. */ spin_lock(&si->global_cluster_lock); offset =3D si->global_cluster->next[order]; - if (offset =3D=3D SWAP_ENTRY_INVALID) + if (offset =3D=3D SWAP_SLOT_INVALID) goto new_cluster; =20 ci =3D swap_cluster_lock(si, offset); @@ -1255,7 +1260,7 @@ static void swap_range_free(struct swap_info_struct *= si, unsigned long offset, */ for (i =3D 0; i < nr_entries; i++) { clear_bit(offset + i, si->zeromap); - zswap_invalidate(swp_entry(si->type, offset + i)); + zswap_invalidate(swp_slot_to_swp_entry(swp_slot(si->type, offset + i))); } =20 if (si->flags & SWP_BLKDEV) @@ -1300,12 +1305,11 @@ static bool get_swap_device_info(struct swap_info_s= truct *si) * Fast path try to get swap entries with specified order from current * CPU's swap entry pool (a cluster). */ -static bool swap_alloc_fast(swp_entry_t *entry, - int order) +static bool swap_alloc_fast(swp_slot_t *slot, int order) { struct swap_cluster_info *ci; struct swap_info_struct *si; - unsigned int offset, found =3D SWAP_ENTRY_INVALID; + unsigned int offset, found =3D SWAP_SLOT_INVALID; =20 /* * Once allocated, swap_info_struct will never be completely freed, @@ -1322,18 +1326,17 @@ static bool swap_alloc_fast(swp_entry_t *entry, offset =3D cluster_offset(si, ci); found =3D alloc_swap_scan_cluster(si, ci, offset, order, SWAP_HAS_CACHE); if (found) - *entry =3D swp_entry(si->type, found); + *slot =3D swp_slot(si->type, found); } else { swap_cluster_unlock(ci); } =20 - put_swap_device(si); + swap_slot_put_swap_info(si); return !!found; } =20 /* Rotate the device and switch to a new cluster */ -static void swap_alloc_slow(swp_entry_t *entry, - int order) +static void swap_alloc_slow(swp_slot_t *slot, int order) { unsigned long offset; struct swap_info_struct *si, *next; @@ -1345,10 +1348,10 @@ static void swap_alloc_slow(swp_entry_t *entry, plist_requeue(&si->avail_list, &swap_avail_head); spin_unlock(&swap_avail_lock); if (get_swap_device_info(si)) { - offset =3D cluster_alloc_swap_entry(si, order, SWAP_HAS_CACHE); - put_swap_device(si); + offset =3D cluster_alloc_swap_slot(si, order, SWAP_HAS_CACHE); + swap_slot_put_swap_info(si); if (offset) { - *entry =3D swp_entry(si->type, offset); + *slot =3D swp_slot(si->type, offset); return; } if (order) @@ -1388,7 +1391,7 @@ static bool swap_sync_discard(void) if (get_swap_device_info(si)) { if (si->flags & SWP_PAGE_DISCARD) ret =3D swap_do_scheduled_discard(si); - put_swap_device(si); + swap_slot_put_swap_info(si); } if (ret) return true; @@ -1402,25 +1405,9 @@ static bool swap_sync_discard(void) return false; } =20 -/** - * folio_alloc_swap - allocate swap space for a folio - * @folio: folio we want to move to swap - * - * Allocate swap space for the folio and add the folio to the - * swap cache. - * - * Context: Caller needs to hold the folio lock. - * Return: Whether the folio was added to the swap cache. - */ -int folio_alloc_swap(struct folio *folio) +static int swap_slot_alloc(swp_slot_t *slot, unsigned int order) { - unsigned int order =3D folio_order(folio); unsigned int size =3D 1 << order; - swp_entry_t entry =3D {}; - int err; - - VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); - VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio); =20 if (order) { /* @@ -1442,22 +1429,52 @@ int folio_alloc_swap(struct folio *folio) =20 again: local_lock(&percpu_swap_cluster.lock); - if (!swap_alloc_fast(&entry, order)) - swap_alloc_slow(&entry, order); + if (!swap_alloc_fast(slot, order)) + swap_alloc_slow(slot, order); local_unlock(&percpu_swap_cluster.lock); =20 - if (unlikely(!order && !entry.val)) { + if (unlikely(!order && !slot->val)) { if (swap_sync_discard()) goto again; } =20 + return 0; +} + +/** + * folio_alloc_swap - allocate swap space for a folio + * @folio: folio we want to move to swap + * + * Allocate swap space for the folio and add the folio to the + * swap cache. + * + * Context: Caller needs to hold the folio lock. + * Return: Whether the folio was added to the swap cache. + */ +int folio_alloc_swap(struct folio *folio) +{ + unsigned int order =3D folio_order(folio); + swp_slot_t slot =3D { 0 }; + swp_entry_t entry =3D {}; + int err =3D 0, ret; + + VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); + VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio); + + ret =3D swap_slot_alloc(&slot, order); + if (ret) + return ret; + + /* XXX: for now, physical and virtual swap slots are identical */ + entry.val =3D slot.val; + /* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */ if (mem_cgroup_try_charge_swap(folio, entry)) { err =3D -ENOMEM; goto out_free; } =20 - if (!entry.val) + if (!slot.val) return -ENOMEM; =20 err =3D swap_cache_add_folio(folio, entry, __GFP_HIGH | __GFP_NOMEMALLOC = | __GFP_NOWARN, NULL); @@ -1471,46 +1488,46 @@ int folio_alloc_swap(struct folio *folio) return err; } =20 -static struct swap_info_struct *_swap_info_get(swp_entry_t entry) +static struct swap_info_struct *_swap_info_get(swp_slot_t slot) { struct swap_info_struct *si; unsigned long offset; =20 - if (!entry.val) + if (!slot.val) goto out; - si =3D swap_entry_to_info(entry); + si =3D swap_slot_to_info(slot); if (!si) goto bad_nofile; if (data_race(!(si->flags & SWP_USED))) goto bad_device; - offset =3D swp_offset(entry); + offset =3D swp_slot_offset(slot); if (offset >=3D si->max) goto bad_offset; - if (data_race(!si->swap_map[swp_offset(entry)])) + if (data_race(!si->swap_map[swp_slot_offset(slot)])) goto bad_free; return si; =20 bad_free: - pr_err("%s: %s%08lx\n", __func__, Unused_offset, entry.val); + pr_err("%s: %s%08lx\n", __func__, Unused_offset, slot.val); goto out; bad_offset: - pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val); + pr_err("%s: %s%08lx\n", __func__, Bad_offset, slot.val); goto out; bad_device: - pr_err("%s: %s%08lx\n", __func__, Unused_file, entry.val); + pr_err("%s: %s%08lx\n", __func__, Unused_file, slot.val); goto out; bad_nofile: - pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val); + pr_err("%s: %s%08lx\n", __func__, Bad_file, slot.val); out: return NULL; } =20 -static unsigned char swap_entry_put_locked(struct swap_info_struct *si, +static unsigned char swap_slot_put_locked(struct swap_info_struct *si, struct swap_cluster_info *ci, - swp_entry_t entry, + swp_slot_t slot, unsigned char usage) { - unsigned long offset =3D swp_offset(entry); + unsigned long offset =3D swp_slot_offset(slot); unsigned char count; unsigned char has_cache; =20 @@ -1542,7 +1559,7 @@ static unsigned char swap_entry_put_locked(struct swa= p_info_struct *si, if (usage) WRITE_ONCE(si->swap_map[offset], usage); else - swap_entries_free(si, ci, entry, 1); + swap_slots_free(si, ci, slot, 1); =20 return usage; } @@ -1552,8 +1569,9 @@ static unsigned char swap_entry_put_locked(struct swa= p_info_struct *si, * prevent swapoff, such as the folio in swap cache is locked, RCU * reader side is locked, etc., the swap entry may become invalid * because of swapoff. Then, we need to enclose all swap related - * functions with get_swap_device() and put_swap_device(), unless the - * swap functions call get/put_swap_device() by themselves. + * functions with swap_slot_tryget_swap_info() and + * swap_slot_put_swap_info(), unless the swap functions call + * swap_slot_(tryget|put)_swap_info by themselves. * * RCU reader side lock (including any spinlock) is sufficient to * prevent swapoff, because synchronize_rcu() is called in swapoff() @@ -1562,11 +1580,11 @@ static unsigned char swap_entry_put_locked(struct s= wap_info_struct *si, * Check whether swap entry is valid in the swap device. If so, * return pointer to swap_info_struct, and keep the swap entry valid * via preventing the swap device from being swapoff, until - * put_swap_device() is called. Otherwise return NULL. + * swap_slot_put_swap_info() is called. Otherwise return NULL. * * Notice that swapoff or swapoff+swapon can still happen before the - * percpu_ref_tryget_live() in get_swap_device() or after the - * percpu_ref_put() in put_swap_device() if there isn't any other way + * percpu_ref_tryget_live() in swap_slot_tryget_swap_info() or after the + * percpu_ref_put() in swap_slot_put_swap_info() if there isn't any other = way * to prevent swapoff. The caller must be prepared for that. For * example, the following situation is possible. * @@ -1586,53 +1604,53 @@ static unsigned char swap_entry_put_locked(struct s= wap_info_struct *si, * changed with the page table locked to check whether the swap device * has been swapoff or swapoff+swapon. */ -struct swap_info_struct *get_swap_device(swp_entry_t entry) +struct swap_info_struct *swap_slot_tryget_swap_info(swp_slot_t slot) { struct swap_info_struct *si; unsigned long offset; =20 - if (!entry.val) + if (!slot.val) goto out; - si =3D swap_entry_to_info(entry); + si =3D swap_slot_to_info(slot); if (!si) goto bad_nofile; if (!get_swap_device_info(si)) goto out; - offset =3D swp_offset(entry); + offset =3D swp_slot_offset(slot); if (offset >=3D si->max) goto put_out; =20 return si; bad_nofile: - pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val); + pr_err("%s: %s%08lx\n", __func__, Bad_file, slot.val); out: return NULL; put_out: - pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val); + pr_err("%s: %s%08lx\n", __func__, Bad_offset, slot.val); percpu_ref_put(&si->users); return NULL; } =20 -static void swap_entries_put_cache(struct swap_info_struct *si, - swp_entry_t entry, int nr) +static void swap_slots_put_cache(struct swap_info_struct *si, + swp_slot_t slot, int nr) { - unsigned long offset =3D swp_offset(entry); + unsigned long offset =3D swp_slot_offset(slot); struct swap_cluster_info *ci; =20 ci =3D swap_cluster_lock(si, offset); if (swap_only_has_cache(si, offset, nr)) { - swap_entries_free(si, ci, entry, nr); + swap_slots_free(si, ci, slot, nr); } else { - for (int i =3D 0; i < nr; i++, entry.val++) - swap_entry_put_locked(si, ci, entry, SWAP_HAS_CACHE); + for (int i =3D 0; i < nr; i++, slot.val++) + swap_slot_put_locked(si, ci, slot, SWAP_HAS_CACHE); } swap_cluster_unlock(ci); } =20 -static bool swap_entries_put_map(struct swap_info_struct *si, - swp_entry_t entry, int nr) +static bool swap_slots_put_map(struct swap_info_struct *si, + swp_slot_t slot, int nr) { - unsigned long offset =3D swp_offset(entry); + unsigned long offset =3D swp_slot_offset(slot); struct swap_cluster_info *ci; bool has_cache =3D false; unsigned char count; @@ -1649,7 +1667,7 @@ static bool swap_entries_put_map(struct swap_info_str= uct *si, goto locked_fallback; } if (!has_cache) - swap_entries_free(si, ci, entry, nr); + swap_slots_free(si, ci, slot, nr); else for (i =3D 0; i < nr; i++) WRITE_ONCE(si->swap_map[offset + i], SWAP_HAS_CACHE); @@ -1660,8 +1678,8 @@ static bool swap_entries_put_map(struct swap_info_str= uct *si, fallback: ci =3D swap_cluster_lock(si, offset); locked_fallback: - for (i =3D 0; i < nr; i++, entry.val++) { - count =3D swap_entry_put_locked(si, ci, entry, 1); + for (i =3D 0; i < nr; i++, slot.val++) { + count =3D swap_slot_put_locked(si, ci, slot, 1); if (count =3D=3D SWAP_HAS_CACHE) has_cache =3D true; } @@ -1674,20 +1692,20 @@ static bool swap_entries_put_map(struct swap_info_s= truct *si, * cross multi clusters, so ensure the range is within a single cluster * when freeing entries with functions without "_nr" suffix. */ -static bool swap_entries_put_map_nr(struct swap_info_struct *si, - swp_entry_t entry, int nr) +static bool swap_slots_put_map_nr(struct swap_info_struct *si, + swp_slot_t slot, int nr) { int cluster_nr, cluster_rest; - unsigned long offset =3D swp_offset(entry); + unsigned long offset =3D swp_slot_offset(slot); bool has_cache =3D false; =20 cluster_rest =3D SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER; while (nr) { cluster_nr =3D min(nr, cluster_rest); - has_cache |=3D swap_entries_put_map(si, entry, cluster_nr); + has_cache |=3D swap_slots_put_map(si, slot, cluster_nr); cluster_rest =3D SWAPFILE_CLUSTER; nr -=3D cluster_nr; - entry.val +=3D cluster_nr; + slot.val +=3D cluster_nr; } =20 return has_cache; @@ -1707,13 +1725,14 @@ static inline bool __maybe_unused swap_is_last_ref(= unsigned char count) * Drop the last ref of swap entries, caller have to ensure all entries * belong to the same cgroup and cluster. */ -static void swap_entries_free(struct swap_info_struct *si, +static void swap_slots_free(struct swap_info_struct *si, struct swap_cluster_info *ci, - swp_entry_t entry, unsigned int nr_pages) + swp_slot_t slot, unsigned int nr_pages) { - unsigned long offset =3D swp_offset(entry); + unsigned long offset =3D swp_slot_offset(slot); unsigned char *map =3D si->swap_map + offset; unsigned char *map_end =3D map + nr_pages; + swp_entry_t entry =3D swp_slot_to_swp_entry(slot); =20 /* It should never free entries across different clusters */ VM_BUG_ON(ci !=3D __swap_offset_to_cluster(si, offset + nr_pages - 1)); @@ -1739,43 +1758,54 @@ static void swap_entries_free(struct swap_info_stru= ct *si, * Caller has made sure that the swap device corresponding to entry * is still around or has not been recycled. */ -void swap_free_nr(swp_entry_t entry, int nr_pages) +void swap_slot_free_nr(swp_slot_t slot, int nr_pages) { int nr; struct swap_info_struct *sis; - unsigned long offset =3D swp_offset(entry); + unsigned long offset =3D swp_slot_offset(slot); =20 - sis =3D _swap_info_get(entry); + sis =3D _swap_info_get(slot); if (!sis) return; =20 while (nr_pages) { nr =3D min_t(int, nr_pages, SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER= ); - swap_entries_put_map(sis, swp_entry(sis->type, offset), nr); + swap_slots_put_map(sis, swp_slot(sis->type, offset), nr); offset +=3D nr; nr_pages -=3D nr; } } =20 +/* + * Caller has made sure that the swap device corresponding to entry + * is still around or has not been recycled. + */ +void swap_free_nr(swp_entry_t entry, int nr_pages) +{ + swap_slot_free_nr(swp_entry_to_swp_slot(entry), nr_pages); +} + /* * Called after dropping swapcache to decrease refcnt to swap entries. */ void put_swap_folio(struct folio *folio, swp_entry_t entry) { + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); struct swap_info_struct *si; - int size =3D 1 << swap_entry_order(folio_order(folio)); + int size =3D 1 << swap_slot_order(folio_order(folio)); =20 - si =3D _swap_info_get(entry); + si =3D _swap_info_get(slot); if (!si) return; =20 - swap_entries_put_cache(si, entry, size); + swap_slots_put_cache(si, slot, size); } =20 int __swap_count(swp_entry_t entry) { - struct swap_info_struct *si =3D __swap_entry_to_info(entry); - pgoff_t offset =3D swp_offset(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + struct swap_info_struct *si =3D __swap_slot_to_info(slot); + pgoff_t offset =3D swp_slot_offset(slot); =20 return swap_count(si->swap_map[offset]); } @@ -1787,7 +1817,8 @@ int __swap_count(swp_entry_t entry) */ bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry) { - pgoff_t offset =3D swp_offset(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + pgoff_t offset =3D swp_slot_offset(slot); struct swap_cluster_info *ci; int count; =20 @@ -1803,6 +1834,7 @@ bool swap_entry_swapped(struct swap_info_struct *si, = swp_entry_t entry) */ int swp_swapcount(swp_entry_t entry) { + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); int count, tmp_count, n; struct swap_info_struct *si; struct swap_cluster_info *ci; @@ -1810,11 +1842,11 @@ int swp_swapcount(swp_entry_t entry) pgoff_t offset; unsigned char *map; =20 - si =3D _swap_info_get(entry); + si =3D _swap_info_get(slot); if (!si) return 0; =20 - offset =3D swp_offset(entry); + offset =3D swp_slot_offset(slot); =20 ci =3D swap_cluster_lock(si, offset); =20 @@ -1846,10 +1878,11 @@ int swp_swapcount(swp_entry_t entry) static bool swap_page_trans_huge_swapped(struct swap_info_struct *si, swp_entry_t entry, int order) { + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); struct swap_cluster_info *ci; unsigned char *map =3D si->swap_map; unsigned int nr_pages =3D 1 << order; - unsigned long roffset =3D swp_offset(entry); + unsigned long roffset =3D swp_slot_offset(slot); unsigned long offset =3D round_down(roffset, nr_pages); int i; bool ret =3D false; @@ -1874,7 +1907,8 @@ static bool swap_page_trans_huge_swapped(struct swap_= info_struct *si, static bool folio_swapped(struct folio *folio) { swp_entry_t entry =3D folio->swap; - struct swap_info_struct *si =3D _swap_info_get(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + struct swap_info_struct *si =3D _swap_info_get(slot); =20 if (!si) return false; @@ -1948,13 +1982,14 @@ bool folio_free_swap(struct folio *folio) */ void free_swap_and_cache_nr(swp_entry_t entry, int nr) { - const unsigned long start_offset =3D swp_offset(entry); + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + const unsigned long start_offset =3D swp_slot_offset(slot); const unsigned long end_offset =3D start_offset + nr; struct swap_info_struct *si; bool any_only_cache =3D false; unsigned long offset; =20 - si =3D get_swap_device(entry); + si =3D swap_slot_tryget_swap_info(slot); if (!si) return; =20 @@ -1964,7 +1999,7 @@ void free_swap_and_cache_nr(swp_entry_t entry, int nr) /* * First free all entries in the range. */ - any_only_cache =3D swap_entries_put_map_nr(si, entry, nr); + any_only_cache =3D swap_slots_put_map_nr(si, slot, nr); =20 /* * Short-circuit the below loop if none of the entries had their @@ -1998,16 +2033,16 @@ void free_swap_and_cache_nr(swp_entry_t entry, int = nr) } =20 out: - put_swap_device(si); + swap_slot_put_swap_info(si); } =20 #ifdef CONFIG_HIBERNATION =20 -swp_entry_t get_swap_page_of_type(int type) +swp_slot_t swap_slot_alloc_of_type(int type) { struct swap_info_struct *si =3D swap_type_to_info(type); unsigned long offset; - swp_entry_t entry =3D {0}; + swp_slot_t slot =3D {0}; =20 if (!si) goto fail; @@ -2020,15 +2055,15 @@ swp_entry_t get_swap_page_of_type(int type) * with swap table allocation. */ local_lock(&percpu_swap_cluster.lock); - offset =3D cluster_alloc_swap_entry(si, 0, 1); + offset =3D cluster_alloc_swap_slot(si, 0, 1); local_unlock(&percpu_swap_cluster.lock); if (offset) - entry =3D swp_entry(si->type, offset); + slot =3D swp_slot(si->type, offset); } - put_swap_device(si); + swap_slot_put_swap_info(si); } fail: - return entry; + return slot; } =20 /* @@ -2257,6 +2292,7 @@ static int unuse_pte_range(struct vm_area_struct *vma= , pmd_t *pmd, unsigned long offset; unsigned char swp_count; softleaf_t entry; + swp_slot_t slot; int ret; pte_t ptent; =20 @@ -2271,10 +2307,12 @@ static int unuse_pte_range(struct vm_area_struct *v= ma, pmd_t *pmd, =20 if (!softleaf_is_swap(entry)) continue; - if (swp_type(entry) !=3D type) + + slot =3D swp_entry_to_swp_slot(entry); + if (swp_slot_type(slot) !=3D type) continue; =20 - offset =3D swp_offset(entry); + offset =3D swp_slot_offset(slot); pte_unmap(pte); pte =3D NULL; =20 @@ -2459,6 +2497,7 @@ static int try_to_unuse(unsigned int type) struct swap_info_struct *si =3D swap_info[type]; struct folio *folio; swp_entry_t entry; + swp_slot_t slot; unsigned int i; =20 if (!swap_usage_in_pages(si)) @@ -2506,7 +2545,8 @@ static int try_to_unuse(unsigned int type) !signal_pending(current) && (i =3D find_next_to_unuse(si, i)) !=3D 0) { =20 - entry =3D swp_entry(type, i); + slot =3D swp_slot(type, i); + entry =3D swp_slot_to_swp_entry(slot); folio =3D swap_cache_get_folio(entry); if (!folio) continue; @@ -2890,7 +2930,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) } =20 /* - * Wait for swap operations protected by get/put_swap_device() + * Wait for swap operations protected by swap_slot_(tryget|put)_swap_info= () * to complete. Because of synchronize_rcu() here, all swap * operations protected by RCU reader side lock (including any * spinlock) will be waited too. This makes it easy to @@ -3331,7 +3371,7 @@ static struct swap_cluster_info *setup_clusters(struc= t swap_info_struct *si, if (!si->global_cluster) goto err; for (i =3D 0; i < SWAP_NR_ORDERS; i++) - si->global_cluster->next[i] =3D SWAP_ENTRY_INVALID; + si->global_cluster->next[i] =3D SWAP_SLOT_INVALID; spin_lock_init(&si->global_cluster_lock); } =20 @@ -3669,6 +3709,7 @@ void si_swapinfo(struct sysinfo *val) */ static int __swap_duplicate(swp_entry_t entry, unsigned char usage, int nr) { + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); struct swap_info_struct *si; struct swap_cluster_info *ci; unsigned long offset; @@ -3676,13 +3717,13 @@ static int __swap_duplicate(swp_entry_t entry, unsi= gned char usage, int nr) unsigned char has_cache; int err, i; =20 - si =3D swap_entry_to_info(entry); + si =3D swap_slot_to_info(slot); if (WARN_ON_ONCE(!si)) { pr_err("%s%08lx\n", Bad_file, entry.val); return -EINVAL; } =20 - offset =3D swp_offset(entry); + offset =3D swp_slot_offset(slot); VM_WARN_ON(nr > SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER); VM_WARN_ON(usage =3D=3D 1 && nr > 1); ci =3D swap_cluster_lock(si, offset); @@ -3788,7 +3829,7 @@ int swapcache_prepare(swp_entry_t entry, int nr) */ void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int n= r) { - swap_entries_put_cache(si, entry, nr); + swap_slots_put_cache(si, swp_entry_to_swp_slot(entry), nr); } =20 /* @@ -3815,6 +3856,7 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) struct page *list_page; pgoff_t offset; unsigned char count; + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); int ret =3D 0; =20 /* @@ -3823,7 +3865,7 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) */ page =3D alloc_page(gfp_mask | __GFP_HIGHMEM); =20 - si =3D get_swap_device(entry); + si =3D swap_slot_tryget_swap_info(slot); if (!si) { /* * An acceptable race has occurred since the failing @@ -3832,7 +3874,7 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) goto outer; } =20 - offset =3D swp_offset(entry); + offset =3D swp_slot_offset(slot); =20 ci =3D swap_cluster_lock(si, offset); =20 @@ -3895,7 +3937,7 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) spin_unlock(&si->cont_lock); out: swap_cluster_unlock(ci); - put_swap_device(si); + swap_slot_put_swap_info(si); outer: if (page) __free_page(page); --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oi1-f177.google.com (mail-oi1-f177.google.com [209.85.167.177]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3A3CA35E541 for ; Sun, 8 Feb 2026 21:58:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587938; cv=none; b=RKBq/78dEsg5trvCA9WcHNOPJVmD5/MrS0Twz4+a6K3t9bME5+kikJwIcOvbeIGny8KfrgiOFXScgW4eN/UAEVFKJnaqMSc62XOol1RK/H4j8rv+x+COX+HJZuJg4hpOKZnPuNcvmebnbDAcp7UqyHkRwVY83CPnabVEHqA15MY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587938; c=relaxed/simple; bh=hMYJkWqt5SRZ9hrREEyYUKQBPS2WDzY73VTSLMkQ4D4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=jSpZWKv2XYPdONr7f5xpdj7NJyaaV2N3IdG2OTwW0XtoxBYZ8si6raOFVKtsaL90WsQXVn3xYLMtTLf5DKWpaXn+55a6Io+hsyekgM/lw4JPxTS8fgZTS3qbivlM2kgPBK17VVgonq8TZ4XrPtuUPYqXIfc0QcwN74C2Od4vDkA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=lZdQK67i; arc=none smtp.client-ip=209.85.167.177 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.b="lZdQK67i" Received: by mail-oi1-f177.google.com with SMTP id 5614622812f47-45c7c841904so1649547b6e.3 for ; Sun, 08 Feb 2026 13:58:58 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587937; x=1771192737; 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; bh=AAYGpIpTp87S2/ee6Fydv9Vv1Hcay3Vy8wBGMvAXEzA=; b=lZdQK67iWJAHL7JGqSbW628gYhVUpecwY2VhyZOxTrrWA9miY6RTBYUIRetakIP8cx KPc0sEsxpSIjAx5VMYh1cpCcPYdjTV7BcInUkRo/8X8zaOaH+3EVVtmQqVAZUr7AnRGC C0m/YiqEShQAShnDiCv3W/YCUcR3MJLeZu3Bkv7IQSfdZj6RxHigwizARFnWiK6KtiZc BBWNVzaEj5W9w3eYCb70oG5vOMU//9dKtpZSy4clzWBxAMxdPwl6tuyx+lxOAT7QxMqH qu7mJi1J+aNSa6YAqaC2XrQqdUuuTO03xubyhBsYxi8o/v5qfHFIVl6x2Z2tpT2SoLMG i6iQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587937; x=1771192737; 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; bh=AAYGpIpTp87S2/ee6Fydv9Vv1Hcay3Vy8wBGMvAXEzA=; b=SiV60D0bfNW9FwJCxPCM/lw3IM9H/vjTQPsel85cIl5lyH/92qO9e02mkGKAVtVRNn mBqohyt0Zvq7xIBYySH7sZ2iFwSDm191Kht9Y3SHGQOdbClUpqVoBaTdOvbpqgPVnr9Z 1y/5hs86W4zCh6mE3fSjyb/UDUeYybqpahq85EjcDgMWsHhHu9EY7MAXDUSCxYyGh3uH tD/j0n2ftrLvq+IOSehBbDZlmKAVkiFG/u2/+EB99L3JR18PHYHZEZacj/+VZIoKqfM9 P7EO26XkXoLzcD51lFHbkFGc+GiLQPg0E/NCf1IOg8JlcU0DZ2bJKD49EOiZe7AWAzNd cqxA== X-Forwarded-Encrypted: i=1; AJvYcCUUZqyOSaBtZe7PIA0jF3sWNo6Y/7ZxvOlUnv8vQVdTib/kwYGc7P1DckryhOIpnKsS9i+/B3wGscBzAVY=@vger.kernel.org X-Gm-Message-State: AOJu0YxUQf+EgfYNVFPTOimTZMz53vmFvGXtmpVUtzyX3qYk8az0wYp6 1gK/JqZC4y9IeedArmwI9/BCWUy0FIaVNnFJ1EaGfYpx+A/Itkaj3H3h X-Gm-Gg: AZuq6aKDDqPAlyc4xewZ3vFmzyrgE9V8NH+i6n6L3PdfYF/RmMN/ANrSoA/82yDqBig CweIF2qc5yx97xvlss0qWw8wZLmXKwYvUfyhIgjLRWntIu861YLRB2KvI7Rw37zZX5CVNsY2VgB 9xwDoa+fASb2JwHO4sRSk/EieaJhgu2Gm8pdm23jiS7xUnTN8+LyfPv8XJ1wuDvJqzCDZtJzWX5 Mg8cCALERJ1uoD4WwB0TMToQxwIQOAi2+BabbJYBdF26bsILXOYQ1HFGN0oBoOiL+NXld/qBDax TEmv/yTwbSTI2FqiRrVN0qyoKnmDMPPwi1xr8hEl87V2hrZdJZHEVynV0dHL5vFPKt1/cJHqOXu Hcksd/WKidxZOG0NGRIrG6B+lDnDJjOuPjUZ7XK7e9ksyRAHdABYw1xrQS9OBe/3+AVK2M8VkYq dx/Y8Hbk5XLr49VzNG9H/MH4c6WYe+LOce X-Received: by 2002:a05:6808:6a83:b0:45e:84ec:f163 with SMTP id 5614622812f47-462fcbf61f5mr5120530b6e.64.1770587937297; Sun, 08 Feb 2026 13:58:57 -0800 (PST) Received: from localhost ([2a03:2880:10ff:1::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d464785674sm6238015a34.19.2026.02.08.13.58.56 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:56 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 07/20] mm: create scaffolds for the new virtual swap implementation Date: Sun, 8 Feb 2026 13:58:20 -0800 Message-ID: <20260208215839.87595-8-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" In prepration for the implementation of swap virtualization, add new scaffolds for the new code: a new mm/vswap.c source file, which currently only holds the logic to set up the (for now, empty) vswap debugfs directory. Hook this up in the swap setup step in mm/swap_state.c, and set up vswap compilation in the Makefile. Other than the debugfs directory, no behavioral change intended. Finally, make Johannes a swap reviewer, given that he has contributed majorly to the developments of virtual swap. Signed-off-by: Nhat Pham --- MAINTAINERS | 2 ++ include/linux/swap.h | 2 ++ mm/Makefile | 2 +- mm/swap_state.c | 6 ++++++ mm/vswap.c | 35 +++++++++++++++++++++++++++++++++++ 5 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 mm/vswap.c diff --git a/MAINTAINERS b/MAINTAINERS index e087673237636..b21038b160a07 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -16728,6 +16728,7 @@ R: Kemeng Shi R: Nhat Pham R: Baoquan He R: Barry Song +R: Johannes Weiner L: linux-mm@kvack.org S: Maintained F: Documentation/mm/swap-table.rst @@ -16740,6 +16741,7 @@ F: mm/swap.h F: mm/swap_table.h F: mm/swap_state.c F: mm/swapfile.c +F: mm/vswap.c =20 MEMORY MANAGEMENT - THP (TRANSPARENT HUGE PAGE) M: Andrew Morton diff --git a/include/linux/swap.h b/include/linux/swap.h index 918b47da55f44..1ff463fb3a966 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -669,6 +669,8 @@ static inline bool mem_cgroup_swap_full(struct folio *f= olio) } #endif =20 +int vswap_init(void); + /** * swp_entry_to_swp_slot - look up the physical swap slot corresponding to= a * virtual swap slot. diff --git a/mm/Makefile b/mm/Makefile index 2d0570a16e5be..67fa4586e7e18 100644 --- a/mm/Makefile +++ b/mm/Makefile @@ -75,7 +75,7 @@ ifdef CONFIG_MMU obj-$(CONFIG_ADVISE_SYSCALLS) +=3D madvise.o endif =20 -obj-$(CONFIG_SWAP) +=3D page_io.o swap_state.o swapfile.o +obj-$(CONFIG_SWAP) +=3D page_io.o swap_state.o swapfile.o vswap.o obj-$(CONFIG_ZSWAP) +=3D zswap.o obj-$(CONFIG_HAS_DMA) +=3D dmapool.o obj-$(CONFIG_HUGETLBFS) +=3D hugetlb.o hugetlb_sysfs.o hugetlb_sysctl.o diff --git a/mm/swap_state.c b/mm/swap_state.c index e2e9f55bea3bb..29ec666be4204 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -882,6 +882,12 @@ static int __init swap_init(void) int err; struct kobject *swap_kobj; =20 + err =3D vswap_init(); + if (err) { + pr_err("failed to initialize virtual swap space\n"); + return err; + } + swap_kobj =3D kobject_create_and_add("swap", mm_kobj); if (!swap_kobj) { pr_err("failed to create swap kobject\n"); diff --git a/mm/vswap.c b/mm/vswap.c new file mode 100644 index 0000000000000..e68234f053fc9 --- /dev/null +++ b/mm/vswap.c @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Virtual swap space + * + * Copyright (C) 2024 Meta Platforms, Inc., Nhat Pham + */ +#include + +#ifdef CONFIG_DEBUG_FS +#include + +static struct dentry *vswap_debugfs_root; + +static int vswap_debug_fs_init(void) +{ + if (!debugfs_initialized()) + return -ENODEV; + + vswap_debugfs_root =3D debugfs_create_dir("vswap", NULL); + return 0; +} +#else +static int vswap_debug_fs_init(void) +{ + return 0; +} +#endif + +int vswap_init(void) +{ + if (vswap_debug_fs_init()) + pr_warn("Failed to initialize vswap debugfs\n"); + + return 0; +} --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oi1-f179.google.com (mail-oi1-f179.google.com [209.85.167.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8B7CA34EF02 for ; Sun, 8 Feb 2026 21:58:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587941; cv=none; b=l6gp//HOvCe/oKrPYvEX7gVyTgaJCCS/5irgT7FYJCc4j0liz/T0u1F4WgBX8WFysZtIsAILXag8jc06PgLwsJpJGsD9DTex8UDzHccbSTJzBzUGn17VUusrHjkShnrX+NgW0rOW+3rUKVol3ciO28ODMLiaFBD5bfzFmCiYYFg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587941; c=relaxed/simple; bh=K9PmpF4kbVu6ILPHk8wqR1G3rBTWjZhGbr2v5i6EdoM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=h6/7LIpifg5hGSt8psnVwJvVixugO2x73eG73f1WsVOG62IihSoVuBd3kbLkY8QtVvxhK+DdmTKULXbdXxSkkfnpIHJX8lGr4zGIDGIuvtdqap/ttJouEvNazE+NvThnyALRCZKr//jNAnE4VTSj96eoyRigqYaoMtW5eHaScIk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=F1oaq3Bn; arc=none smtp.client-ip=209.85.167.179 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.b="F1oaq3Bn" Received: by mail-oi1-f179.google.com with SMTP id 5614622812f47-45c70afbeebso2489725b6e.0 for ; Sun, 08 Feb 2026 13:58:59 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587938; x=1771192738; 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; bh=Br8/Kp0dBiDnoT9vYl1sItOdYWaxT3y8ap5a4tIpuAg=; b=F1oaq3Bnt8jDbn0tVnE2PGBKUeKJKvXvkfCJoBFZ+5VIlMddyCHsVpw80dZwRttfDQ dZHYsFLQvKpLimoM7PtR3WCTYfVLKdqpQXZxFVbgxKvNV0rx5zOaFWvv7nKKNHHCJO0u bvKJQPup5+fEa/jKYohF3Mxb32Porh4KSuAzlXd24gkVAcn7S6zX33Syx14kpw9MFjTG Ks3mooiqSvQ9y6keqSBsH2r+tIS3+iDhOUZo5HwNNb84mQmjPJnOlfoy8GK04Zo69ecT ODL6QTgWNtICIh0DhUS6ePzW9hU6TYhMMl1ILdcN8RUqBJ5lys0IrV+qYa38LjXQ8bMQ jlgQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587938; x=1771192738; 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; bh=Br8/Kp0dBiDnoT9vYl1sItOdYWaxT3y8ap5a4tIpuAg=; b=NYLCqwKffOvnDgYtXrvDUFZyhx8EgO9D00H4r7VP3vwdmq7I0Yjfd/TLB3u9cf0LhR ZpeY34EjxQh8fgioP/eshiVPN/kdgatdwVDBSH09Dvw0mLLEX38zdncx3MGecmZvCnqg EPx+cVFdu355k32PyZ6Qp4G7VJOAjWs6GPQxKgJD5oTnkacj7pv61Yg2clCS6CoKI+Fo G5OSbY0k5F+nMT2o/HSTlnPir5+CU8M8eZnTuPx/3umJzRTCCutwxNujoR4OSntDLgN0 KWAvlg4LquPAwEBiysOL03uWPuwtDf3a9/Cb0OR0jb/AV48guGhxwgwlC/x8qrq1CQSG hG6g== X-Forwarded-Encrypted: i=1; AJvYcCWxmJCXsrPei7Iimd3T2OuROUQxFblvqxGyAc7eLT+vLDq7NsnjaOewLSVlYxGMQljQ7b1z3rXHlPjWhxk=@vger.kernel.org X-Gm-Message-State: AOJu0YyvmyS6UwRO26g831UmHbxH8H4v/mLXSOMWG9w3rvYW4EiDiBC9 TrokPq7Hk+qKE0sbTR+ZTDp1G88aLl3Tx1Z90WXYtV1Yj9KtC3tazj/m X-Gm-Gg: AZuq6aJLRwnrFjphieTMWZqqK0FhOQEHoeXqtKbuIZzzj1dtWPWRd0tC52K/9svoA0R zcsEoO9HyRm5jNGx46YXlVeD8KENIkqFCd0H4NGFveRWv4Qoes8cGhOs4FvDg62Oc07PupMaa6k vPLDrpnukTM9d0g4XxGNTF3ZsrbrfvDeXMdTSmsuQlYmjqfGRHXPxyTC/BJeIuskIfuqWjQhqwU FVd3uQLMB81c8car1AY8WI6V1XS61G4pQ67ktlLjn7eYMu56B5DYg2zKC9eWCAVr+u4ckCkz3PR GBTAOulCC892RjE+QmS+/rMXcpvR90m9sqXQzSw+XGYinv7jBTFybHv3x/ao8By/PwIySnXZRwh MrYMnS2ep6C47h5MFGguuwJKgD6dsVAks4rn9ISYXFNb1S4H6JCQUS/Ic7Ku8PrisvlJ9X6TUWx 467pi3uPe0JZSewCddCMvQjVaN5XVjhVoi X-Received: by 2002:a05:6808:6b8e:b0:450:b215:8f22 with SMTP id 5614622812f47-462fcb81536mr4957989b6e.55.1770587938562; Sun, 08 Feb 2026 13:58:58 -0800 (PST) Received: from localhost ([2a03:2880:10ff:9::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d4646fb89fsm6346818a34.1.2026.02.08.13.58.57 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:58:58 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 08/20] zswap: prepare zswap for swap virtualization Date: Sun, 8 Feb 2026 13:58:21 -0800 Message-ID: <20260208215839.87595-9-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" The zswap tree code, specifically the range partition logic, can no longer easily be reused for the new virtual swap space design. Use a simple unified zswap tree in the new implementation for now. Signed-off-by: Nhat Pham --- include/linux/zswap.h | 7 ----- mm/swapfile.c | 9 +----- mm/zswap.c | 69 +++++++------------------------------------ 3 files changed, 11 insertions(+), 74 deletions(-) diff --git a/include/linux/zswap.h b/include/linux/zswap.h index 30c193a1207e1..1a04caf283dc8 100644 --- a/include/linux/zswap.h +++ b/include/linux/zswap.h @@ -28,8 +28,6 @@ unsigned long zswap_total_pages(void); bool zswap_store(struct folio *folio); int zswap_load(struct folio *folio); void zswap_invalidate(swp_entry_t swp); -int zswap_swapon(int type, unsigned long nr_pages); -void zswap_swapoff(int type); void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg); void zswap_lruvec_state_init(struct lruvec *lruvec); void zswap_folio_swapin(struct folio *folio); @@ -50,11 +48,6 @@ static inline int zswap_load(struct folio *folio) } =20 static inline void zswap_invalidate(swp_entry_t swp) {} -static inline int zswap_swapon(int type, unsigned long nr_pages) -{ - return 0; -} -static inline void zswap_swapoff(int type) {} static inline void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg) {} static inline void zswap_lruvec_state_init(struct lruvec *lruvec) {} static inline void zswap_folio_swapin(struct folio *folio) {} diff --git a/mm/swapfile.c b/mm/swapfile.c index 4b4126d4e2769..3f70df488c1da 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -2970,7 +2970,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) spin_unlock(&p->lock); spin_unlock(&swap_lock); arch_swap_invalidate_area(p->type); - zswap_swapoff(p->type); mutex_unlock(&swapon_mutex); kfree(p->global_cluster); p->global_cluster =3D NULL; @@ -3613,10 +3612,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, special= file, int, swap_flags) } } =20 - error =3D zswap_swapon(si->type, maxpages); - if (error) - goto bad_swap_unlock_inode; - /* * Flush any pending IO and dirty mappings before we start using this * swap device. @@ -3625,7 +3620,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) error =3D inode_drain_writes(inode); if (error) { inode->i_flags &=3D ~S_SWAPFILE; - goto free_swap_zswap; + goto bad_swap_unlock_inode; } =20 mutex_lock(&swapon_mutex); @@ -3648,8 +3643,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) =20 error =3D 0; goto out; -free_swap_zswap: - zswap_swapoff(si->type); bad_swap_unlock_inode: inode_unlock(inode); bad_swap: diff --git a/mm/zswap.c b/mm/zswap.c index a5a3f068bd1a6..f7313261673ff 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -197,8 +197,6 @@ struct zswap_entry { struct list_head lru; }; =20 -static struct xarray *zswap_trees[MAX_SWAPFILES]; -static unsigned int nr_zswap_trees[MAX_SWAPFILES]; =20 /* RCU-protected iteration */ static LIST_HEAD(zswap_pools); @@ -225,45 +223,35 @@ static bool zswap_has_pool; * helpers and fwd declarations **********************************/ =20 -/* One swap address space for each 64M swap space */ -#define ZSWAP_ADDRESS_SPACE_SHIFT 14 -#define ZSWAP_ADDRESS_SPACE_PAGES (1 << ZSWAP_ADDRESS_SPACE_SHIFT) -static inline struct xarray *swap_zswap_tree(swp_entry_t swp) -{ - return &zswap_trees[swp_type(swp)][swp_offset(swp) - >> ZSWAP_ADDRESS_SPACE_SHIFT]; -} +static DEFINE_XARRAY(zswap_tree); + +#define zswap_tree_index(entry) (entry.val) =20 static inline void *zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry) { - struct xarray *tree =3D swap_zswap_tree(swpentry); - pgoff_t offset =3D swp_offset(swpentry); + pgoff_t offset =3D zswap_tree_index(swpentry); =20 - return xa_store(tree, offset, entry, GFP_KERNEL); + return xa_store(&zswap_tree, offset, entry, GFP_KERNEL); } =20 static inline void *zswap_entry_load(swp_entry_t swpentry) { - struct xarray *tree =3D swap_zswap_tree(swpentry); - pgoff_t offset =3D swp_offset(swpentry); + pgoff_t offset =3D zswap_tree_index(swpentry); =20 - return xa_load(tree, offset); + return xa_load(&zswap_tree, offset); } =20 static inline void *zswap_entry_erase(swp_entry_t swpentry) { - struct xarray *tree =3D swap_zswap_tree(swpentry); - pgoff_t offset =3D swp_offset(swpentry); + pgoff_t offset =3D zswap_tree_index(swpentry); =20 - return xa_erase(tree, offset); + return xa_erase(&zswap_tree, offset); } =20 static inline bool zswap_empty(swp_entry_t swpentry) { - struct xarray *tree =3D swap_zswap_tree(swpentry); - - return xa_empty(tree); + return xa_empty(&zswap_tree); } =20 #define zswap_pool_debug(msg, p) \ @@ -1691,43 +1679,6 @@ void zswap_invalidate(swp_entry_t swp) zswap_entry_free(entry); } =20 -int zswap_swapon(int type, unsigned long nr_pages) -{ - struct xarray *trees, *tree; - unsigned int nr, i; - - nr =3D DIV_ROUND_UP(nr_pages, ZSWAP_ADDRESS_SPACE_PAGES); - trees =3D kvcalloc(nr, sizeof(*tree), GFP_KERNEL); - if (!trees) { - pr_err("alloc failed, zswap disabled for swap type %d\n", type); - return -ENOMEM; - } - - for (i =3D 0; i < nr; i++) - xa_init(trees + i); - - nr_zswap_trees[type] =3D nr; - zswap_trees[type] =3D trees; - return 0; -} - -void zswap_swapoff(int type) -{ - struct xarray *trees =3D zswap_trees[type]; - unsigned int i; - - if (!trees) - return; - - /* try_to_unuse() invalidated all the entries already */ - for (i =3D 0; i < nr_zswap_trees[type]; i++) - WARN_ON_ONCE(!xa_empty(trees + i)); - - kvfree(trees); - nr_zswap_trees[type] =3D 0; - zswap_trees[type] =3D NULL; -} - /********************************* * debugfs functions **********************************/ --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oi1-f172.google.com (mail-oi1-f172.google.com [209.85.167.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 83C4834FF67 for ; Sun, 8 Feb 2026 21:59:02 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587942; cv=none; b=A/HmAdIS/MOHjfTr+22hF7EFsG2nbH/YKrjIAYsBE0S5tlpiIJWvyukQdbZwqphVl+nIpxu3Aa56h6QF3xASD/CxjSb39gQUjGFMRbURnbDOLaz++Mm9rpHwZUB/TbpH9UQgMcj/iTHi/W2/emETHi+Xq5CYV28MymzFfMR6Nw8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587942; c=relaxed/simple; bh=4H77+53imRkursL0fnuILPf5H3cLtNhnI8zEfj7hqZs=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=ZM7jWP4/Bs588iGgOO60IVhF3SlwQx3d6Vy8iDuprPcESqsHGtkM8NAo9dGNBLOdgAIQpBK/M/U56nruYf8YM0W/TDyJKzpl+PCMkrVIqzQlCEtGIGOc1weFzSj91GJCjphWRjXqIvGO9awqWWN8HhICmCPWOCzJB7kKBOmhS2I= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=AAs5ClWw; arc=none smtp.client-ip=209.85.167.172 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.b="AAs5ClWw" Received: by mail-oi1-f172.google.com with SMTP id 5614622812f47-45f0dbe7dafso786327b6e.3 for ; Sun, 08 Feb 2026 13:59:02 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587941; x=1771192741; 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; bh=Vnr5PMaeHclHPTB5XskcisezMSN6YTcA4viXAcebDs8=; b=AAs5ClWwxBH8MsuOlll8+3bBDPb3CG5JFx69tGzub+4cDP5OotnO4NBq7cffjdBb8J sZHr4eYzC/h65TViDmGJiN+aY7N2KhCAC2z8/7wiH3stVxmb3dOfFCY8KbY+uMdVSjpH R+FBANVV+81fTWxZRecXsIdEH+/gC8nCo8zglt3g/FMjZqzbmbDiVP1EEuVjZEKuFzsF fQ8pKGuUrtadHnUL8/sBk8M284Lv/Y1BQsYs/Wrs5opwHPqYNM/xZUv3UTguBJHGGGKA OF/NNPnQTqBgzxMmaCugBHTx8cmwkM3xkTGp3wQd3CBdZCovDL/gsAf8zHzeQfRxlM+n QGvQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587941; x=1771192741; 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; bh=Vnr5PMaeHclHPTB5XskcisezMSN6YTcA4viXAcebDs8=; b=v4aRZAiIwR3rWeUK8dD6sBauMssw8zE1k5YgZMITBAT0iy9NVP2MjMHbvcPo2c7Td5 nCGGIBAhCeSozKS4JSl5pHMmqz8KhP85rIMInChdCgXP7WlCg1i/lVGvCjzG21R5Xp/x mmyr609JCxQ+NEPSmmOdVQicUdxU6EsrfHVbkm+FpCxom8Hlv/VYxDI2BVb/padys724 b4tRS0s3OLvR/EeNEdLnhpZCDGjmC/n/+Fnnv/z9AZdsYj76Y5jsbI+YPaq5KVFpBSWC ze1WT3NrnhA7b6BdeebAJOZsT9oE3V0xpHtMK/xKmyooGguvMfiAcWi5QezH2PF3Yu4f ZS8A== X-Forwarded-Encrypted: i=1; AJvYcCVQPw7GwlKA2lNScr87ILzI/9uOe1XwByHpVwEJniTtz6WYUt7nNUqGpkJmnE1V2kONXqd8YojUAT24d2s=@vger.kernel.org X-Gm-Message-State: AOJu0Yx+ZWQar98AJSeBDwnMIqKkM2pQWy2U/w+hkuFGlNvVIXHN8ocv PFWUPS7JjOMO0T/mWOvmUz/jboOzAW3uyCtbUn8mDbJgGdtjU8c3g2OI X-Gm-Gg: AZuq6aIIsqH6K5oqASSshEuLBwHB6j/KLvJYv2hqqygoTpRWm/4vd4yWEQajqtCpXgZ 62+h5w89h6l8BoeDc9/CLkSsVziGKjGyvaY45pvZFOSm68ZxskCQUsYFw4HqNNzeL5Udp4eR2QH aii8UoHv6q7x6E1/b5fZOcyrHkiO3usT++yBDTaMuQBgTzIDPWblY7o0ccPD4F6DZXP32JMBGB4 NOl8AgCXclf5XqpMKEsYos7sgnQS3OnIVsd9+aJ5LTh90mH8EN5Lu84YO8E/d1ZfzM41DTtyCRJ Uemyh1vUCb58TjiWUlU9JzEWnVI+m755TewB/0wVSu4Bk31IgK3VR98xNZXcC4QdE9bB450NJPB AMbIyEVzkJzhqCSemsybt5myF3FpA2gyavq0bXIdeLMzLJaO1czAUIdLG4TAT5tEpEnZ3q5sVph Gp5NknNGnAcfcEvDl8C5gldT1MwF+hJw== X-Received: by 2002:a05:6808:3a13:b0:45e:ed0b:765e with SMTP id 5614622812f47-462fcb47130mr4332521b6e.51.1770587941368; Sun, 08 Feb 2026 13:59:01 -0800 (PST) Received: from localhost ([2a03:2880:10ff::]) by smtp.gmail.com with ESMTPSA id 5614622812f47-4631407de2dsm3559722b6e.16.2026.02.08.13.58.59 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:00 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 09/20] mm: swap: allocate a virtual swap slot for each swapped out page Date: Sun, 8 Feb 2026 13:58:22 -0800 Message-ID: <20260208215839.87595-10-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" For the new virtual swap space design, dynamically allocate a virtual slot (as well as an associated metadata structure) for each swapped out page, and associate it to the (physical) swap slot on the swapfile/swap partition. This virtual swap slot is now stored in page table entries and used to index into swap data structures (swap cache, zswap tree, swap cgroup array), in place of the old physical swap slot. For now, there is always a physical slot in the swapfile associated for each virtual swap slot (except those about to be freed). The virtual swap slot's lifetime is still tied to the lifetime of its physical swap slot. We do change the freeing ordering a bit - we clear the shadow, invalidate the zswap entry, and uncharge swap cgroup when we release the virtual swap slot, as we now use virtual swap slot to index into these swap data structures. We also repurpose the swap table infrastructure as a reverse map to look up the virtual swap slot from its associated physical swap slot on swapfile. This is used in cluster readahead, as well as several swapfile operations, such as the swap slot reclamation that happens when the swapfile is almost full. It will also be used in a future patch that simplifies swapoff. Signed-off-by: Nhat Pham --- include/linux/cpuhotplug.h | 1 + include/linux/swap.h | 49 +-- mm/internal.h | 28 +- mm/page_io.c | 6 +- mm/shmem.c | 9 +- mm/swap.h | 8 +- mm/swap_state.c | 5 +- mm/swapfile.c | 63 +--- mm/vswap.c | 658 +++++++++++++++++++++++++++++++++++++ 9 files changed, 710 insertions(+), 117 deletions(-) diff --git a/include/linux/cpuhotplug.h b/include/linux/cpuhotplug.h index 62cd7b35a29c9..85cb45022e796 100644 --- a/include/linux/cpuhotplug.h +++ b/include/linux/cpuhotplug.h @@ -86,6 +86,7 @@ enum cpuhp_state { CPUHP_FS_BUFF_DEAD, CPUHP_PRINTK_DEAD, CPUHP_MM_MEMCQ_DEAD, + CPUHP_MM_VSWAP_DEAD, CPUHP_PERCPU_CNT_DEAD, CPUHP_RADIX_DEAD, CPUHP_PAGE_ALLOC, diff --git a/include/linux/swap.h b/include/linux/swap.h index 1ff463fb3a966..0410a00fd353c 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -471,6 +471,7 @@ static inline long get_nr_swap_pages(void) } =20 void si_swapinfo(struct sysinfo *); +int swap_slot_alloc(swp_slot_t *slot, unsigned int order); swp_slot_t swap_slot_alloc_of_type(int); int add_swap_count_continuation(swp_entry_t, gfp_t); int swap_type_of(dev_t device, sector_t offset); @@ -670,48 +671,12 @@ static inline bool mem_cgroup_swap_full(struct folio = *folio) #endif =20 int vswap_init(void); - -/** - * swp_entry_to_swp_slot - look up the physical swap slot corresponding to= a - * virtual swap slot. - * @entry: the virtual swap slot. - * - * Return: the physical swap slot corresponding to the virtual swap slot. - */ -static inline swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry) -{ - return (swp_slot_t) { entry.val }; -} - -/** - * swp_slot_to_swp_entry - look up the virtual swap slot corresponding to a - * physical swap slot. - * @slot: the physical swap slot. - * - * Return: the virtual swap slot corresponding to the physical swap slot. - */ -static inline swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot) -{ - return (swp_entry_t) { slot.val }; -} - -static inline bool tryget_swap_entry(swp_entry_t entry, - struct swap_info_struct **sip) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *si =3D swap_slot_tryget_swap_info(slot); - - if (sip) - *sip =3D si; - - return si; -} - -static inline void put_swap_entry(swp_entry_t entry, - struct swap_info_struct *si) -{ - swap_slot_put_swap_info(si); -} +void vswap_exit(void); +void vswap_free(swp_entry_t entry, struct swap_cluster_info *ci); +swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry); +swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot); +bool tryget_swap_entry(swp_entry_t entry, struct swap_info_struct **si); +void put_swap_entry(swp_entry_t entry, struct swap_info_struct *si); =20 #endif /* __KERNEL__*/ #endif /* _LINUX_SWAP_H */ diff --git a/mm/internal.h b/mm/internal.h index e739e8cac5b55..7ced0def684ca 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -322,6 +322,25 @@ static inline unsigned int folio_pte_batch_flags(struc= t folio *folio, unsigned int folio_pte_batch(struct folio *folio, pte_t *ptep, pte_t pte, unsigned int max_nr); =20 +static inline swp_entry_t swap_nth(swp_entry_t entry, long n) +{ + return (swp_entry_t) { entry.val + n }; +} + +/* similar to swap_nth, but check the backing physical slots as well. */ +static inline swp_entry_t swap_move(swp_entry_t entry, long delta) +{ + swp_slot_t slot =3D swp_entry_to_swp_slot(entry), next_slot; + swp_entry_t next_entry =3D swap_nth(entry, delta); + + next_slot =3D swp_entry_to_swp_slot(next_entry); + if (swp_slot_type(slot) !=3D swp_slot_type(next_slot) || + swp_slot_offset(slot) + delta !=3D swp_slot_offset(next_slot)) + next_entry.val =3D 0; + + return next_entry; +} + /** * pte_move_swp_offset - Move the swap entry offset field of a swap pte * forward or backward by delta @@ -334,13 +353,8 @@ unsigned int folio_pte_batch(struct folio *folio, pte_= t *ptep, pte_t pte, */ static inline pte_t pte_move_swp_offset(pte_t pte, long delta) { - softleaf_t entry =3D softleaf_from_pte(pte), new_entry; - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - pte_t new; - - new_entry =3D swp_slot_to_swp_entry(swp_slot(swp_slot_type(slot), - swp_slot_offset(slot) + delta)); - new =3D swp_entry_to_pte(new_entry); + softleaf_t entry =3D softleaf_from_pte(pte); + pte_t new =3D swp_entry_to_pte(swap_move(entry, delta)); =20 if (pte_swp_soft_dirty(pte)) new =3D pte_swp_mksoft_dirty(new); diff --git a/mm/page_io.c b/mm/page_io.c index 0b02bcc85e2a8..5de3705572955 100644 --- a/mm/page_io.c +++ b/mm/page_io.c @@ -364,7 +364,7 @@ static void sio_write_complete(struct kiocb *iocb, long= ret) */ pr_err_ratelimited("Write error %ld on dio swapfile (%llu)\n", ret, - swap_slot_pos(swp_entry_to_swp_slot(page_swap_entry(page)))); + swap_slot_dev_pos(swp_entry_to_swp_slot(page_swap_entry(page)))); for (p =3D 0; p < sio->pages; p++) { page =3D sio->bvec[p].bv_page; set_page_dirty(page); @@ -384,7 +384,7 @@ static void swap_writepage_fs(struct folio *folio, stru= ct swap_iocb **swap_plug) swp_slot_t slot =3D swp_entry_to_swp_slot(folio->swap); struct swap_info_struct *sis =3D __swap_slot_to_info(slot); struct file *swap_file =3D sis->swap_file; - loff_t pos =3D swap_slot_pos(slot); + loff_t pos =3D swap_slot_dev_pos(slot); =20 count_swpout_vm_event(folio); folio_start_writeback(folio); @@ -549,7 +549,7 @@ static void swap_read_folio_fs(struct folio *folio, str= uct swap_iocb **plug) swp_slot_t slot =3D swp_entry_to_swp_slot(folio->swap); struct swap_info_struct *sis =3D __swap_slot_to_info(slot); struct swap_iocb *sio =3D NULL; - loff_t pos =3D swap_slot_pos(slot); + loff_t pos =3D swap_slot_dev_pos(slot); =20 if (plug) sio =3D *plug; diff --git a/mm/shmem.c b/mm/shmem.c index 400e2fa8e77cb..13f7469a04c8a 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2227,7 +2227,6 @@ static int shmem_split_large_entry(struct inode *inod= e, pgoff_t index, XA_STATE_ORDER(xas, &mapping->i_pages, index, 0); int split_order =3D 0; int i; - swp_slot_t slot =3D swp_entry_to_swp_slot(swap); =20 /* Convert user data gfp flags to xarray node gfp flags */ gfp &=3D GFP_RECLAIM_MASK; @@ -2268,13 +2267,7 @@ static int shmem_split_large_entry(struct inode *ino= de, pgoff_t index, */ for (i =3D 0; i < 1 << cur_order; i +=3D (1 << split_order)) { - swp_entry_t tmp_entry; - swp_slot_t tmp_slot; - - tmp_slot =3D - swp_slot(swp_slot_type(slot), - swp_slot_offset(slot) + swap_offset + i); - tmp_entry =3D swp_slot_to_swp_entry(tmp_slot); + swp_entry_t tmp_entry =3D swap_nth(swap, swap_offset + i); =20 __xa_store(&mapping->i_pages, aligned_index + i, swp_to_radix_entry(tmp_entry), 0); diff --git a/mm/swap.h b/mm/swap.h index bdf7aca146643..5eb53758bbd5d 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -36,7 +36,11 @@ struct swap_cluster_info { u16 count; u8 flags; u8 order; - atomic_long_t __rcu *table; /* Swap table entries, see mm/swap_table.h */ + /* + * Reverse map, to look up the virtual swap slot backed by a given physic= al + * swap slot. + */ + atomic_long_t __rcu *table; struct list_head list; }; =20 @@ -212,7 +216,7 @@ static inline struct address_space *swap_address_space(= swp_entry_t entry) } =20 /* Return the swap device position of the swap slot. */ -static inline loff_t swap_slot_pos(swp_slot_t slot) +static inline loff_t swap_slot_dev_pos(swp_slot_t slot) { return ((loff_t)swp_slot_offset(slot)) << PAGE_SHIFT; } diff --git a/mm/swap_state.c b/mm/swap_state.c index 29ec666be4204..c5ceccd756699 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -891,7 +891,8 @@ static int __init swap_init(void) swap_kobj =3D kobject_create_and_add("swap", mm_kobj); if (!swap_kobj) { pr_err("failed to create swap kobject\n"); - return -ENOMEM; + err =3D -ENOMEM; + goto vswap_exit; } err =3D sysfs_create_group(swap_kobj, &swap_attr_group); if (err) { @@ -904,6 +905,8 @@ static int __init swap_init(void) =20 delete_obj: kobject_put(swap_kobj); +vswap_exit: + vswap_exit(); return err; } subsys_initcall(swap_init); diff --git a/mm/swapfile.c b/mm/swapfile.c index 3f70df488c1da..68ec5d9f05848 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -1249,7 +1249,6 @@ static void swap_range_alloc(struct swap_info_struct = *si, static void swap_range_free(struct swap_info_struct *si, unsigned long off= set, unsigned int nr_entries) { - unsigned long begin =3D offset; unsigned long end =3D offset + nr_entries - 1; void (*swap_slot_free_notify)(struct block_device *, unsigned long); unsigned int i; @@ -1258,10 +1257,8 @@ static void swap_range_free(struct swap_info_struct = *si, unsigned long offset, * Use atomic clear_bit operations only on zeromap instead of non-atomic * bitmap_clear to prevent adjacent bits corruption due to simultaneous w= rites. */ - for (i =3D 0; i < nr_entries; i++) { + for (i =3D 0; i < nr_entries; i++) clear_bit(offset + i, si->zeromap); - zswap_invalidate(swp_slot_to_swp_entry(swp_slot(si->type, offset + i))); - } =20 if (si->flags & SWP_BLKDEV) swap_slot_free_notify =3D @@ -1274,7 +1271,6 @@ static void swap_range_free(struct swap_info_struct *= si, unsigned long offset, swap_slot_free_notify(si->bdev, offset); offset++; } - swap_cache_clear_shadow(swp_entry(si->type, begin), nr_entries); =20 /* * Make sure that try_to_unuse() observes si->inuse_pages reaching 0 @@ -1405,7 +1401,7 @@ static bool swap_sync_discard(void) return false; } =20 -static int swap_slot_alloc(swp_slot_t *slot, unsigned int order) +int swap_slot_alloc(swp_slot_t *slot, unsigned int order) { unsigned int size =3D 1 << order; =20 @@ -1441,53 +1437,6 @@ static int swap_slot_alloc(swp_slot_t *slot, unsigne= d int order) return 0; } =20 -/** - * folio_alloc_swap - allocate swap space for a folio - * @folio: folio we want to move to swap - * - * Allocate swap space for the folio and add the folio to the - * swap cache. - * - * Context: Caller needs to hold the folio lock. - * Return: Whether the folio was added to the swap cache. - */ -int folio_alloc_swap(struct folio *folio) -{ - unsigned int order =3D folio_order(folio); - swp_slot_t slot =3D { 0 }; - swp_entry_t entry =3D {}; - int err =3D 0, ret; - - VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); - VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio); - - ret =3D swap_slot_alloc(&slot, order); - if (ret) - return ret; - - /* XXX: for now, physical and virtual swap slots are identical */ - entry.val =3D slot.val; - - /* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */ - if (mem_cgroup_try_charge_swap(folio, entry)) { - err =3D -ENOMEM; - goto out_free; - } - - if (!slot.val) - return -ENOMEM; - - err =3D swap_cache_add_folio(folio, entry, __GFP_HIGH | __GFP_NOMEMALLOC = | __GFP_NOWARN, NULL); - if (err) - goto out_free; - - return 0; - -out_free: - put_swap_folio(folio, entry); - return err; -} - static struct swap_info_struct *_swap_info_get(swp_slot_t slot) { struct swap_info_struct *si; @@ -1733,6 +1682,13 @@ static void swap_slots_free(struct swap_info_struct = *si, unsigned char *map =3D si->swap_map + offset; unsigned char *map_end =3D map + nr_pages; swp_entry_t entry =3D swp_slot_to_swp_entry(slot); + int i; + + /* release all the associated (virtual) swap slots */ + for (i =3D 0; i < nr_pages; i++) { + vswap_free(entry, ci); + entry.val++; + } =20 /* It should never free entries across different clusters */ VM_BUG_ON(ci !=3D __swap_offset_to_cluster(si, offset + nr_pages - 1)); @@ -1745,7 +1701,6 @@ static void swap_slots_free(struct swap_info_struct *= si, *map =3D 0; } while (++map < map_end); =20 - mem_cgroup_uncharge_swap(entry, nr_pages); swap_range_free(si, offset, nr_pages); =20 if (!ci->count) diff --git a/mm/vswap.c b/mm/vswap.c index e68234f053fc9..9aa95558f320a 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -4,7 +4,147 @@ * * Copyright (C) 2024 Meta Platforms, Inc., Nhat Pham */ +#include +#include #include +#include +#include +#include +#include "swap.h" +#include "swap_table.h" + +/* + * Virtual Swap Space + * + * We associate with each swapped out page a virtual swap slot. This will = allow + * us to change the backing state of a swapped out page without having to + * update every single page table entries referring to it. + * + * For now, there is a one-to-one correspondence between a virtual swap sl= ot + * and its associated physical swap slot. + * + * Virtual swap slots are organized into PMD-sized clusters, analogous to + * physical swap allocator. However, unlike the physical swap allocator, + * the clusters are dynamically allocated and freed on-demand. There is no + * "free list" of virtual swap clusters - new free clusters are allocated + * directly from the cluster map xarray. + * + * This allows us to avoid the overhead of pre-allocating a large number of + * virtual swap clusters. + */ + +/** + * Swap descriptor - metadata of a swapped out page. + * + * @slot: The handle to the physical swap slot backing this page. + */ +struct swp_desc { + swp_slot_t slot; +}; + +#define VSWAP_CLUSTER_SHIFT HPAGE_PMD_ORDER +#define VSWAP_CLUSTER_SIZE (1UL << VSWAP_CLUSTER_SHIFT) +#define VSWAP_CLUSTER_MASK (VSWAP_CLUSTER_SIZE - 1) + +/* + * Map from a cluster id to the number of allocated virtual swap slots in = the + * (PMD-sized) cluster. This allows us to quickly allocate an empty cluster + * for a large folio being swapped out. + * + * This xarray's lock is also used as the "global" allocator lock (for e.g= , to + * synchronize global cluster lists manipulation). + */ +static DEFINE_XARRAY_FLAGS(vswap_cluster_map, XA_FLAGS_TRACK_FREE); + +#if SWP_TYPE_SHIFT > 32 +/* + * In 64 bit architecture, the maximum number of virtual swap slots is cap= ped + * by the number of clusters (as the vswap_cluster_map xarray can only all= ocate + * up to U32 clusters). + */ +#define MAX_VSWAP \ + (((unsigned long)U32_MAX << VSWAP_CLUSTER_SHIFT) + (VSWAP_CLUSTER_SIZE - = 1)) +#else +/* + * In 32 bit architecture, just make sure the range of virtual swap slots = is + * the same as the range of physical swap slots. + */ +#define MAX_VSWAP (((MAX_SWAPFILES - 1) << SWP_TYPE_SHIFT) | SWP_OFFSET_MA= SK) +#endif + +static const struct xa_limit vswap_cluster_map_limit =3D { + .max =3D MAX_VSWAP >> VSWAP_CLUSTER_SHIFT, + .min =3D 0, +}; + +static struct list_head partial_clusters_lists[SWAP_NR_ORDERS]; + +/** + * struct vswap_cluster + * + * @lock: Spinlock protecting the cluster's data + * @rcu: RCU head for deferred freeing when the cluster is no longer in use + * @list: List entry for tracking in partial_clusters_lists when not fully= allocated + * @id: Unique identifier for this cluster, used to calculate swap slot va= lues + * @count: Number of allocated virtual swap slots in this cluster + * @order: Order of allocation (0 for single pages, higher for contiguous = ranges) + * @cached: Whether this cluster is cached in a per-CPU variable for fast = allocation + * @full: Whether this cluster is considered full (no more allocations pos= sible) + * @refcnt: Reference count tracking usage of slots in this cluster + * @bitmap: Bitmap tracking which slots in the cluster are allocated + * @descriptors: Pointer to array of swap descriptors for each slot in the= cluster + * + * A vswap_cluster manages a PMD-sized group of contiguous virtual swap sl= ots. + * It tracks which slots are allocated using a bitmap and maintains the + * swap descriptors in an array. The cluster is reference-counted and free= d when + * all of its slots are released and the cluster is not cached. Each clust= er + * only allocates aligned slots of a single order, determined when the clu= ster is + * allocated (and never change for the entire lifetime of the cluster). + * + * Clusters can be in the following states: + * - Cached in per-CPU variables for fast allocation. + * - In partial_clusters_lists when partially allocated but not cached. + * - Marked as full when no more allocations are possible. + */ +struct vswap_cluster { + spinlock_t lock; + union { + struct rcu_head rcu; + struct list_head list; + }; + unsigned long id; + unsigned int count:VSWAP_CLUSTER_SHIFT + 1; + unsigned int order:4; + bool cached:1; + bool full:1; + refcount_t refcnt; + DECLARE_BITMAP(bitmap, VSWAP_CLUSTER_SIZE); + struct swp_desc descriptors[VSWAP_CLUSTER_SIZE]; +}; + +#define VSWAP_VAL_CLUSTER_IDX(val) ((val) >> VSWAP_CLUSTER_SHIFT) +#define VSWAP_CLUSTER_IDX(entry) VSWAP_VAL_CLUSTER_IDX(entry.val) +#define VSWAP_IDX_WITHIN_CLUSTER_VAL(val) ((val) & VSWAP_CLUSTER_MASK) +#define VSWAP_IDX_WITHIN_CLUSTER(entry) VSWAP_IDX_WITHIN_CLUSTER_VAL(entry= .val) + +struct percpu_vswap_cluster { + struct vswap_cluster *clusters[SWAP_NR_ORDERS]; + local_lock_t lock; +}; + +/* + * Per-CPU cache of the last allocated cluster for each order. This allows + * allocation fast path to skip the global vswap_cluster_map's spinlock, if + * the locally cached cluster still has free slots. Note that caching a cl= uster + * also increments its reference count. + */ +static DEFINE_PER_CPU(struct percpu_vswap_cluster, percpu_vswap_cluster) = =3D { + .clusters =3D { NULL, }, + .lock =3D INIT_LOCAL_LOCK(), +}; + +static atomic_t vswap_alloc_reject; +static atomic_t vswap_used; =20 #ifdef CONFIG_DEBUG_FS #include @@ -17,6 +157,10 @@ static int vswap_debug_fs_init(void) return -ENODEV; =20 vswap_debugfs_root =3D debugfs_create_dir("vswap", NULL); + debugfs_create_atomic_t("alloc_reject", 0444, + vswap_debugfs_root, &vswap_alloc_reject); + debugfs_create_atomic_t("used", 0444, vswap_debugfs_root, &vswap_used); + return 0; } #else @@ -26,10 +170,524 @@ static int vswap_debug_fs_init(void) } #endif =20 +static struct swp_desc *vswap_iter(struct vswap_cluster **clusterp, unsign= ed long i) +{ + unsigned long cluster_id =3D VSWAP_VAL_CLUSTER_IDX(i); + struct vswap_cluster *cluster =3D *clusterp; + struct swp_desc *desc =3D NULL; + unsigned long slot_index; + + if (!cluster || cluster_id !=3D cluster->id) { + if (cluster) + spin_unlock(&cluster->lock); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + if (!cluster) + goto done; + VM_WARN_ON(cluster->id !=3D cluster_id); + spin_lock(&cluster->lock); + } + + slot_index =3D VSWAP_IDX_WITHIN_CLUSTER_VAL(i); + if (test_bit(slot_index, cluster->bitmap)) + desc =3D &cluster->descriptors[slot_index]; + + if (!desc) { + spin_unlock(&cluster->lock); + cluster =3D NULL; + } + +done: + *clusterp =3D cluster; + return desc; +} + +static bool cluster_is_alloc_candidate(struct vswap_cluster *cluster) +{ + return cluster->count + (1 << (cluster->order)) <=3D VSWAP_CLUSTER_SIZE; +} + +static void __vswap_alloc_from_cluster(struct vswap_cluster *cluster, int = start) +{ + int i, nr =3D 1 << cluster->order; + struct swp_desc *desc; + + for (i =3D 0; i < nr; i++) { + desc =3D &cluster->descriptors[start + i]; + desc->slot.val =3D 0; + } + cluster->count +=3D nr; +} + +static unsigned long vswap_alloc_from_cluster(struct vswap_cluster *cluste= r) +{ + int nr =3D 1 << cluster->order; + unsigned long i =3D cluster->id ? 0 : nr; + + VM_WARN_ON(!spin_is_locked(&cluster->lock)); + if (!cluster_is_alloc_candidate(cluster)) + return 0; + + /* Find the first free range of nr contiguous aligned slots */ + i =3D bitmap_find_next_zero_area(cluster->bitmap, + VSWAP_CLUSTER_SIZE, i, nr, nr - 1); + if (i >=3D VSWAP_CLUSTER_SIZE) + return 0; + + /* Mark the range as allocated in the bitmap */ + bitmap_set(cluster->bitmap, i, nr); + + refcount_add(nr, &cluster->refcnt); + __vswap_alloc_from_cluster(cluster, i); + return i + (cluster->id << VSWAP_CLUSTER_SHIFT); +} + +/* Allocate a contiguous range of virtual swap slots */ +static swp_entry_t vswap_alloc(int order) +{ + struct xa_limit limit =3D vswap_cluster_map_limit; + struct vswap_cluster *local, *cluster; + int nr =3D 1 << order; + bool need_caching =3D true; + u32 cluster_id; + swp_entry_t entry; + + entry.val =3D 0; + + /* first, let's try the locally cached cluster */ + rcu_read_lock(); + local_lock(&percpu_vswap_cluster.lock); + cluster =3D this_cpu_read(percpu_vswap_cluster.clusters[order]); + if (cluster) { + spin_lock(&cluster->lock); + entry.val =3D vswap_alloc_from_cluster(cluster); + need_caching =3D !entry.val; + + if (!entry.val || !cluster_is_alloc_candidate(cluster)) { + this_cpu_write(percpu_vswap_cluster.clusters[order], NULL); + cluster->cached =3D false; + refcount_dec(&cluster->refcnt); + cluster->full =3D true; + } + spin_unlock(&cluster->lock); + } + local_unlock(&percpu_vswap_cluster.lock); + rcu_read_unlock(); + + /* + * Local cluster does not have space. Let's try the uncached partial + * clusters before acquiring a new free cluster to reduce fragmentation, + * and avoid having to allocate a new cluster structure. + */ + if (!entry.val) { + cluster =3D NULL; + xa_lock(&vswap_cluster_map); + list_for_each_entry_safe(cluster, local, + &partial_clusters_lists[order], list) { + if (!spin_trylock(&cluster->lock)) + continue; + + entry.val =3D vswap_alloc_from_cluster(cluster); + list_del_init(&cluster->list); + cluster->full =3D !entry.val || !cluster_is_alloc_candidate(cluster); + need_caching =3D !cluster->full; + spin_unlock(&cluster->lock); + if (entry.val) + break; + } + xa_unlock(&vswap_cluster_map); + } + + /* try a new free cluster */ + if (!entry.val) { + cluster =3D kvzalloc(sizeof(*cluster), GFP_KERNEL); + if (cluster) { + /* first cluster cannot allocate a PMD-sized THP */ + if (order =3D=3D SWAP_NR_ORDERS - 1) + limit.min =3D 1; + + if (!xa_alloc(&vswap_cluster_map, &cluster_id, cluster, limit, + GFP_KERNEL)) { + spin_lock_init(&cluster->lock); + cluster->id =3D cluster_id; + cluster->order =3D order; + INIT_LIST_HEAD(&cluster->list); + /* Initialize bitmap to all zeros (all slots free) */ + bitmap_zero(cluster->bitmap, VSWAP_CLUSTER_SIZE); + entry.val =3D cluster->id << VSWAP_CLUSTER_SHIFT; + refcount_set(&cluster->refcnt, nr); + if (!cluster_id) + entry.val +=3D nr; + __vswap_alloc_from_cluster(cluster, + (entry.val & VSWAP_CLUSTER_MASK)); + /* Mark the allocated range in the bitmap */ + bitmap_set(cluster->bitmap, (entry.val & VSWAP_CLUSTER_MASK), nr); + need_caching =3D cluster_is_alloc_candidate(cluster); + } else { + /* Failed to insert into cluster map, free the cluster */ + kvfree(cluster); + cluster =3D NULL; + } + } + } + + if (need_caching && entry.val) { + local_lock(&percpu_vswap_cluster.lock); + local =3D this_cpu_read(percpu_vswap_cluster.clusters[order]); + if (local !=3D cluster) { + if (local) { + spin_lock(&local->lock); + /* only update the local cache if cached cluster is full */ + need_caching =3D !cluster_is_alloc_candidate(local); + if (need_caching) { + this_cpu_write(percpu_vswap_cluster.clusters[order], NULL); + local->cached =3D false; + refcount_dec(&local->refcnt); + } + spin_unlock(&local->lock); + } + + VM_WARN_ON(!cluster); + spin_lock(&cluster->lock); + if (cluster_is_alloc_candidate(cluster)) { + if (need_caching) { + this_cpu_write(percpu_vswap_cluster.clusters[order], cluster); + refcount_inc(&cluster->refcnt); + cluster->cached =3D true; + } else { + xa_lock(&vswap_cluster_map); + VM_WARN_ON(!list_empty(&cluster->list)); + list_add(&cluster->list, &partial_clusters_lists[order]); + xa_unlock(&vswap_cluster_map); + } + } + spin_unlock(&cluster->lock); + } + local_unlock(&percpu_vswap_cluster.lock); + } + + if (entry.val) { + VM_WARN_ON(entry.val + nr - 1 > MAX_VSWAP); + atomic_add(nr, &vswap_used); + } else { + atomic_add(nr, &vswap_alloc_reject); + } + return entry; +} + +static void vswap_cluster_free(struct vswap_cluster *cluster) +{ + VM_WARN_ON(cluster->count || cluster->cached); + VM_WARN_ON(!spin_is_locked(&cluster->lock)); + xa_lock(&vswap_cluster_map); + list_del_init(&cluster->list); + __xa_erase(&vswap_cluster_map, cluster->id); + xa_unlock(&vswap_cluster_map); + rcu_head_init(&cluster->rcu); + kvfree_rcu(cluster, rcu); +} + +static inline void release_vswap_slot(struct vswap_cluster *cluster, + unsigned long index) +{ + unsigned long slot_index =3D VSWAP_IDX_WITHIN_CLUSTER_VAL(index); + + VM_WARN_ON(!spin_is_locked(&cluster->lock)); + cluster->count--; + + bitmap_clear(cluster->bitmap, slot_index, 1); + + /* we only free uncached empty clusters */ + if (refcount_dec_and_test(&cluster->refcnt)) + vswap_cluster_free(cluster); + else if (cluster->full && cluster_is_alloc_candidate(cluster)) { + cluster->full =3D false; + if (!cluster->cached) { + xa_lock(&vswap_cluster_map); + VM_WARN_ON(!list_empty(&cluster->list)); + list_add_tail(&cluster->list, + &partial_clusters_lists[cluster->order]); + xa_unlock(&vswap_cluster_map); + } + } + + atomic_dec(&vswap_used); +} + +/* + * Update the physical-to-virtual swap slot mapping. + * Caller must ensure the physical swap slot's cluster is locked. + */ +static void vswap_rmap_set(struct swap_cluster_info *ci, swp_slot_t slot, + unsigned long vswap, int nr) +{ + atomic_long_t *table; + unsigned long slot_offset =3D swp_slot_offset(slot); + unsigned int ci_off =3D slot_offset % SWAPFILE_CLUSTER; + int i; + + table =3D rcu_dereference_protected(ci->table, lockdep_is_held(&ci->lock)= ); + VM_WARN_ON(!table); + for (i =3D 0; i < nr; i++) + __swap_table_set(ci, ci_off + i, vswap ? vswap + i : 0); +} + +/** + * vswap_free - free a virtual swap slot. + * @entry: the virtual swap slot to free + * @ci: the physical swap slot's cluster (optional, can be NULL) + * + * If @ci is NULL, this function is called to clean up a virtual swap entry + * when no linkage has been established between physical and virtual swap = slots. + * If @ci is provided, the caller must ensure it is locked. + */ +void vswap_free(swp_entry_t entry, struct swap_cluster_info *ci) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + + if (!entry.val) + return; + + swap_cache_clear_shadow(entry, 1); + zswap_invalidate(entry); + mem_cgroup_uncharge_swap(entry, 1); + + /* do not immediately erase the virtual slot to prevent its reuse */ + rcu_read_lock(); + desc =3D vswap_iter(&cluster, entry.val); + if (!desc) { + rcu_read_unlock(); + return; + } + + if (desc->slot.val) + vswap_rmap_set(ci, desc->slot, 0, 1); + + /* erase forward mapping and release the virtual slot for reallocation */ + release_vswap_slot(cluster, entry.val); + spin_unlock(&cluster->lock); + rcu_read_unlock(); +} + +/** + * folio_alloc_swap - allocate swap space for a folio. + * @folio: the folio. + * + * Return: 0, if the allocation succeeded, -ENOMEM, if the allocation fail= ed. + */ +int folio_alloc_swap(struct folio *folio) +{ + struct vswap_cluster *cluster =3D NULL; + struct swap_info_struct *si; + struct swap_cluster_info *ci; + int i, err, nr =3D folio_nr_pages(folio), order =3D folio_order(folio); + struct swp_desc *desc; + swp_entry_t entry; + swp_slot_t slot; + + VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); + VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio); + + entry =3D vswap_alloc(folio_order(folio)); + if (!entry.val) + return -ENOMEM; + + /* + * XXX: for now, we always allocate a physical swap slot for each virtual + * swap slot, and their lifetime are coupled. This will change once we + * decouple virtual swap slots from their backing states, and only alloca= te + * physical swap slots for them on demand (i.e on zswap writeback, or + * fallback from zswap store failure). + */ + if (swap_slot_alloc(&slot, order)) { + for (i =3D 0; i < nr; i++) + vswap_free((swp_entry_t){entry.val + i}, NULL); + entry.val =3D 0; + return -ENOMEM; + } + + /* establish the vrtual <-> physical swap slots linkages. */ + si =3D __swap_slot_to_info(slot); + ci =3D swap_cluster_lock(si, swp_slot_offset(slot)); + vswap_rmap_set(ci, slot, entry.val, nr); + swap_cluster_unlock(ci); + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + VM_WARN_ON(!desc); + + desc->slot.val =3D slot.val + i; + } + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + /* + * XXX: for now, we charge towards the memory cgroup's swap limit on virt= ual + * swap slots allocation. This is acceptable because as noted above, each + * virtual swap slot corresponds to a physical swap slot. Once we have + * decoupled virtual and physical swap slots, we will only charge when we + * actually allocate a physical swap slot. + */ + if (mem_cgroup_try_charge_swap(folio, entry)) + goto out_free; + + err =3D swap_cache_add_folio(folio, entry, __GFP_HIGH | __GFP_NOMEMALLOC = | __GFP_NOWARN, NULL); + if (err) + goto out_free; + + return 0; + +out_free: + put_swap_folio(folio, entry); + return -ENOMEM; +} + +/** + * swp_entry_to_swp_slot - look up the physical swap slot corresponding to= a + * virtual swap slot. + * @entry: the virtual swap slot. + * + * Return: the physical swap slot corresponding to the virtual swap slot. + */ +swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + swp_slot_t slot; + + slot.val =3D 0; + if (!entry.val) + return slot; + + rcu_read_lock(); + desc =3D vswap_iter(&cluster, entry.val); + if (!desc) { + rcu_read_unlock(); + return (swp_slot_t){0}; + } + slot =3D desc->slot; + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return slot; +} + +/** + * swp_slot_to_swp_entry - look up the virtual swap slot corresponding to a + * physical swap slot. + * @slot: the physical swap slot. + * + * Return: the virtual swap slot corresponding to the physical swap slot. + */ +swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot) +{ + swp_entry_t ret; + struct swap_cluster_info *ci; + unsigned long offset; + unsigned int ci_off; + + ret.val =3D 0; + if (!slot.val) + return ret; + + offset =3D swp_slot_offset(slot); + ci_off =3D offset % SWAPFILE_CLUSTER; + ci =3D __swap_slot_to_cluster(slot); + + ret.val =3D swap_table_get(ci, ci_off); + return ret; +} + +bool tryget_swap_entry(swp_entry_t entry, struct swap_info_struct **si) +{ + struct vswap_cluster *cluster; + swp_slot_t slot; + + slot =3D swp_entry_to_swp_slot(entry); + *si =3D swap_slot_tryget_swap_info(slot); + if (!*si) + return false; + + /* + * Ensure the cluster and its associated data structures (swap cache etc.) + * remain valid. + */ + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, VSWAP_CLUSTER_IDX(entry)); + if (!cluster || !refcount_inc_not_zero(&cluster->refcnt)) { + rcu_read_unlock(); + swap_slot_put_swap_info(*si); + *si =3D NULL; + return false; + } + rcu_read_unlock(); + return true; +} + +void put_swap_entry(swp_entry_t entry, struct swap_info_struct *si) +{ + struct vswap_cluster *cluster; + + if (si) + swap_slot_put_swap_info(si); + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, VSWAP_CLUSTER_IDX(entry)); + spin_lock(&cluster->lock); + if (refcount_dec_and_test(&cluster->refcnt)) + vswap_cluster_free(cluster); + spin_unlock(&cluster->lock); + rcu_read_unlock(); +} + +static int vswap_cpu_dead(unsigned int cpu) +{ + struct percpu_vswap_cluster *percpu_cluster; + struct vswap_cluster *cluster; + int order; + + percpu_cluster =3D per_cpu_ptr(&percpu_vswap_cluster, cpu); + + rcu_read_lock(); + local_lock(&percpu_cluster->lock); + for (order =3D 0; order < SWAP_NR_ORDERS; order++) { + cluster =3D percpu_cluster->clusters[order]; + if (cluster) { + percpu_cluster->clusters[order] =3D NULL; + spin_lock(&cluster->lock); + cluster->cached =3D false; + if (refcount_dec_and_test(&cluster->refcnt)) + vswap_cluster_free(cluster); + spin_unlock(&cluster->lock); + } + } + local_unlock(&percpu_cluster->lock); + rcu_read_unlock(); + + return 0; +} + + int vswap_init(void) { + int i; + + if (cpuhp_setup_state_nocalls(CPUHP_MM_VSWAP_DEAD, "mm/vswap:dead", NULL, + vswap_cpu_dead)) { + pr_err("Failed to register vswap CPU hotplug callback\n"); + return -ENOMEM; + } + if (vswap_debug_fs_init()) pr_warn("Failed to initialize vswap debugfs\n"); =20 + for (i =3D 0; i < SWAP_NR_ORDERS; i++) + INIT_LIST_HEAD(&partial_clusters_lists[i]); + return 0; } + +void vswap_exit(void) +{ +} --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-ot1-f43.google.com (mail-ot1-f43.google.com [209.85.210.43]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0574E35E530 for ; Sun, 8 Feb 2026 21:59:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.43 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587944; cv=none; b=Vtp8nQPcZ5T9teZPEV8zHFG2Yd+ODsw47EJ1vuOXdwJqw1RILjaeWiJXhroDQRVtA8J4pZM/5IzioTHNZjS/KJyfeOLOoQ5MA/4E07nE7C8HuOpz0J2Wd/8g1UjjEPbmxIFrhiQnydX+2AaWuFyMJFLBnfLEDjLehkubfQzsSmY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587944; c=relaxed/simple; bh=7ZpeUy08Tt7waGoLPUK+KDH/WTBw71RG9IGuJ1VLi3Q=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Oqnfo84RictalgeFKaaU2LNVCO5Hsk624B3OFtUKtnG75R9H4tVFnu6AvmuJVqpZ7Nf6uKVs6xSwAWbARIYxziTu1tL3RVYCctHaNKedC8+UbAY+bKaeJkYTV3ncFzuVdGYkXebq1xH+52B12u8mHQckf9NO0WOvZfl+7b8+ju0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=SrlVNVNv; arc=none smtp.client-ip=209.85.210.43 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.b="SrlVNVNv" Received: by mail-ot1-f43.google.com with SMTP id 46e09a7af769-7d1866473b0so2190867a34.1 for ; Sun, 08 Feb 2026 13:59:03 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587943; x=1771192743; 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; bh=OU6FG/1ImjDgjh8K5anzkahxddqp677D6NQQqJ3zZIs=; b=SrlVNVNvok1opZNrAhrAHaz6xf+vnLfamAj6lRJohkoNWpURkxr6lfNZ3xsZlsz/IY dpLfIBD2LLV7fBPUP/mbZlHhtXLYIuGDRqcvKPSydLyFnxYIFVnx37RvcJ1tGt+LiHIB Zjv8tbjWw4EblgfoVgSIXORvzkZEl59LLV5b7w7VUC1RN0isfchgXVGtGE7NAhrM6lL8 vfngYznfGqU0g4uw2KGecfOlmTOj2sP0OzNCqxnRzbBu0yDuXXGSzJ5f7F9SZ/+EEnTV eVt4a5yRLWB1EjZrAPXR+Li+SZynt64+0m0QlALTwaF8TLgwCrpiqpWO0UMFTZn4f68k 6r+Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587943; x=1771192743; 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; bh=OU6FG/1ImjDgjh8K5anzkahxddqp677D6NQQqJ3zZIs=; b=bWX9DH1CDS7mO4UnngqtUq56/Otl3+DLOB9qcdIUS6lQhP0T7cc8nsWCZa0RxTcyfQ 9A96NNBnLc49IK6rLRXSx+Uw1FlcY1r+YKr+UPQEPQV3EkugYx2a/PsT7fVAZ1Ws7ETf RWPiiCIQEzFwcgGSHFzgdIFJYnrrlsltwG3Jivb4ZTujiiiH8PaezsnuGQKMevN139mC 4+QU3w+bqdpc5Vow9p9wNOzrTr8i0AnfjDEKGoo5QDbs9lyXlcwl/gyi1eRQca4cso4o RyETE40ecEreGX4unmQL0mxGAdU52QXbF/zzeWC0XUUeoDBy9ffKiB9NCxKEX6iEV1Fr os8A== X-Forwarded-Encrypted: i=1; AJvYcCVU5eQ2bf+tkBo6On7n61jo/SeyUTyFzcp9pS0WM7yj4A6H+oBpb8fC86TUY0FycDi7XyHKz946/bXZiYo=@vger.kernel.org X-Gm-Message-State: AOJu0YxED35Y1z5YmnzWjnnbfS/7OSMk883V1O1IxGCjHKySmrHYbz8g iXqb+j1VPrBP01brozN8VNa83KPQ4GTHGF8sE/Limps5V8CS3kBg+yC+ X-Gm-Gg: AZuq6aLEwGc8W7pmDPLBQFwXs4K4o9mBxNinIMna5/0DAmu4BvTcbI225qgD6BL5HNw 4m3YjAennX2gKl9HIK7dxbmy9GSCe0x6kCssJgzaN6I/evVGZcX7VDe/+zfdECicDKqOosw1wzg vHgHe3+ThEPN0JS6EdJuIUNLZmWlejA21gR92IEXuZLxZ2Ay9DOnICWaRjjT24M+kNAqePn17kz TTvvjj7KPFge5JPn2jYammuTd0GtzDoMf7nenJPmvcqyHVmwN5oC2lDa2Q3kQE/P4H5guaIfsKB jpLPhIMP/c4LXiRPVkn+7/uoDMsWlAPiCJ5jo1EazPJzF13bIUe+95Vx124Ez1DABNRH1o2T50/ ySTFd+iCeVE/WcYm75tTvE+0uQVZYgXevZOpJ6aQVVPj51FVtxXsDs2uLBLQuDAjyYd1ztViFeH eBx4KkdkysXp+6fYwTOQ66B+rjwvEU1O5Q+Q== X-Received: by 2002:a05:6830:6518:b0:7c7:8280:9207 with SMTP id 46e09a7af769-7d464689b0amr5463329a34.37.1770587942713; Sun, 08 Feb 2026 13:59:02 -0800 (PST) Received: from localhost ([2a03:2880:10ff:53::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d464785f68sm6051602a34.16.2026.02.08.13.59.01 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:02 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 10/20] swap: move swap cache to virtual swap descriptor Date: Sun, 8 Feb 2026 13:58:23 -0800 Message-ID: <20260208215839.87595-11-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Move the swap cache (and workingset shadow for anonymous pages) to the virtual swap descriptor. This effectively range-partitions the swap cache by virtual swap clusters (of PMD sized), eliminate swap cache lock contention. Signed-off-by: Nhat Pham --- mm/huge_memory.c | 4 +- mm/migrate.c | 6 +- mm/shmem.c | 4 +- mm/swap.h | 16 +-- mm/swap_state.c | 251 +-------------------------------- mm/vmscan.c | 6 +- mm/vswap.c | 350 ++++++++++++++++++++++++++++++++++++++++++++++- 7 files changed, 364 insertions(+), 273 deletions(-) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index 21215ac870144..dcbd3821d6178 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -3825,7 +3825,7 @@ static int __folio_freeze_and_split_unmapped(struct f= olio *folio, unsigned int n return -EINVAL; } =20 - swap_cache_lock(); + swap_cache_lock(folio->swap); } =20 /* lock lru list/PageCompound, ref frozen by page_ref_freeze */ @@ -3901,7 +3901,7 @@ static int __folio_freeze_and_split_unmapped(struct f= olio *folio, unsigned int n unlock_page_lruvec(lruvec); =20 if (folio_test_swapcache(folio)) - swap_cache_unlock(); + swap_cache_unlock(folio->swap); } else { split_queue_unlock(ds_queue); return -EAGAIN; diff --git a/mm/migrate.c b/mm/migrate.c index 11d9b43dff5d8..e850b05a232de 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -600,13 +600,13 @@ static int __folio_migrate_mapping(struct address_spa= ce *mapping, newzone =3D folio_zone(newfolio); =20 if (folio_test_swapcache(folio)) - swap_cache_lock_irq(); + swap_cache_lock_irq(folio->swap); else xas_lock_irq(&xas); =20 if (!folio_ref_freeze(folio, expected_count)) { if (folio_test_swapcache(folio)) - swap_cache_unlock_irq(); + swap_cache_unlock_irq(folio->swap); else xas_unlock_irq(&xas); return -EAGAIN; @@ -652,7 +652,7 @@ static int __folio_migrate_mapping(struct address_space= *mapping, =20 /* Leave irq disabled to prevent preemption while updating stats */ if (folio_test_swapcache(folio)) - swap_cache_unlock(); + swap_cache_unlock(folio->swap); else xas_unlock(&xas); =20 diff --git a/mm/shmem.c b/mm/shmem.c index 13f7469a04c8a..66cf8af6779ca 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2168,12 +2168,12 @@ static int shmem_replace_folio(struct folio **folio= p, gfp_t gfp, new->swap =3D entry; folio_set_swapcache(new); =20 - swap_cache_lock_irq(); + swap_cache_lock_irq(entry); __swap_cache_replace_folio(old, new); mem_cgroup_replace_folio(old, new); shmem_update_stats(new, nr_pages); shmem_update_stats(old, -nr_pages); - swap_cache_unlock_irq(); + swap_cache_unlock_irq(entry); =20 folio_add_lru(new); *foliop =3D new; diff --git a/mm/swap.h b/mm/swap.h index 5eb53758bbd5d..57ed24a2d6356 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -205,10 +205,12 @@ void __swap_writepage(struct folio *folio, struct swa= p_iocb **swap_plug); =20 /* linux/mm/swap_state.c */ extern struct address_space swap_space __read_mostly; -void swap_cache_lock_irq(void); -void swap_cache_unlock_irq(void); -void swap_cache_lock(void); -void swap_cache_unlock(void); + +/* linux/mm/vswap.c */ +void swap_cache_lock_irq(swp_entry_t entry); +void swap_cache_unlock_irq(swp_entry_t entry); +void swap_cache_lock(swp_entry_t entry); +void swap_cache_unlock(swp_entry_t entry); =20 static inline struct address_space *swap_address_space(swp_entry_t entry) { @@ -256,12 +258,11 @@ static inline bool folio_matches_swap_entry(const str= uct folio *folio, */ struct folio *swap_cache_get_folio(swp_entry_t entry); void *swap_cache_get_shadow(swp_entry_t entry); -int swap_cache_add_folio(struct folio *folio, swp_entry_t entry, gfp_t gfp= , void **shadow); +void swap_cache_add_folio(struct folio *folio, swp_entry_t entry, void **s= hadow); void swap_cache_del_folio(struct folio *folio); /* Below helpers require the caller to lock the swap cache. */ void __swap_cache_del_folio(struct folio *folio, swp_entry_t entry, void *= shadow); void __swap_cache_replace_folio(struct folio *old, struct folio *new); -void swap_cache_clear_shadow(swp_entry_t entry, int nr_ents); =20 void show_swap_cache_info(void); void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int n= r); @@ -422,9 +423,8 @@ static inline void *swap_cache_get_shadow(swp_entry_t e= ntry) return NULL; } =20 -static inline int swap_cache_add_folio(struct folio *folio, swp_entry_t en= try, gfp_t gfp, void **shadow) +static inline void swap_cache_add_folio(struct folio *folio, swp_entry_t e= ntry, void **shadow) { - return 0; } =20 static inline void swap_cache_del_folio(struct folio *folio) diff --git a/mm/swap_state.c b/mm/swap_state.c index c5ceccd756699..00fa3e76a5c19 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -41,28 +41,6 @@ struct address_space swap_space __read_mostly =3D { .a_ops =3D &swap_aops, }; =20 -static DEFINE_XARRAY(swap_cache); - -void swap_cache_lock_irq(void) -{ - xa_lock_irq(&swap_cache); -} - -void swap_cache_unlock_irq(void) -{ - xa_unlock_irq(&swap_cache); -} - -void swap_cache_lock(void) -{ - xa_lock(&swap_cache); -} - -void swap_cache_unlock(void) -{ - xa_unlock(&swap_cache); -} - static bool enable_vma_readahead __read_mostly =3D true; =20 #define SWAP_RA_ORDER_CEILING 5 @@ -94,231 +72,6 @@ void show_swap_cache_info(void) printk("Total swap =3D %lukB\n", K(total_swap_pages)); } =20 -/** - * swap_cache_get_folio - Looks up a folio in the swap cache. - * @entry: swap entry used for the lookup. - * - * A found folio will be returned unlocked and with its refcount increased. - * - * Context: Caller must ensure @entry is valid and protect the swap device - * with reference count or locks. - * Return: Returns the found folio on success, NULL otherwise. The caller - * must lock nd check if the folio still matches the swap entry before - * use (e.g., folio_matches_swap_entry). - */ -struct folio *swap_cache_get_folio(swp_entry_t entry) -{ - void *entry_val; - struct folio *folio; - - for (;;) { - rcu_read_lock(); - entry_val =3D xa_load(&swap_cache, entry.val); - if (!entry_val || xa_is_value(entry_val)) { - rcu_read_unlock(); - return NULL; - } - folio =3D entry_val; - if (likely(folio_try_get(folio))) { - rcu_read_unlock(); - return folio; - } - rcu_read_unlock(); - } - - return NULL; -} - -/** - * swap_cache_get_shadow - Looks up a shadow in the swap cache. - * @entry: swap entry used for the lookup. - * - * Context: Caller must ensure @entry is valid and protect the swap device - * with reference count or locks. - * Return: Returns either NULL or an XA_VALUE (shadow). - */ -void *swap_cache_get_shadow(swp_entry_t entry) -{ - void *entry_val; - - rcu_read_lock(); - entry_val =3D xa_load(&swap_cache, entry.val); - rcu_read_unlock(); - - if (xa_is_value(entry_val)) - return entry_val; - return NULL; -} - -/** - * swap_cache_add_folio - Add a folio into the swap cache. - * @folio: The folio to be added. - * @entry: The swap entry corresponding to the folio. - * @gfp: gfp_mask for XArray node allocation. - * @shadowp: If a shadow is found, return the shadow. - * - * Context: Caller must ensure @entry is valid and protect the swap device - * with reference count or locks. - * The caller also needs to update the corresponding swap_map slots with - * SWAP_HAS_CACHE bit to avoid race or conflict. - * - * Return: 0 on success, negative error code on failure. - */ -int swap_cache_add_folio(struct folio *folio, swp_entry_t entry, gfp_t gfp= , void **shadowp) -{ - XA_STATE_ORDER(xas, &swap_cache, entry.val, folio_order(folio)); - unsigned long nr_pages =3D folio_nr_pages(folio); - unsigned long i; - void *old; - - VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); - VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio); - VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio); - - folio_ref_add(folio, nr_pages); - folio_set_swapcache(folio); - folio->swap =3D entry; - - do { - xas_lock_irq(&xas); - xas_create_range(&xas); - if (xas_error(&xas)) - goto unlock; - for (i =3D 0; i < nr_pages; i++) { - VM_BUG_ON_FOLIO(xas.xa_index !=3D entry.val + i, folio); - old =3D xas_load(&xas); - if (old && !xa_is_value(old)) { - VM_WARN_ON_ONCE_FOLIO(1, folio); - xas_set_err(&xas, -EEXIST); - goto unlock; - } - if (shadowp && xa_is_value(old) && !*shadowp) - *shadowp =3D old; - xas_store(&xas, folio); - xas_next(&xas); - } - node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages); - lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages); -unlock: - xas_unlock_irq(&xas); - } while (xas_nomem(&xas, gfp)); - - if (!xas_error(&xas)) - return 0; - - folio_clear_swapcache(folio); - folio_ref_sub(folio, nr_pages); - return xas_error(&xas); -} - -/** - * __swap_cache_del_folio - Removes a folio from the swap cache. - * @folio: The folio. - * @entry: The first swap entry that the folio corresponds to. - * @shadow: shadow value to be filled in the swap cache. - * - * Removes a folio from the swap cache and fills a shadow in place. - * This won't put the folio's refcount. The caller has to do that. - * - * Context: Caller must ensure the folio is locked and in the swap cache - * using the index of @entry, and lock the swap cache xarray. - */ -void __swap_cache_del_folio(struct folio *folio, swp_entry_t entry, void *= shadow) -{ - long nr_pages =3D folio_nr_pages(folio); - XA_STATE(xas, &swap_cache, entry.val); - int i; - - VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); - VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); - VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio); - - for (i =3D 0; i < nr_pages; i++) { - void *old =3D xas_store(&xas, shadow); - VM_WARN_ON_FOLIO(old !=3D folio, folio); - xas_next(&xas); - } - - folio->swap.val =3D 0; - folio_clear_swapcache(folio); - node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages); - lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages); -} - -/** - * swap_cache_del_folio - Removes a folio from the swap cache. - * @folio: The folio. - * - * Same as __swap_cache_del_folio, but handles lock and refcount. The - * caller must ensure the folio is either clean or has a swap count - * equal to zero, or it may cause data loss. - * - * Context: Caller must ensure the folio is locked and in the swap cache. - */ -void swap_cache_del_folio(struct folio *folio) -{ - swp_entry_t entry =3D folio->swap; - - xa_lock_irq(&swap_cache); - __swap_cache_del_folio(folio, entry, NULL); - xa_unlock_irq(&swap_cache); - - put_swap_folio(folio, entry); - folio_ref_sub(folio, folio_nr_pages(folio)); -} - -/** - * __swap_cache_replace_folio - Replace a folio in the swap cache. - * @old: The old folio to be replaced. - * @new: The new folio. - * - * Replace an existing folio in the swap cache with a new folio. The - * caller is responsible for setting up the new folio's flag and swap - * entries. Replacement will take the new folio's swap entry value as - * the starting offset to override all slots covered by the new folio. - * - * Context: Caller must ensure both folios are locked, and lock the - * swap cache xarray. - */ -void __swap_cache_replace_folio(struct folio *old, struct folio *new) -{ - swp_entry_t entry =3D new->swap; - unsigned long nr_pages =3D folio_nr_pages(new); - XA_STATE(xas, &swap_cache, entry.val); - int i; - - VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new)); - VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new)); - VM_WARN_ON_ONCE(!entry.val); - - for (i =3D 0; i < nr_pages; i++) { - void *old_entry =3D xas_store(&xas, new); - WARN_ON_ONCE(!old_entry || xa_is_value(old_entry) || old_entry !=3D old); - xas_next(&xas); - } -} - -/** - * swap_cache_clear_shadow - Clears a set of shadows in the swap cache. - * @entry: The starting index entry. - * @nr_ents: How many slots need to be cleared. - * - * Context: Caller must ensure the range is valid and all in one single cl= uster, - * not occupied by any folio. - */ -void swap_cache_clear_shadow(swp_entry_t entry, int nr_ents) -{ - XA_STATE(xas, &swap_cache, entry.val); - int i; - - xas_lock(&xas); - for (i =3D 0; i < nr_ents; i++) { - xas_store(&xas, NULL); - xas_next(&xas); - } - xas_unlock(&xas); -} - /* * If we are the only user, then try to free up the swap cache. * @@ -497,9 +250,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry= , gfp_t gfp_mask, if (mem_cgroup_swapin_charge_folio(new_folio, NULL, gfp_mask, entry)) goto fail_unlock; =20 - /* May fail (-ENOMEM) if XArray node allocation failed. */ - if (swap_cache_add_folio(new_folio, entry, gfp_mask & GFP_RECLAIM_MASK, &= shadow)) - goto fail_unlock; + swap_cache_add_folio(new_folio, entry, &shadow); =20 memcg1_swapin(entry, 1); =20 diff --git a/mm/vmscan.c b/mm/vmscan.c index 558ff7f413786..c9ec1a1458b4e 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -712,7 +712,7 @@ static int __remove_mapping(struct address_space *mappi= ng, struct folio *folio, BUG_ON(mapping !=3D folio_mapping(folio)); =20 if (folio_test_swapcache(folio)) { - swap_cache_lock_irq(); + swap_cache_lock_irq(folio->swap); } else { spin_lock(&mapping->host->i_lock); xa_lock_irq(&mapping->i_pages); @@ -759,7 +759,7 @@ static int __remove_mapping(struct address_space *mappi= ng, struct folio *folio, shadow =3D workingset_eviction(folio, target_memcg); __swap_cache_del_folio(folio, swap, shadow); memcg1_swapout(folio, swap); - swap_cache_unlock_irq(); + swap_cache_unlock_irq(swap); put_swap_folio(folio, swap); } else { void (*free_folio)(struct folio *); @@ -798,7 +798,7 @@ static int __remove_mapping(struct address_space *mappi= ng, struct folio *folio, =20 cannot_free: if (folio_test_swapcache(folio)) { - swap_cache_unlock_irq(); + swap_cache_unlock_irq(folio->swap); } else { xa_unlock_irq(&mapping->i_pages); spin_unlock(&mapping->host->i_lock); diff --git a/mm/vswap.c b/mm/vswap.c index 9aa95558f320a..d44199dc059a3 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -37,9 +37,15 @@ * Swap descriptor - metadata of a swapped out page. * * @slot: The handle to the physical swap slot backing this page. + * @swap_cache: The folio in swap cache. + * @shadow: The shadow entry. */ struct swp_desc { swp_slot_t slot; + union { + struct folio *swap_cache; + void *shadow; + }; }; =20 #define VSWAP_CLUSTER_SHIFT HPAGE_PMD_ORDER @@ -170,6 +176,24 @@ static int vswap_debug_fs_init(void) } #endif =20 +/* + * Lockless version of vswap_iter - assumes caller holds cluster lock. + * Used when iterating within the same cluster with the lock already held. + */ +static struct swp_desc *__vswap_iter(struct vswap_cluster *cluster, unsign= ed long i) +{ + unsigned long slot_index; + + lockdep_assert_held(&cluster->lock); + VM_WARN_ON(cluster->id !=3D VSWAP_VAL_CLUSTER_IDX(i)); + + slot_index =3D VSWAP_IDX_WITHIN_CLUSTER_VAL(i); + if (test_bit(slot_index, cluster->bitmap)) + return &cluster->descriptors[slot_index]; + + return NULL; +} + static struct swp_desc *vswap_iter(struct vswap_cluster **clusterp, unsign= ed long i) { unsigned long cluster_id =3D VSWAP_VAL_CLUSTER_IDX(i); @@ -448,7 +472,6 @@ void vswap_free(swp_entry_t entry, struct swap_cluster_= info *ci) if (!entry.val) return; =20 - swap_cache_clear_shadow(entry, 1); zswap_invalidate(entry); mem_cgroup_uncharge_swap(entry, 1); =20 @@ -460,6 +483,10 @@ void vswap_free(swp_entry_t entry, struct swap_cluster= _info *ci) return; } =20 + /* Clear shadow if present */ + if (xa_is_value(desc->shadow)) + desc->shadow =3D NULL; + if (desc->slot.val) vswap_rmap_set(ci, desc->slot, 0, 1); =20 @@ -480,7 +507,7 @@ int folio_alloc_swap(struct folio *folio) struct vswap_cluster *cluster =3D NULL; struct swap_info_struct *si; struct swap_cluster_info *ci; - int i, err, nr =3D folio_nr_pages(folio), order =3D folio_order(folio); + int i, nr =3D folio_nr_pages(folio), order =3D folio_order(folio); struct swp_desc *desc; swp_entry_t entry; swp_slot_t slot; @@ -533,9 +560,7 @@ int folio_alloc_swap(struct folio *folio) if (mem_cgroup_try_charge_swap(folio, entry)) goto out_free; =20 - err =3D swap_cache_add_folio(folio, entry, __GFP_HIGH | __GFP_NOMEMALLOC = | __GFP_NOWARN, NULL); - if (err) - goto out_free; + swap_cache_add_folio(folio, entry, NULL); =20 return 0; =20 @@ -668,6 +693,321 @@ static int vswap_cpu_dead(unsigned int cpu) return 0; } =20 +/** + * swap_cache_lock - lock the swap cache for a swap entry + * @entry: the swap entry + * + * Locks the vswap cluster spinlock for the given swap entry. + */ +void swap_cache_lock(swp_entry_t entry) +{ + struct vswap_cluster *cluster; + unsigned long cluster_id =3D VSWAP_CLUSTER_IDX(entry); + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + VM_WARN_ON(!cluster); + spin_lock(&cluster->lock); + rcu_read_unlock(); +} + +/** + * swap_cache_unlock - unlock the swap cache for a swap entry + * @entry: the swap entry + * + * Unlocks the vswap cluster spinlock for the given swap entry. + */ +void swap_cache_unlock(swp_entry_t entry) +{ + struct vswap_cluster *cluster; + unsigned long cluster_id =3D VSWAP_CLUSTER_IDX(entry); + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + VM_WARN_ON(!cluster); + spin_unlock(&cluster->lock); + rcu_read_unlock(); +} + +/** + * swap_cache_lock_irq - lock the swap cache with interrupts disabled + * @entry: the swap entry + * + * Locks the vswap cluster spinlock and disables interrupts for the given = swap entry. + */ +void swap_cache_lock_irq(swp_entry_t entry) +{ + struct vswap_cluster *cluster; + unsigned long cluster_id =3D VSWAP_CLUSTER_IDX(entry); + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + VM_WARN_ON(!cluster); + spin_lock_irq(&cluster->lock); + rcu_read_unlock(); +} + +/** + * swap_cache_unlock_irq - unlock the swap cache with interrupts enabled + * @entry: the swap entry + * + * Unlocks the vswap cluster spinlock and enables interrupts for the given= swap entry. + */ +void swap_cache_unlock_irq(swp_entry_t entry) +{ + struct vswap_cluster *cluster; + unsigned long cluster_id =3D VSWAP_CLUSTER_IDX(entry); + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + VM_WARN_ON(!cluster); + spin_unlock_irq(&cluster->lock); + rcu_read_unlock(); +} + +/** + * swap_cache_get_folio - Looks up a folio in the swap cache. + * @entry: swap entry used for the lookup. + * + * A found folio will be returned unlocked and with its refcount increased. + * + * Context: Caller must ensure @entry is valid and protect the cluster with + * reference count or locks. + * + * Return: Returns the found folio on success, NULL otherwise. The caller + * must lock and check if the folio still matches the swap entry before + * use (e.g., folio_matches_swap_entry). + */ +struct folio *swap_cache_get_folio(swp_entry_t entry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + struct folio *folio; + + for (;;) { + rcu_read_lock(); + desc =3D vswap_iter(&cluster, entry.val); + if (!desc) { + rcu_read_unlock(); + return NULL; + } + + /* Check if this is a shadow value (xa_is_value equivalent) */ + if (xa_is_value(desc->shadow)) { + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return NULL; + } + + folio =3D desc->swap_cache; + if (!folio) { + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return NULL; + } + + if (likely(folio_try_get(folio))) { + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return folio; + } + spin_unlock(&cluster->lock); + rcu_read_unlock(); + } + + return NULL; +} + +/** + * swap_cache_get_shadow - Looks up a shadow in the swap cache. + * @entry: swap entry used for the lookup. + * + * Context: Caller must ensure @entry is valid and protect the cluster with + * reference count or locks. + * + * Return: Returns either NULL or an XA_VALUE (shadow). + */ +void *swap_cache_get_shadow(swp_entry_t entry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + void *shadow; + + rcu_read_lock(); + desc =3D vswap_iter(&cluster, entry.val); + if (!desc) { + rcu_read_unlock(); + return NULL; + } + + shadow =3D desc->shadow; + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + if (xa_is_value(shadow)) + return shadow; + return NULL; +} + +/** + * swap_cache_add_folio - Add a folio into the swap cache. + * @folio: The folio to be added. + * @entry: The swap entry corresponding to the folio. + * @shadowp: If a shadow is found, return the shadow. + * + * Context: Caller must ensure @entry is valid and protect the cluster with + * reference count or locks. + * + * The caller also needs to update the corresponding swap_map slots with + * SWAP_HAS_CACHE bit to avoid race or conflict. + */ +void swap_cache_add_folio(struct folio *folio, swp_entry_t entry, void **s= hadowp) +{ + struct vswap_cluster *cluster; + unsigned long nr_pages =3D folio_nr_pages(folio); + unsigned long cluster_id =3D VSWAP_CLUSTER_IDX(entry); + unsigned long i; + struct swp_desc *desc; + void *old; + + VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); + VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio); + VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio); + + folio_ref_add(folio, nr_pages); + folio_set_swapcache(folio); + folio->swap =3D entry; + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + VM_WARN_ON(!cluster); + spin_lock_irq(&cluster->lock); + + for (i =3D 0; i < nr_pages; i++) { + desc =3D __vswap_iter(cluster, entry.val + i); + VM_WARN_ON(!desc); + old =3D desc->shadow; + + /* Warn if slot is already occupied by a folio */ + VM_WARN_ON_FOLIO(old && !xa_is_value(old), folio); + + /* Save shadow if found and not yet saved */ + if (shadowp && xa_is_value(old) && !*shadowp) + *shadowp =3D old; + + desc->swap_cache =3D folio; + } + + spin_unlock_irq(&cluster->lock); + rcu_read_unlock(); + + node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages); + lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages); +} + +/** + * __swap_cache_del_folio - Removes a folio from the swap cache. + * @folio: The folio. + * @entry: The first swap entry that the folio corresponds to. + * @shadow: shadow value to be filled in the swap cache. + * + * Removes a folio from the swap cache and fills a shadow in place. + * This won't put the folio's refcount. The caller has to do that. + * + * Context: Caller must ensure the folio is locked and in the swap cache + * using the index of @entry, and lock the swap cache. + */ +void __swap_cache_del_folio(struct folio *folio, swp_entry_t entry, void *= shadow) +{ + long nr_pages =3D folio_nr_pages(folio); + struct vswap_cluster *cluster; + struct swp_desc *desc; + unsigned long cluster_id =3D VSWAP_CLUSTER_IDX(entry); + int i; + + VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); + VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); + VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio); + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + VM_WARN_ON(!cluster); + + for (i =3D 0; i < nr_pages; i++) { + desc =3D __vswap_iter(cluster, entry.val + i); + VM_WARN_ON_FOLIO(!desc || desc->swap_cache !=3D folio, folio); + desc->shadow =3D shadow; + } + rcu_read_unlock(); + + folio->swap.val =3D 0; + folio_clear_swapcache(folio); + node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages); + lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages); +} + +/** + * swap_cache_del_folio - Removes a folio from the swap cache. + * @folio: The folio. + * + * Same as __swap_cache_del_folio, but handles lock and refcount. The + * caller must ensure the folio is either clean or has a swap count + * equal to zero, or it may cause data loss. + * + * Context: Caller must ensure the folio is locked and in the swap cache. + */ +void swap_cache_del_folio(struct folio *folio) +{ + swp_entry_t entry =3D folio->swap; + + swap_cache_lock_irq(entry); + __swap_cache_del_folio(folio, entry, NULL); + swap_cache_unlock_irq(entry); + + put_swap_folio(folio, entry); + folio_ref_sub(folio, folio_nr_pages(folio)); +} + +/** + * __swap_cache_replace_folio - Replace a folio in the swap cache. + * @old: The old folio to be replaced. + * @new: The new folio. + * + * Replace an existing folio in the swap cache with a new folio. The + * caller is responsible for setting up the new folio's flag and swap + * entries. Replacement will take the new folio's swap entry value as + * the starting offset to override all slots covered by the new folio. + * + * Context: Caller must ensure both folios are locked, and lock the + * swap cache. + */ +void __swap_cache_replace_folio(struct folio *old, struct folio *new) +{ + swp_entry_t entry =3D new->swap; + unsigned long nr_pages =3D folio_nr_pages(new); + struct vswap_cluster *cluster; + struct swp_desc *desc; + unsigned long cluster_id =3D VSWAP_CLUSTER_IDX(entry); + void *old_entry; + int i; + + VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new)); + VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new)); + VM_WARN_ON_ONCE(!entry.val); + + rcu_read_lock(); + cluster =3D xa_load(&vswap_cluster_map, cluster_id); + VM_WARN_ON(!cluster); + + for (i =3D 0; i < nr_pages; i++) { + desc =3D __vswap_iter(cluster, entry.val + i); + VM_WARN_ON(!desc); + old_entry =3D desc->swap_cache; + VM_WARN_ON(!old_entry || xa_is_value(old_entry) || old_entry !=3D old); + desc->swap_cache =3D new; + } + rcu_read_unlock(); +} =20 int vswap_init(void) { --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-ot1-f47.google.com (mail-ot1-f47.google.com [209.85.210.47]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0A9743624CF for ; Sun, 8 Feb 2026 21:59:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.47 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587945; cv=none; b=euHNvAOtPDtSNyI2v5lMgb/F3LauZL80+p8ONofKVfdpnZYcfYhj5Wb130lfbGIF4wH6LLfJePbE7qvkavXK8/c+U2LuWqniVmPnAuMyr28l2pkFCMV/XFd/cG6CrPmBaHca1enDDiwaPZAJJffkUqNH8B5ub9fP5mjbHZxAbUQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587945; c=relaxed/simple; bh=6RNDsiwA220Z2rFQxFzDnDxfVQ5PPyPpZSE3BQiIsfI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=P3oTWzzQT8eqFgUyYuMsD/w2m7+Um0l+pdPKr/qId4SCZ1MVe0HZm2p5An2pt9pvYEqspR/JiQACv5GeSfu0ZCqHvbQ1ww2nM2ksy2Vxxx0veJZ48ayBx6vCZS+Y8Ad25Lf9Xk72XuLGITCokVZjVfffVHgIynhtJhaD/UbvHw8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=g8iG3blA; arc=none smtp.client-ip=209.85.210.47 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.b="g8iG3blA" Received: by mail-ot1-f47.google.com with SMTP id 46e09a7af769-7d45d37c7a0so1532786a34.3 for ; Sun, 08 Feb 2026 13:59:04 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587944; x=1771192744; 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; bh=vwTpwkTCuWwHn2fL97emlDEhO4U5O+3cG0JKQCZZBaY=; b=g8iG3blAM2uB5QYSyUQPuoNFlNW3JKUDibmfS4bJ6jV4aF9htsWTXFfv9awoVgmjN8 nnHnxyJ67rz5tzBL1K6NFEQuJlmv0Hx5ejWysOM0CU304USpCDnyc5ystgV7VU4GJYHi hg++zwU3ptcy4JrhCb5V0oBYBeBdIEjA6iK7Gsvc6yCDCyiIBq9zO9WMv5aHylTrQxM/ 2M5+LibXTgC+53wxpmupn6wMFhqwSWZ/rD5+ZPSqYxBxUgBnC2bkxmPOlML4TmaKHbE3 LJg/rShF8W4RlF3FqjBhikqGyEoVTxZ5vSZ9aS9rH2fZOmrtfqMVMR6HZl4TinkfEtK6 ujEw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587944; x=1771192744; 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; bh=vwTpwkTCuWwHn2fL97emlDEhO4U5O+3cG0JKQCZZBaY=; b=d/8MGXNk/dAZXtLdS+bTyVCpzhYZD6E5v5I1ZwJqo0y71aVhSw1cX2zywEq0naBMZu kwmaregxbGP1Zo3ibGjGh6hofoZqiylBPX6FOCKtKo88Qdwgi7VLYvgGCkYG9U98ahd5 RViGZSI08ekvISHeufgswUFc7NZ4LTMwQqCCXbQ+lHD+s6YhgEiMRqH70YBJnXPFf4n6 HYi4J72GNEb2veYXoK/cjsVsELav0fVabG9O/iCqASgnDwRpjbbUt406dSGcNhquFeUr z/La24yUdnvALm5sTdN0JF/3LvtPKIZvfiaBn/g0QyHvsaLQ4tOPHwfCFyFwF2c7YSfK MxYw== X-Forwarded-Encrypted: i=1; AJvYcCXJkqfX1hBs6FmhXXHCiJdgr76FRD49K8uFxkQKS4X3IQMW77Ra/7Bqxv1MmgjQFeA2yudql/MQjjEW+Bo=@vger.kernel.org X-Gm-Message-State: AOJu0Yxjt9d6XSAwmpuQFI/9L22B2Bhn5kvydq+R3jdhCTXzridOFlNx 1ssYSSqtW5fACCzJDU9azzINpjlvbq6dygnyBS/iO5RPjj5B6VjhkMoD X-Gm-Gg: AZuq6aIzSpl6MmCE0blju/1fUzEImPoffoSwu8GR5UDgj4x/U0FEBQTQGVP1K2UONjH BqGQwGEij8MwgsTTWeIOzCgA9fJqEsXe0TfhwqAe0fTrCQHIp+9vfWEeqGtNWMVRaG9M6pfQxiz tjoKzkYS6xmqKwYCLqosq4s3Ns7I9WTbChptknlZRovpp5BuSaFCZhi6JAdFT9dkjlPvALo07Jf 2AxMEA4Xkc4chVXIGDDGU82QdWl2ss2tOeBdnhnEPltiiVQfJEDBmM2q5Le63SVsCW0lJvoSgCx yBfMCajS61duWZbGclfgfxH5OSpkDAfAeCk7WqBgE4LRz4I2J6PbXsBBNeb8KoonspYhWqJ+lnA 124D3/FblxR3BpxwzrLmM/PQWO+Y8bffGqCXkTZ27bliKpidzX/rwPf2XgZqFTNH/TtJxrlyDWf 2OsBVNDuUlDfObk8sGnginW/Gev5XqDEYDkw== X-Received: by 2002:a05:6830:3784:b0:7c7:266:392d with SMTP id 46e09a7af769-7d46440c217mr4795266a34.13.1770587943960; Sun, 08 Feb 2026 13:59:03 -0800 (PST) Received: from localhost ([2a03:2880:10ff:73::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d4647aa6cbsm6238339a34.26.2026.02.08.13.59.03 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:03 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 11/20] zswap: move zswap entry management to the virtual swap descriptor Date: Sun, 8 Feb 2026 13:58:24 -0800 Message-ID: <20260208215839.87595-12-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Remove the zswap tree and manage zswap entries directly through the virtual swap descriptor. This re-partitions the zswap pool (by virtual swap cluster), which eliminates zswap tree lock contention. Signed-off-by: Nhat Pham --- include/linux/zswap.h | 6 +++ mm/vswap.c | 100 ++++++++++++++++++++++++++++++++++++++++++ mm/zswap.c | 40 ----------------- 3 files changed, 106 insertions(+), 40 deletions(-) diff --git a/include/linux/zswap.h b/include/linux/zswap.h index 1a04caf283dc8..7eb3ce7e124fc 100644 --- a/include/linux/zswap.h +++ b/include/linux/zswap.h @@ -6,6 +6,7 @@ #include =20 struct lruvec; +struct zswap_entry; =20 extern atomic_long_t zswap_stored_pages; =20 @@ -33,6 +34,11 @@ void zswap_lruvec_state_init(struct lruvec *lruvec); void zswap_folio_swapin(struct folio *folio); bool zswap_is_enabled(void); bool zswap_never_enabled(void); +void *zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry); +void *zswap_entry_load(swp_entry_t swpentry); +void *zswap_entry_erase(swp_entry_t swpentry); +bool zswap_empty(swp_entry_t swpentry); + #else =20 struct zswap_lruvec_state {}; diff --git a/mm/vswap.c b/mm/vswap.c index d44199dc059a3..9bb733f00fd21 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -10,6 +10,7 @@ #include #include #include +#include #include "swap.h" #include "swap_table.h" =20 @@ -37,11 +38,13 @@ * Swap descriptor - metadata of a swapped out page. * * @slot: The handle to the physical swap slot backing this page. + * @zswap_entry: The zswap entry associated with this swap slot. * @swap_cache: The folio in swap cache. * @shadow: The shadow entry. */ struct swp_desc { swp_slot_t slot; + struct zswap_entry *zswap_entry; union { struct folio *swap_cache; void *shadow; @@ -238,6 +241,7 @@ static void __vswap_alloc_from_cluster(struct vswap_clu= ster *cluster, int start) for (i =3D 0; i < nr; i++) { desc =3D &cluster->descriptors[start + i]; desc->slot.val =3D 0; + desc->zswap_entry =3D NULL; } cluster->count +=3D nr; } @@ -1009,6 +1013,102 @@ void __swap_cache_replace_folio(struct folio *old, = struct folio *new) rcu_read_unlock(); } =20 +#ifdef CONFIG_ZSWAP +/** + * zswap_entry_store - store a zswap entry for a swap entry + * @swpentry: the swap entry + * @entry: the zswap entry to store + * + * Stores a zswap entry in the swap descriptor for the given swap entry. + * The cluster is locked during the store operation. + * + * Return: the old zswap entry if one existed, NULL otherwise + */ +void *zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + void *old; + + rcu_read_lock(); + desc =3D vswap_iter(&cluster, swpentry.val); + if (!desc) { + rcu_read_unlock(); + return NULL; + } + + old =3D desc->zswap_entry; + desc->zswap_entry =3D entry; + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + return old; +} + +/** + * zswap_entry_load - load a zswap entry for a swap entry + * @swpentry: the swap entry + * + * Loads the zswap entry from the swap descriptor for the given swap entry. + * + * Return: the zswap entry if one exists, NULL otherwise + */ +void *zswap_entry_load(swp_entry_t swpentry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + void *zswap_entry; + + rcu_read_lock(); + desc =3D vswap_iter(&cluster, swpentry.val); + if (!desc) { + rcu_read_unlock(); + return NULL; + } + + zswap_entry =3D desc->zswap_entry; + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + return zswap_entry; +} + +/** + * zswap_entry_erase - erase a zswap entry for a swap entry + * @swpentry: the swap entry + * + * Erases the zswap entry from the swap descriptor for the given swap entr= y. + * The cluster is locked during the erase operation. + * + * Return: the zswap entry that was erased, NULL if none existed + */ +void *zswap_entry_erase(swp_entry_t swpentry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + void *old; + + rcu_read_lock(); + desc =3D vswap_iter(&cluster, swpentry.val); + if (!desc) { + rcu_read_unlock(); + return NULL; + } + + old =3D desc->zswap_entry; + desc->zswap_entry =3D NULL; + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + return old; +} + +bool zswap_empty(swp_entry_t swpentry) +{ + return xa_empty(&vswap_cluster_map); +} +#endif /* CONFIG_ZSWAP */ + int vswap_init(void) { int i; diff --git a/mm/zswap.c b/mm/zswap.c index f7313261673ff..72441131f094e 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -223,37 +223,6 @@ static bool zswap_has_pool; * helpers and fwd declarations **********************************/ =20 -static DEFINE_XARRAY(zswap_tree); - -#define zswap_tree_index(entry) (entry.val) - -static inline void *zswap_entry_store(swp_entry_t swpentry, - struct zswap_entry *entry) -{ - pgoff_t offset =3D zswap_tree_index(swpentry); - - return xa_store(&zswap_tree, offset, entry, GFP_KERNEL); -} - -static inline void *zswap_entry_load(swp_entry_t swpentry) -{ - pgoff_t offset =3D zswap_tree_index(swpentry); - - return xa_load(&zswap_tree, offset); -} - -static inline void *zswap_entry_erase(swp_entry_t swpentry) -{ - pgoff_t offset =3D zswap_tree_index(swpentry); - - return xa_erase(&zswap_tree, offset); -} - -static inline bool zswap_empty(swp_entry_t swpentry) -{ - return xa_empty(&zswap_tree); -} - #define zswap_pool_debug(msg, p) \ pr_debug("%s pool %s\n", msg, (p)->tfm_name) =20 @@ -1445,13 +1414,6 @@ static bool zswap_store_page(struct page *page, goto compress_failed; =20 old =3D zswap_entry_store(page_swpentry, entry); - if (xa_is_err(old)) { - int err =3D xa_err(old); - - WARN_ONCE(err !=3D -ENOMEM, "unexpected xarray error: %d\n", err); - zswap_reject_alloc_fail++; - goto store_failed; - } =20 /* * We may have had an existing entry that became stale when @@ -1498,8 +1460,6 @@ static bool zswap_store_page(struct page *page, =20 return true; =20 -store_failed: - zs_free(pool->zs_pool, entry->handle); compress_failed: zswap_entry_cache_free(entry); return false; --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-ot1-f48.google.com (mail-ot1-f48.google.com [209.85.210.48]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F0EFE3644DA for ; Sun, 8 Feb 2026 21:59:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.48 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587948; cv=none; b=ZIGp/ceB4D5YOdUkhP7XHX/WBagHUUbYm3YCHVUao1kTsvovtEjmxs31+G1IQWvBatQStzrPvXz0PkQvc2tJO79WlkzG8Qddb6soILNAZPJt6WOMninpm1xjUeNNe5bFm11FgdVTxHO1lV70pal2EY0rHNj9M4j5JTP0Fu2B5kc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587948; c=relaxed/simple; bh=pyOt9cHGZeWhU9XUoVsThPyzTsvwfO6OGKo9BkcPdbA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=c5o47oBTs0q+sR+tcmMFk6vbVGM3FOBqzz0PCgz2Sg1FGBXDyNFfmR2wACd/j6LZ2EO0kVb3yS6HNmT9iVprh7pgJit/jk+4h23wRGL5NebwkxSNXuTpdEJaFY2wxBGVAXrIAxSha0hpJN3p9nQGK6fGozU09Ac++HCV72iJ+lU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=izhQG7A9; arc=none smtp.client-ip=209.85.210.48 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.b="izhQG7A9" Received: by mail-ot1-f48.google.com with SMTP id 46e09a7af769-7d1890f5cafso810663a34.1 for ; Sun, 08 Feb 2026 13:59:07 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587947; x=1771192747; 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; bh=e8bNI/GS1vV3CKrDoFoyeQFdwXdHl+beBAT/+JTFa9I=; b=izhQG7A9OvkAdcUORzA2M75SdmLMDN2NGTkribHOmDE5/bGTXsGC28qLR2pFjIbSO4 ByvBn3JrviQZWZRykV1wB8tB/gZhEWAFSDzq+59wbMPia75PpAr1uTHb7TdgCCukZ62I L98h3IWPtKa7DJ0fYg28vsHxU3DG1DSC3k1qkOVdial9WtLESPzpDWTykZ1IsDGpjH5F horO3rRHzSyQi892O5jCxPPmu3Hg4ZzqG8dy5Qe5o0DtJWkc6x9aeeiAlzzVq3hHt4s2 g+ku+3MFgmEptB4MH2xhTny9Nj5n6JxJZcF9RXBDHFxJ20VwFuf8M8AVoHgeSI+HzifD KLIw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587947; x=1771192747; 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; bh=e8bNI/GS1vV3CKrDoFoyeQFdwXdHl+beBAT/+JTFa9I=; b=dW0voohoc6wr9ypco6BxomPTK5lkgSajPi4c5CULb5s3p0Y2FCbiajJLSiBxdiovVe aQM4idIzu1XawgL1mcAScXXN24ml1xr8ywPyJVATqI1W9HRr5NgMG/Wk835/Uozm8bM7 ys3jKhLfnlD+1mNSvBO1VQfSAEg/F65woEp14Fspc8MJuIgGn6tpEssXqo2pXyS84ygA gm9akHsESyl57Hg6Nr6hpL9e4kBU2eawM+qKmotu9uSdZhr76Xk+/LMJoiSi+xh3AKSZ yQnYeISa8KyJpSjKDRIcEW19CCZP1BOzmLA3EoLI15egRAwICp9Po3njHtO1eqiW+AbR NnQg== X-Forwarded-Encrypted: i=1; AJvYcCUnGOuGnkeFfACcd/JM4Q56iJlU0JgOXCA1JgO5EV32yWqhfN0kzQJVAUQPeeBDP5TkQZX4Hh/CUbiB6g4=@vger.kernel.org X-Gm-Message-State: AOJu0Yz+PSnFPCS/7T4QozMUpnIySFWPcsTRsLvPLwcsRqpavwFswPkc IQK0YO3/Wi5cmLlvMc/OkoMRTpU1N4KV7wZMyDm3btdkj4rDpwf0GaWD X-Gm-Gg: AZuq6aLC5YYAFjijIXuY0f9Y7Z2j2ZirMRkJIOpuO/vNsIgm1pMm+vTULfVEBm/mQ8s sM4BbrhFZz5Kpph7GnKjOU5S41xhmulCI3qj+hVtUbID8AUFYkOaYczY2gD3ZyFyP8X+X71PC0c aDzZ5QTwPJlYBoyesZvPa4llQD3CXYzlkPyO2JtaOyz3yR03QvZLoWbaYFlOn9y7WwmBz3ULa+Z CpkQHJqjwzsVLocpLxO2eFT+hPyetb82p34mcNO6WygehH8jsyf4atNifNURlwg5WYqROt3W6we vpTToA8NcDaIKSDmehVhtEUNk8kExuxYf4IQQLyDJoO6RAIMpD23Jk1JqyXJ6g9GAk7FfyvCSPl y/pj1VbdFkAbxFtWDCMFhS3S7nAd96l28F3kBUcHmQ7r7nO8waAyzSknPVamyaA5DZpvf4ZWvjQ gdg5sE3UiwIUcV7bhyFvxuWRAJUmAGkomk5A== X-Received: by 2002:a05:6830:2b0e:b0:7cf:c485:be43 with SMTP id 46e09a7af769-7d4643e7eddmr5001314a34.7.1770587946806; Sun, 08 Feb 2026 13:59:06 -0800 (PST) Received: from localhost ([2a03:2880:10ff:48::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d46470da04sm6394135a34.7.2026.02.08.13.59.04 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:05 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 12/20] swap: implement the swap_cgroup API using virtual swap Date: Sun, 8 Feb 2026 13:58:25 -0800 Message-ID: <20260208215839.87595-13-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Once we decouple a swap entry from its backing store via the virtual swap, we can no longer statically allocate an array to store the swap entries' cgroup information. Move it to the swap descriptor. Note that the memory overhead for swap cgroup information is now on demand, i.e dynamically incurred when the virtual swap cluster is allocated. This help reduces the memory overhead in a huge but sparsely used swap space. For instance, a 2 TB swapfile consists of 2147483648 swap slots, each incurring 2 bytes of overhead for swap cgroup, for a total of 1 GB. If we only utilize 10% of the swapfile, we will save 900 MB. Signed-off-by: Nhat Pham --- include/linux/swap_cgroup.h | 13 --- mm/Makefile | 3 - mm/swap_cgroup.c | 174 ------------------------------------ mm/swapfile.c | 7 -- mm/vswap.c | 95 ++++++++++++++++++++ 5 files changed, 95 insertions(+), 197 deletions(-) delete mode 100644 mm/swap_cgroup.c diff --git a/include/linux/swap_cgroup.h b/include/linux/swap_cgroup.h index 91cdf12190a03..a2abb4d6fa085 100644 --- a/include/linux/swap_cgroup.h +++ b/include/linux/swap_cgroup.h @@ -9,8 +9,6 @@ extern void swap_cgroup_record(struct folio *folio, unsigned short id, swp= _entry_t ent); extern unsigned short swap_cgroup_clear(swp_entry_t ent, unsigned int nr_e= nts); extern unsigned short lookup_swap_cgroup_id(swp_entry_t ent); -extern int swap_cgroup_swapon(int type, unsigned long max_pages); -extern void swap_cgroup_swapoff(int type); =20 #else =20 @@ -31,17 +29,6 @@ unsigned short lookup_swap_cgroup_id(swp_entry_t ent) return 0; } =20 -static inline int -swap_cgroup_swapon(int type, unsigned long max_pages) -{ - return 0; -} - -static inline void swap_cgroup_swapoff(int type) -{ - return; -} - #endif =20 #endif /* __LINUX_SWAP_CGROUP_H */ diff --git a/mm/Makefile b/mm/Makefile index 67fa4586e7e18..a7538784191bf 100644 --- a/mm/Makefile +++ b/mm/Makefile @@ -103,9 +103,6 @@ obj-$(CONFIG_PAGE_COUNTER) +=3D page_counter.o obj-$(CONFIG_LIVEUPDATE) +=3D memfd_luo.o obj-$(CONFIG_MEMCG_V1) +=3D memcontrol-v1.o obj-$(CONFIG_MEMCG) +=3D memcontrol.o vmpressure.o -ifdef CONFIG_SWAP -obj-$(CONFIG_MEMCG) +=3D swap_cgroup.o -endif obj-$(CONFIG_CGROUP_HUGETLB) +=3D hugetlb_cgroup.o obj-$(CONFIG_GUP_TEST) +=3D gup_test.o obj-$(CONFIG_DMAPOOL_TEST) +=3D dmapool_test.o diff --git a/mm/swap_cgroup.c b/mm/swap_cgroup.c deleted file mode 100644 index 77ce1d66c318d..0000000000000 --- a/mm/swap_cgroup.c +++ /dev/null @@ -1,174 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -#include -#include -#include - -#include /* depends on mm.h include */ - -static DEFINE_MUTEX(swap_cgroup_mutex); - -/* Pack two cgroup id (short) of two entries in one swap_cgroup (atomic_t)= */ -#define ID_PER_SC (sizeof(struct swap_cgroup) / sizeof(unsigned short)) -#define ID_SHIFT (BITS_PER_TYPE(unsigned short)) -#define ID_MASK (BIT(ID_SHIFT) - 1) -struct swap_cgroup { - atomic_t ids; -}; - -struct swap_cgroup_ctrl { - struct swap_cgroup *map; -}; - -static struct swap_cgroup_ctrl swap_cgroup_ctrl[MAX_SWAPFILES]; - -static unsigned short __swap_cgroup_id_lookup(struct swap_cgroup *map, - pgoff_t offset) -{ - unsigned int shift =3D (offset % ID_PER_SC) * ID_SHIFT; - unsigned int old_ids =3D atomic_read(&map[offset / ID_PER_SC].ids); - - BUILD_BUG_ON(!is_power_of_2(ID_PER_SC)); - BUILD_BUG_ON(sizeof(struct swap_cgroup) !=3D sizeof(atomic_t)); - - return (old_ids >> shift) & ID_MASK; -} - -static unsigned short __swap_cgroup_id_xchg(struct swap_cgroup *map, - pgoff_t offset, - unsigned short new_id) -{ - unsigned short old_id; - struct swap_cgroup *sc =3D &map[offset / ID_PER_SC]; - unsigned int shift =3D (offset % ID_PER_SC) * ID_SHIFT; - unsigned int new_ids, old_ids =3D atomic_read(&sc->ids); - - do { - old_id =3D (old_ids >> shift) & ID_MASK; - new_ids =3D (old_ids & ~(ID_MASK << shift)); - new_ids |=3D ((unsigned int)new_id) << shift; - } while (!atomic_try_cmpxchg(&sc->ids, &old_ids, new_ids)); - - return old_id; -} - -/** - * swap_cgroup_record - record mem_cgroup for a set of swap entries. - * These entries must belong to one single folio, and that folio - * must be being charged for swap space (swap out), and these - * entries must not have been charged - * - * @folio: the folio that the swap entry belongs to - * @id: mem_cgroup ID to be recorded - * @ent: the first swap entry to be recorded - */ -void swap_cgroup_record(struct folio *folio, unsigned short id, - swp_entry_t ent) -{ - unsigned int nr_ents =3D folio_nr_pages(folio); - swp_slot_t slot =3D swp_entry_to_swp_slot(ent); - struct swap_cgroup *map; - pgoff_t offset, end; - unsigned short old; - - offset =3D swp_slot_offset(slot); - end =3D offset + nr_ents; - map =3D swap_cgroup_ctrl[swp_slot_type(slot)].map; - - do { - old =3D __swap_cgroup_id_xchg(map, offset, id); - VM_BUG_ON(old); - } while (++offset !=3D end); -} - -/** - * swap_cgroup_clear - clear mem_cgroup for a set of swap entries. - * These entries must be being uncharged from swap. They either - * belongs to one single folio in the swap cache (swap in for - * cgroup v1), or no longer have any users (slot freeing). - * - * @ent: the first swap entry to be recorded into - * @nr_ents: number of swap entries to be recorded - * - * Returns the existing old value. - */ -unsigned short swap_cgroup_clear(swp_entry_t ent, unsigned int nr_ents) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(ent); - pgoff_t offset =3D swp_slot_offset(slot); - pgoff_t end =3D offset + nr_ents; - struct swap_cgroup *map; - unsigned short old, iter =3D 0; - - map =3D swap_cgroup_ctrl[swp_slot_type(slot)].map; - - do { - old =3D __swap_cgroup_id_xchg(map, offset, 0); - if (!iter) - iter =3D old; - VM_BUG_ON(iter !=3D old); - } while (++offset !=3D end); - - return old; -} - -/** - * lookup_swap_cgroup_id - lookup mem_cgroup id tied to swap entry - * @ent: swap entry to be looked up. - * - * Returns ID of mem_cgroup at success. 0 at failure. (0 is invalid ID) - */ -unsigned short lookup_swap_cgroup_id(swp_entry_t ent) -{ - struct swap_cgroup_ctrl *ctrl; - swp_slot_t slot =3D swp_entry_to_swp_slot(ent); - - if (mem_cgroup_disabled()) - return 0; - - ctrl =3D &swap_cgroup_ctrl[swp_slot_type(slot)]; - return __swap_cgroup_id_lookup(ctrl->map, swp_slot_offset(slot)); -} - -int swap_cgroup_swapon(int type, unsigned long max_pages) -{ - struct swap_cgroup *map; - struct swap_cgroup_ctrl *ctrl; - - if (mem_cgroup_disabled()) - return 0; - - BUILD_BUG_ON(sizeof(unsigned short) * ID_PER_SC !=3D - sizeof(struct swap_cgroup)); - map =3D vzalloc(DIV_ROUND_UP(max_pages, ID_PER_SC) * - sizeof(struct swap_cgroup)); - if (!map) - goto nomem; - - ctrl =3D &swap_cgroup_ctrl[type]; - mutex_lock(&swap_cgroup_mutex); - ctrl->map =3D map; - mutex_unlock(&swap_cgroup_mutex); - - return 0; -nomem: - pr_info("couldn't allocate enough memory for swap_cgroup\n"); - pr_info("swap_cgroup can be disabled by swapaccount=3D0 boot option\n"); - return -ENOMEM; -} - -void swap_cgroup_swapoff(int type) -{ - struct swap_cgroup *map; - struct swap_cgroup_ctrl *ctrl; - - if (mem_cgroup_disabled()) - return; - - mutex_lock(&swap_cgroup_mutex); - ctrl =3D &swap_cgroup_ctrl[type]; - map =3D ctrl->map; - ctrl->map =3D NULL; - mutex_unlock(&swap_cgroup_mutex); - - vfree(map); -} diff --git a/mm/swapfile.c b/mm/swapfile.c index 68ec5d9f05848..345877786e432 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -2931,8 +2931,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) vfree(swap_map); kvfree(zeromap); free_cluster_info(cluster_info, maxpages); - /* Destroy swap account information */ - swap_cgroup_swapoff(p->type); =20 inode =3D mapping->host; =20 @@ -3497,10 +3495,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, special= file, int, swap_flags) goto bad_swap_unlock_inode; } =20 - error =3D swap_cgroup_swapon(si->type, maxpages); - if (error) - goto bad_swap_unlock_inode; - error =3D setup_swap_map(si, swap_header, swap_map, maxpages); if (error) goto bad_swap_unlock_inode; @@ -3605,7 +3599,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) si->global_cluster =3D NULL; inode =3D NULL; destroy_swap_extents(si); - swap_cgroup_swapoff(si->type); spin_lock(&swap_lock); si->swap_file =3D NULL; si->flags =3D 0; diff --git a/mm/vswap.c b/mm/vswap.c index 9bb733f00fd21..64747493ca9f7 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -41,6 +41,7 @@ * @zswap_entry: The zswap entry associated with this swap slot. * @swap_cache: The folio in swap cache. * @shadow: The shadow entry. + * @memcgid: The memcg id of the owning memcg, if any. */ struct swp_desc { swp_slot_t slot; @@ -49,6 +50,9 @@ struct swp_desc { struct folio *swap_cache; void *shadow; }; +#ifdef CONFIG_MEMCG + unsigned short memcgid; +#endif }; =20 #define VSWAP_CLUSTER_SHIFT HPAGE_PMD_ORDER @@ -242,6 +246,9 @@ static void __vswap_alloc_from_cluster(struct vswap_clu= ster *cluster, int start) desc =3D &cluster->descriptors[start + i]; desc->slot.val =3D 0; desc->zswap_entry =3D NULL; +#ifdef CONFIG_MEMCG + desc->memcgid =3D 0; +#endif } cluster->count +=3D nr; } @@ -1109,6 +1116,94 @@ bool zswap_empty(swp_entry_t swpentry) } #endif /* CONFIG_ZSWAP */ =20 +#ifdef CONFIG_MEMCG +static unsigned short vswap_cgroup_record(swp_entry_t entry, + unsigned short memcgid, unsigned int nr_ents) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + unsigned short oldid, iter =3D 0; + int i; + + rcu_read_lock(); + for (i =3D 0; i < nr_ents; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + VM_WARN_ON(!desc); + oldid =3D desc->memcgid; + desc->memcgid =3D memcgid; + if (!iter) + iter =3D oldid; + VM_WARN_ON(iter !=3D oldid); + } + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + return oldid; +} + +/** + * swap_cgroup_record - record mem_cgroup for a set of swap entries. + * These entries must belong to one single folio, and that folio + * must be being charged for swap space (swap out), and these + * entries must not have been charged + * + * @folio: the folio that the swap entry belongs to + * @memcgid: mem_cgroup ID to be recorded + * @entry: the first swap entry to be recorded + */ +void swap_cgroup_record(struct folio *folio, unsigned short memcgid, + swp_entry_t entry) +{ + unsigned short oldid =3D + vswap_cgroup_record(entry, memcgid, folio_nr_pages(folio)); + + VM_WARN_ON(oldid); +} + +/** + * swap_cgroup_clear - clear mem_cgroup for a set of swap entries. + * These entries must be being uncharged from swap. They either + * belongs to one single folio in the swap cache (swap in for + * cgroup v1), or no longer have any users (slot freeing). + * + * @entry: the first swap entry to be recorded into + * @nr_ents: number of swap entries to be recorded + * + * Returns the existing old value. + */ +unsigned short swap_cgroup_clear(swp_entry_t entry, unsigned int nr_ents) +{ + return vswap_cgroup_record(entry, 0, nr_ents); +} + +/** + * lookup_swap_cgroup_id - lookup mem_cgroup id tied to swap entry + * @entry: swap entry to be looked up. + * + * Returns ID of mem_cgroup at success. 0 at failure. (0 is invalid ID) + */ +unsigned short lookup_swap_cgroup_id(swp_entry_t entry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + unsigned short ret; + + /* + * Note that the virtual swap slot can be freed under us, for instance in + * the invocation of mem_cgroup_swapin_charge_folio. We need to wrap the + * entire lookup in RCU read-side critical section, and double check the + * existence of the swap descriptor. + */ + rcu_read_lock(); + desc =3D vswap_iter(&cluster, entry.val); + ret =3D desc ? desc->memcgid : 0; + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return ret; +} +#endif /* CONFIG_MEMCG */ + int vswap_init(void) { int i; --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oo1-f49.google.com (mail-oo1-f49.google.com [209.85.161.49]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 52FB035E54C for ; Sun, 8 Feb 2026 21:59:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.161.49 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587951; cv=none; b=ueu33juISy1+/MWlITBqstMTvhCnceeBE6MAy231S8xtxDqR1CtANIHWwcbCYsUfGDPTeUCSwWGyIubOwC5UuTlawosn6czJrQrJlCZuG2bnsqez7QIE9BmMy184tUfiXQjhtYoR65LjdBAIUNMjFZqc86tfPLFZpu3VFmIeNVo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587951; c=relaxed/simple; bh=iQleYa8UyD/yETNZGEhp1GGO+Wrw7D0qqMtgLIRDx6U=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=HpP6q987Te5WsHQFxrtcNr+gBv/zre0NMMbU2GJ4Drus+QTJbRlg16xwPTpC+D2Zd4suvvk9wEKf8ISSJQFcrWFaSdkI3g1nQ74hUJ92lniLvA6KpcdAW1WTd6aHP69OaziXh3d7e7uSd0cyWssoWqw3ELSN1NP3t2Iu4t4gVfc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=KRDCK8uP; arc=none smtp.client-ip=209.85.161.49 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.b="KRDCK8uP" Received: by mail-oo1-f49.google.com with SMTP id 006d021491bc7-66307e10d1dso2095926eaf.0 for ; Sun, 08 Feb 2026 13:59:11 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587950; x=1771192750; 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; bh=urnAkpKBtV9A23UEBLJ/2ALvkYqgV0wD8zPsi/hrDZs=; b=KRDCK8uPrxqfvf5QJlXSDL8wauStYBCLweKgflSWVraZSINPSqMA0Y7PIxaoisD1IM DlUOTGyqKKoW/GK+uH2aTwl175zrMY5N3TYsJE9mGMQZxe6v4Lfcg79oFgWIh8CWMGi0 V3zSz0DnXRE9xg5mrSAvYUt4FzmMvT3joTsr1OWdfV6efY2m/7mmSe1RYH6VB8EiSv8A ORJl56Ofac8q0auphOjl2oGXoRJKoaiK009c8TXTKCxGhzjjduDYQFeCVDKKUl3VH5SP P0v+y3G+rNtYynEKUTTDB1oV0jWn58QoEbQHQf9AHWenzDjjsQqMq/R6W1J5YFoMKHPR 3mBQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587950; x=1771192750; 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; bh=urnAkpKBtV9A23UEBLJ/2ALvkYqgV0wD8zPsi/hrDZs=; b=ZdFPciwyFvayYBWnfjUHxy/AovZ0oKD11Sk8VZzSeTtofYzC1sRVgI1n7xA6bdvp1p uZw/UfjzzQcH6Jjlb2t5pk9BHyw5RGhL5SB3i17KuX9X6eXXzapUK6OOwFUQSeWbsewH WkH03kOIBX2nOCDIrknVk3UUjvimduHE/YyLsJ/vFQraDh6oMR2vj00d3v7CcJNYiP7E tyeVz9K7SlNY5HuQpOcjEk+045qczDtmoP0ohMoLGkoZoMmd64oc1qrE+HpL3N/ACLWx RkBVh51rCnHFjSlad+K25L18Wil3SY707kSGSNd58F0cHO9Sd7Y4v729TOF9mNYbiRVA uu4w== X-Forwarded-Encrypted: i=1; AJvYcCXAYjJuC12c0llYM5XHknr2mZnhwAja/80VW19bk514SmT9EUhR2CFsKioVkDQtgx+kAlcrZBP3VzaSogc=@vger.kernel.org X-Gm-Message-State: AOJu0Yy9prhlNSbADM1A2IP9XfAu2zSRGJzdof8Yw2O8gCoLPtr7tAM7 5RBixU0km2gBJ+zB1belzFIv/phH5HimKPVbQEuUHTQ7WvYLwCHCpFq6 X-Gm-Gg: AZuq6aJ//Q62EFxDmOS5pIf5wVhSasnsvt8ROJSTW0f7gZsEO03JpiKUdhUVDR0ePOl AJZr4ifHVTHPPlVVvp32/sbgYqJkBXG1HfJ5q1DizGvWxCSRrE3a+HRjyzY69iqCBn1ybSWXXS9 L8LqDEeGU7jNCqrvwTaaV1M05GXhLe4FP8MhzlOr091N4sAjQBJpHVMs6pzXrCWFbuYy9KO5K5y cXL8OLHPIlzAQRQBuIw3a32+9TIgS6zb3t+dVbztbRc+dWeX4b2sQtOrYRQuV6BiN6myxquG0Mk KmVxLARa+/juoTCd4eFwR/FLKwMfe76Ztehgr+R/5dle1Ro1tE2WLv0sVQ8Ffw88iRKbN+RqoJz rF9LatWtUNdw1Y6A60hMWm0UNaFQOKgLxTJmyED57SKJE3JxSSiPXEjfzyzvkpSVZsYzGP5tOVM pCm17f3bQPInyLC+rt7zJa0OJ59h2IMhxzbRwNQCQpBgWD X-Received: by 2002:a05:6820:4a0c:b0:66e:4e57:d475 with SMTP id 006d021491bc7-66e4e671885mr1985520eaf.52.1770587949769; Sun, 08 Feb 2026 13:59:09 -0800 (PST) Received: from localhost ([2a03:2880:10ff:48::]) by smtp.gmail.com with ESMTPSA id 006d021491bc7-66fdf303607sm1910464eaf.14.2026.02.08.13.59.07 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:08 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 13/20] swap: manage swap entry lifecycle at the virtual swap layer Date: Sun, 8 Feb 2026 13:58:26 -0800 Message-ID: <20260208215839.87595-14-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This patch moves the swap entry lifecycle management to the virtual swap layer by adding to the swap descriptor two fields: 1. in_swapcache, i.e whether the swap entry is in swap cache (or about to be added). 2. The swap count of the swap entry, which counts the number of page table entries at which the swap entry is inserted. and re-implementing all of the swap entry lifecycle API (swap_duplicate(), swap_free_nr(), swapcache_prepare(), etc.) in the virtual swap layer. For now, we do not implement swap count continuation - the swap_count field in the swap descriptor is big enough to hold the maximum number of swap counts. This vastly simplifies the logic. Signed-off-by: Nhat Pham --- include/linux/swap.h | 29 +- include/linux/zswap.h | 5 +- mm/memory.c | 8 +- mm/shmem.c | 4 +- mm/swap.h | 58 ++-- mm/swap_state.c | 4 +- mm/swapfile.c | 786 ++---------------------------------------- mm/vswap.c | 452 ++++++++++++++++++++++-- mm/zswap.c | 14 +- 9 files changed, 502 insertions(+), 858 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 0410a00fd353c..aae2e502d9975 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -223,17 +223,9 @@ enum { #define SWAP_CLUSTER_MAX_SKIPPED (SWAP_CLUSTER_MAX << 10) #define COMPACT_CLUSTER_MAX SWAP_CLUSTER_MAX =20 -/* Bit flag in swap_map */ -#define SWAP_HAS_CACHE 0x40 /* Flag page is cached, in first swap_map */ -#define COUNT_CONTINUED 0x80 /* Flag swap_map continuation for full count = */ - -/* Special value in first swap_map */ -#define SWAP_MAP_MAX 0x3e /* Max count */ -#define SWAP_MAP_BAD 0x3f /* Note page is bad */ -#define SWAP_MAP_SHMEM 0xbf /* Owned by shmem/tmpfs */ - -/* Special value in each swap_map continuation */ -#define SWAP_CONT_MAX 0x7f /* Max count */ +/* Swapfile's swap map state*/ +#define SWAP_MAP_ALLOCATED 0x01 /* Page is allocated */ +#define SWAP_MAP_BAD 0x02 /* Page is bad */ =20 /* * The first page in the swap file is the swap header, which is always mar= ked @@ -423,7 +415,7 @@ extern void __meminit kswapd_stop(int nid); =20 #ifdef CONFIG_SWAP =20 -/* Lifecycle swap API (mm/swapfile.c) */ +/* Lifecycle swap API (mm/swapfile.c and mm/vswap.c) */ int folio_alloc_swap(struct folio *folio); bool folio_free_swap(struct folio *folio); void put_swap_folio(struct folio *folio, swp_entry_t entry); @@ -433,7 +425,7 @@ int swapcache_prepare(swp_entry_t entry, int nr); void swap_free_nr(swp_entry_t entry, int nr_pages); void free_swap_and_cache_nr(swp_entry_t entry, int nr); int __swap_count(swp_entry_t entry); -bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry); +bool swap_entry_swapped(swp_entry_t entry); int swp_swapcount(swp_entry_t entry); bool is_swap_cached(swp_entry_t entry); =20 @@ -473,7 +465,6 @@ static inline long get_nr_swap_pages(void) void si_swapinfo(struct sysinfo *); int swap_slot_alloc(swp_slot_t *slot, unsigned int order); swp_slot_t swap_slot_alloc_of_type(int); -int add_swap_count_continuation(swp_entry_t, gfp_t); int swap_type_of(dev_t device, sector_t offset); int find_first_swap(dev_t *device); unsigned int count_swap_pages(int, int); @@ -517,11 +508,6 @@ static inline void free_swap_cache(struct folio *folio) { } =20 -static inline int add_swap_count_continuation(swp_entry_t swp, gfp_t gfp_m= ask) -{ - return 0; -} - static inline void swap_shmem_alloc(swp_entry_t swp, int nr) { } @@ -549,7 +535,7 @@ static inline int __swap_count(swp_entry_t entry) return 0; } =20 -static inline bool swap_entry_swapped(struct swap_info_struct *si, swp_ent= ry_t entry) +static inline bool swap_entry_swapped(swp_entry_t entry) { return false; } @@ -672,11 +658,12 @@ static inline bool mem_cgroup_swap_full(struct folio = *folio) =20 int vswap_init(void); void vswap_exit(void); -void vswap_free(swp_entry_t entry, struct swap_cluster_info *ci); swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry); swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot); bool tryget_swap_entry(swp_entry_t entry, struct swap_info_struct **si); void put_swap_entry(swp_entry_t entry, struct swap_info_struct *si); +bool folio_swapped(struct folio *folio); +bool vswap_only_has_cache(swp_entry_t entry, int nr); =20 #endif /* __KERNEL__*/ #endif /* _LINUX_SWAP_H */ diff --git a/include/linux/zswap.h b/include/linux/zswap.h index 7eb3ce7e124fc..07b2936c38f29 100644 --- a/include/linux/zswap.h +++ b/include/linux/zswap.h @@ -28,7 +28,6 @@ struct zswap_lruvec_state { unsigned long zswap_total_pages(void); bool zswap_store(struct folio *folio); int zswap_load(struct folio *folio); -void zswap_invalidate(swp_entry_t swp); void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg); void zswap_lruvec_state_init(struct lruvec *lruvec); void zswap_folio_swapin(struct folio *folio); @@ -38,6 +37,7 @@ void *zswap_entry_store(swp_entry_t swpentry, struct zswa= p_entry *entry); void *zswap_entry_load(swp_entry_t swpentry); void *zswap_entry_erase(swp_entry_t swpentry); bool zswap_empty(swp_entry_t swpentry); +void zswap_entry_free(struct zswap_entry *entry); =20 #else =20 @@ -53,7 +53,6 @@ static inline int zswap_load(struct folio *folio) return -ENOENT; } =20 -static inline void zswap_invalidate(swp_entry_t swp) {} static inline void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg) {} static inline void zswap_lruvec_state_init(struct lruvec *lruvec) {} static inline void zswap_folio_swapin(struct folio *folio) {} @@ -68,6 +67,8 @@ static inline bool zswap_never_enabled(void) return true; } =20 +static inline void zswap_entry_free(struct zswap_entry *entry) {} + #endif =20 #endif /* _LINUX_ZSWAP_H */ diff --git a/mm/memory.c b/mm/memory.c index 90031f833f52e..641e3f65edc00 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -1333,10 +1333,6 @@ copy_pte_range(struct vm_area_struct *dst_vma, struc= t vm_area_struct *src_vma, =20 if (ret =3D=3D -EIO) { VM_WARN_ON_ONCE(!entry.val); - if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) { - ret =3D -ENOMEM; - goto out; - } entry.val =3D 0; } else if (ret =3D=3D -EBUSY || unlikely(ret =3D=3D -EHWPOISON)) { goto out; @@ -5044,7 +5040,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) out: /* Clear the swap cache pin for direct swapin after PTL unlock */ if (need_clear_cache) { - swapcache_clear(si, entry, nr_pages); + swapcache_clear(entry, nr_pages); if (waitqueue_active(&swapcache_wq)) wake_up(&swapcache_wq); } @@ -5063,7 +5059,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) folio_put(swapcache); } if (need_clear_cache) { - swapcache_clear(si, entry, nr_pages); + swapcache_clear(entry, nr_pages); if (waitqueue_active(&swapcache_wq)) wake_up(&swapcache_wq); } diff --git a/mm/shmem.c b/mm/shmem.c index 66cf8af6779ca..780571c830e5b 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2442,7 +2442,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, =20 if (skip_swapcache) { folio->swap.val =3D 0; - swapcache_clear(si, swap, nr_pages); + swapcache_clear(swap, nr_pages); } else { swap_cache_del_folio(folio); } @@ -2463,7 +2463,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, folio_unlock(folio); failed_nolock: if (skip_swapcache) - swapcache_clear(si, folio->swap, folio_nr_pages(folio)); + swapcache_clear(folio->swap, folio_nr_pages(folio)); if (folio) folio_put(folio); put_swap_entry(swap, si); diff --git a/mm/swap.h b/mm/swap.h index 57ed24a2d6356..ae97cf9712c5c 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -211,6 +211,8 @@ void swap_cache_lock_irq(swp_entry_t entry); void swap_cache_unlock_irq(swp_entry_t entry); void swap_cache_lock(swp_entry_t entry); void swap_cache_unlock(swp_entry_t entry); +void vswap_rmap_set(struct swap_cluster_info *ci, swp_slot_t slot, + unsigned long vswap, int nr); =20 static inline struct address_space *swap_address_space(swp_entry_t entry) { @@ -245,6 +247,31 @@ static inline bool folio_matches_swap_entry(const stru= ct folio *folio, return folio_entry.val =3D=3D round_down(entry.val, nr_pages); } =20 +/** + * folio_matches_swap_slot - Check if a folio matches both the virtual + * swap entry and its backing physical swap slot. + * @folio: The folio. + * @entry: The virtual swap entry to check against. + * @slot: The physical swap slot to check against. + * + * Context: The caller should have the folio locked to ensure it's stable + * and nothing will move it in or out of the swap cache. + * Return: true if both checks pass, false otherwise. + */ +static inline bool folio_matches_swap_slot(const struct folio *folio, + swp_entry_t entry, + swp_slot_t slot) +{ + if (!folio_matches_swap_entry(folio, entry)) + return false; + + /* + * Confirm the virtual swap entry is still backed by the same + * physical swap slot. + */ + return slot.val =3D=3D swp_entry_to_swp_slot(entry).val; +} + /* * All swap cache helpers below require the caller to ensure the swap entr= ies * used are valid and stablize the device by any of the following ways: @@ -265,7 +292,7 @@ void __swap_cache_del_folio(struct folio *folio, swp_en= try_t entry, void *shadow void __swap_cache_replace_folio(struct folio *old, struct folio *new); =20 void show_swap_cache_info(void); -void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int n= r); +void swapcache_clear(swp_entry_t entry, int nr); struct folio *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask, struct vm_area_struct *vma, unsigned long addr, struct swap_iocb **plug); @@ -312,25 +339,7 @@ static inline int swap_zeromap_batch(swp_entry_t entry= , int max_nr, return find_next_bit(sis->zeromap, end, start) - start; } =20 -static inline int non_swapcache_batch(swp_entry_t entry, int max_nr) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *si =3D __swap_slot_to_info(slot); - pgoff_t offset =3D swp_slot_offset(slot); - int i; - - /* - * While allocating a large folio and doing mTHP swapin, we need to - * ensure all entries are not cached, otherwise, the mTHP folio will - * be in conflict with the folio in swap cache. - */ - for (i =3D 0; i < max_nr; i++) { - if ((si->swap_map[offset + i] & SWAP_HAS_CACHE)) - return i; - } - - return i; -} +int non_swapcache_batch(swp_entry_t entry, int max_nr); =20 #else /* CONFIG_SWAP */ struct swap_iocb; @@ -382,6 +391,13 @@ static inline bool folio_matches_swap_entry(const stru= ct folio *folio, swp_entry return false; } =20 +static inline bool folio_matches_swap_slot(const struct folio *folio, + swp_entry_t entry, + swp_slot_t slot) +{ + return false; +} + static inline void show_swap_cache_info(void) { } @@ -409,7 +425,7 @@ static inline int swap_writeout(struct folio *folio, return 0; } =20 -static inline void swapcache_clear(struct swap_info_struct *si, swp_entry_= t entry, int nr) +static inline void swapcache_clear(swp_entry_t entry, int nr) { } =20 diff --git a/mm/swap_state.c b/mm/swap_state.c index 00fa3e76a5c19..1827527e88d33 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -174,8 +174,6 @@ struct folio *__read_swap_cache_async(swp_entry_t entry= , gfp_t gfp_mask, struct mempolicy *mpol, pgoff_t ilx, bool *new_page_allocated, bool skip_if_exists) { - struct swap_info_struct *si =3D - __swap_slot_to_info(swp_entry_to_swp_slot(entry)); struct folio *folio; struct folio *new_folio =3D NULL; struct folio *result =3D NULL; @@ -196,7 +194,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry= , gfp_t gfp_mask, /* * Just skip read ahead for unused swap slot. */ - if (!swap_entry_swapped(si, entry)) + if (!swap_entry_swapped(entry)) goto put_and_return; =20 /* diff --git a/mm/swapfile.c b/mm/swapfile.c index 345877786e432..6c5e46bf40701 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -50,9 +50,6 @@ #include "internal.h" #include "swap.h" =20 -static bool swap_count_continued(struct swap_info_struct *, pgoff_t, - unsigned char); -static void free_swap_count_continuations(struct swap_info_struct *); static void swap_slots_free(struct swap_info_struct *si, struct swap_cluster_info *ci, swp_slot_t slot, unsigned int nr_pages); @@ -146,7 +143,7 @@ static struct swap_info_struct *swap_slot_to_info(swp_s= lot_t slot) =20 static inline unsigned char swap_count(unsigned char ent) { - return ent & ~SWAP_HAS_CACHE; /* may include COUNT_CONTINUED flag */ + return ent; } =20 /* @@ -182,52 +179,14 @@ static long swap_usage_in_pages(struct swap_info_stru= ct *si) static bool swap_only_has_cache(struct swap_info_struct *si, unsigned long offset, int nr_pages) { - unsigned char *map =3D si->swap_map + offset; - unsigned char *map_end =3D map + nr_pages; - - do { - VM_BUG_ON(!(*map & SWAP_HAS_CACHE)); - if (*map !=3D SWAP_HAS_CACHE) - return false; - } while (++map < map_end); + swp_entry_t entry =3D swp_slot_to_swp_entry(swp_slot(si->type, offset)); =20 - return true; + return vswap_only_has_cache(entry, nr_pages); } =20 -/** - * is_swap_cached - check if the swap entry is cached - * @entry: swap entry to check - * - * Check swap_map directly to minimize overhead, READ_ONCE is sufficient. - * - * Returns true if the swap entry is cached, false otherwise. - */ -bool is_swap_cached(swp_entry_t entry) +static bool swap_cache_only(struct swap_info_struct *si, unsigned long off= set) { - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *si =3D swap_slot_to_info(slot); - unsigned long offset =3D swp_slot_offset(slot); - - return READ_ONCE(si->swap_map[offset]) & SWAP_HAS_CACHE; -} - -static bool swap_is_last_map(struct swap_info_struct *si, - unsigned long offset, int nr_pages, bool *has_cache) -{ - unsigned char *map =3D si->swap_map + offset; - unsigned char *map_end =3D map + nr_pages; - unsigned char count =3D *map; - - if (swap_count(count) !=3D 1 && swap_count(count) !=3D SWAP_MAP_SHMEM) - return false; - - while (++map < map_end) { - if (*map !=3D count) - return false; - } - - *has_cache =3D !!(count & SWAP_HAS_CACHE); - return true; + return swap_only_has_cache(si, offset, 1); } =20 /* @@ -238,15 +197,15 @@ static bool swap_is_last_map(struct swap_info_struct = *si, static int __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset, unsigned long flags) { - const swp_entry_t entry =3D - swp_slot_to_swp_entry(swp_slot(si->type, offset)); - swp_slot_t slot; + const swp_slot_t slot =3D swp_slot(si->type, offset); + swp_entry_t entry; struct swap_cluster_info *ci; struct folio *folio; int ret, nr_pages; bool need_reclaim; =20 again: + entry =3D swp_slot_to_swp_entry(slot); folio =3D swap_cache_get_folio(entry); if (!folio) return 0; @@ -266,14 +225,15 @@ static int __try_to_reclaim_swap(struct swap_info_str= uct *si, /* * Offset could point to the middle of a large folio, or folio * may no longer point to the expected offset before it's locked. + * Additionally, the virtual swap entry may no longer be backed + * by the same physical swap slot. */ - if (!folio_matches_swap_entry(folio, entry)) { + if (!folio_matches_swap_slot(folio, entry, slot)) { folio_unlock(folio); folio_put(folio); goto again; } - slot =3D swp_entry_to_swp_slot(folio->swap); - offset =3D swp_slot_offset(slot); + offset =3D swp_slot_offset(swp_entry_to_swp_slot(folio->swap)); =20 need_reclaim =3D ((flags & TTRS_ANYWAY) || ((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) || @@ -283,8 +243,7 @@ static int __try_to_reclaim_swap(struct swap_info_struc= t *si, =20 /* * It's safe to delete the folio from swap cache only if the folio's - * swap_map is HAS_CACHE only, which means the slots have no page table - * reference or pending writeback, and can't be allocated to others. + * swap slots have no page table reference or pending writeback. */ ci =3D swap_cluster_lock(si, offset); need_reclaim =3D swap_only_has_cache(si, offset, nr_pages); @@ -811,7 +770,7 @@ static bool cluster_reclaim_range(struct swap_info_stru= ct *si, case 0: offset++; break; - case SWAP_HAS_CACHE: + case SWAP_MAP_ALLOCATED: nr_reclaim =3D __try_to_reclaim_swap(si, offset, TTRS_ANYWAY); if (nr_reclaim > 0) offset +=3D nr_reclaim; @@ -842,22 +801,23 @@ static bool cluster_scan_range(struct swap_info_struc= t *si, { unsigned long offset, end =3D start + nr_pages; unsigned char *map =3D si->swap_map; + unsigned char count; =20 if (cluster_is_empty(ci)) return true; =20 for (offset =3D start; offset < end; offset++) { - switch (READ_ONCE(map[offset])) { - case 0: + count =3D READ_ONCE(map[offset]); + if (!count) continue; - case SWAP_HAS_CACHE: + + if (swap_cache_only(si, offset)) { if (!vm_swap_full()) return false; *need_reclaim =3D true; continue; - default: - return false; } + return false; } =20 return true; @@ -974,7 +934,6 @@ static void swap_reclaim_full_clusters(struct swap_info= _struct *si, bool force) long to_scan =3D 1; unsigned long offset, end; struct swap_cluster_info *ci; - unsigned char *map =3D si->swap_map; int nr_reclaim; =20 if (force) @@ -986,7 +945,7 @@ static void swap_reclaim_full_clusters(struct swap_info= _struct *si, bool force) to_scan--; =20 while (offset < end) { - if (READ_ONCE(map[offset]) =3D=3D SWAP_HAS_CACHE) { + if (swap_cache_only(si, offset)) { spin_unlock(&ci->lock); nr_reclaim =3D __try_to_reclaim_swap(si, offset, TTRS_ANYWAY); @@ -1320,7 +1279,8 @@ static bool swap_alloc_fast(swp_slot_t *slot, int ord= er) if (cluster_is_usable(ci, order)) { if (cluster_is_empty(ci)) offset =3D cluster_offset(si, ci); - found =3D alloc_swap_scan_cluster(si, ci, offset, order, SWAP_HAS_CACHE); + found =3D alloc_swap_scan_cluster(si, ci, offset, order, + SWAP_MAP_ALLOCATED); if (found) *slot =3D swp_slot(si->type, found); } else { @@ -1344,7 +1304,7 @@ static void swap_alloc_slow(swp_slot_t *slot, int ord= er) plist_requeue(&si->avail_list, &swap_avail_head); spin_unlock(&swap_avail_lock); if (get_swap_device_info(si)) { - offset =3D cluster_alloc_swap_slot(si, order, SWAP_HAS_CACHE); + offset =3D cluster_alloc_swap_slot(si, order, SWAP_MAP_ALLOCATED); swap_slot_put_swap_info(si); if (offset) { *slot =3D swp_slot(si->type, offset); @@ -1471,48 +1431,6 @@ static struct swap_info_struct *_swap_info_get(swp_s= lot_t slot) return NULL; } =20 -static unsigned char swap_slot_put_locked(struct swap_info_struct *si, - struct swap_cluster_info *ci, - swp_slot_t slot, - unsigned char usage) -{ - unsigned long offset =3D swp_slot_offset(slot); - unsigned char count; - unsigned char has_cache; - - count =3D si->swap_map[offset]; - - has_cache =3D count & SWAP_HAS_CACHE; - count &=3D ~SWAP_HAS_CACHE; - - if (usage =3D=3D SWAP_HAS_CACHE) { - VM_BUG_ON(!has_cache); - has_cache =3D 0; - } else if (count =3D=3D SWAP_MAP_SHMEM) { - /* - * Or we could insist on shmem.c using a special - * swap_shmem_free() and free_shmem_swap_and_cache()... - */ - count =3D 0; - } else if ((count & ~COUNT_CONTINUED) <=3D SWAP_MAP_MAX) { - if (count =3D=3D COUNT_CONTINUED) { - if (swap_count_continued(si, offset, count)) - count =3D SWAP_MAP_MAX | COUNT_CONTINUED; - else - count =3D SWAP_MAP_MAX; - } else - count--; - } - - usage =3D count | has_cache; - if (usage) - WRITE_ONCE(si->swap_map[offset], usage); - else - swap_slots_free(si, ci, slot, 1); - - return usage; -} - /* * When we get a swap entry, if there aren't some other ways to * prevent swapoff, such as the folio in swap cache is locked, RCU @@ -1580,94 +1498,23 @@ struct swap_info_struct *swap_slot_tryget_swap_info= (swp_slot_t slot) return NULL; } =20 -static void swap_slots_put_cache(struct swap_info_struct *si, - swp_slot_t slot, int nr) -{ - unsigned long offset =3D swp_slot_offset(slot); - struct swap_cluster_info *ci; - - ci =3D swap_cluster_lock(si, offset); - if (swap_only_has_cache(si, offset, nr)) { - swap_slots_free(si, ci, slot, nr); - } else { - for (int i =3D 0; i < nr; i++, slot.val++) - swap_slot_put_locked(si, ci, slot, SWAP_HAS_CACHE); - } - swap_cluster_unlock(ci); -} - static bool swap_slots_put_map(struct swap_info_struct *si, swp_slot_t slot, int nr) { unsigned long offset =3D swp_slot_offset(slot); struct swap_cluster_info *ci; - bool has_cache =3D false; - unsigned char count; - int i; - - if (nr <=3D 1) - goto fallback; - count =3D swap_count(data_race(si->swap_map[offset])); - if (count !=3D 1 && count !=3D SWAP_MAP_SHMEM) - goto fallback; =20 ci =3D swap_cluster_lock(si, offset); - if (!swap_is_last_map(si, offset, nr, &has_cache)) { - goto locked_fallback; - } - if (!has_cache) - swap_slots_free(si, ci, slot, nr); - else - for (i =3D 0; i < nr; i++) - WRITE_ONCE(si->swap_map[offset + i], SWAP_HAS_CACHE); + vswap_rmap_set(ci, slot, 0, nr); + swap_slots_free(si, ci, slot, nr); swap_cluster_unlock(ci); =20 - return has_cache; - -fallback: - ci =3D swap_cluster_lock(si, offset); -locked_fallback: - for (i =3D 0; i < nr; i++, slot.val++) { - count =3D swap_slot_put_locked(si, ci, slot, 1); - if (count =3D=3D SWAP_HAS_CACHE) - has_cache =3D true; - } - swap_cluster_unlock(ci); - return has_cache; -} - -/* - * Only functions with "_nr" suffix are able to free entries spanning - * cross multi clusters, so ensure the range is within a single cluster - * when freeing entries with functions without "_nr" suffix. - */ -static bool swap_slots_put_map_nr(struct swap_info_struct *si, - swp_slot_t slot, int nr) -{ - int cluster_nr, cluster_rest; - unsigned long offset =3D swp_slot_offset(slot); - bool has_cache =3D false; - - cluster_rest =3D SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER; - while (nr) { - cluster_nr =3D min(nr, cluster_rest); - has_cache |=3D swap_slots_put_map(si, slot, cluster_nr); - cluster_rest =3D SWAPFILE_CLUSTER; - nr -=3D cluster_nr; - slot.val +=3D cluster_nr; - } - - return has_cache; + return true; } =20 -/* - * Check if it's the last ref of swap entry in the freeing path. - * Qualified value includes 1, SWAP_HAS_CACHE or SWAP_MAP_SHMEM. - */ static inline bool __maybe_unused swap_is_last_ref(unsigned char count) { - return (count =3D=3D SWAP_HAS_CACHE) || (count =3D=3D 1) || - (count =3D=3D SWAP_MAP_SHMEM); + return count =3D=3D SWAP_MAP_ALLOCATED; } =20 /* @@ -1681,14 +1528,6 @@ static void swap_slots_free(struct swap_info_struct = *si, unsigned long offset =3D swp_slot_offset(slot); unsigned char *map =3D si->swap_map + offset; unsigned char *map_end =3D map + nr_pages; - swp_entry_t entry =3D swp_slot_to_swp_entry(slot); - int i; - - /* release all the associated (virtual) swap slots */ - for (i =3D 0; i < nr_pages; i++) { - vswap_free(entry, ci); - entry.val++; - } =20 /* It should never free entries across different clusters */ VM_BUG_ON(ci !=3D __swap_offset_to_cluster(si, offset + nr_pages - 1)); @@ -1731,149 +1570,6 @@ void swap_slot_free_nr(swp_slot_t slot, int nr_page= s) } } =20 -/* - * Caller has made sure that the swap device corresponding to entry - * is still around or has not been recycled. - */ -void swap_free_nr(swp_entry_t entry, int nr_pages) -{ - swap_slot_free_nr(swp_entry_to_swp_slot(entry), nr_pages); -} - -/* - * Called after dropping swapcache to decrease refcnt to swap entries. - */ -void put_swap_folio(struct folio *folio, swp_entry_t entry) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *si; - int size =3D 1 << swap_slot_order(folio_order(folio)); - - si =3D _swap_info_get(slot); - if (!si) - return; - - swap_slots_put_cache(si, slot, size); -} - -int __swap_count(swp_entry_t entry) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *si =3D __swap_slot_to_info(slot); - pgoff_t offset =3D swp_slot_offset(slot); - - return swap_count(si->swap_map[offset]); -} - -/* - * How many references to @entry are currently swapped out? - * This does not give an exact answer when swap count is continued, - * but does include the high COUNT_CONTINUED flag to allow for that. - */ -bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - pgoff_t offset =3D swp_slot_offset(slot); - struct swap_cluster_info *ci; - int count; - - ci =3D swap_cluster_lock(si, offset); - count =3D swap_count(si->swap_map[offset]); - swap_cluster_unlock(ci); - return !!count; -} - -/* - * How many references to @entry are currently swapped out? - * This considers COUNT_CONTINUED so it returns exact answer. - */ -int swp_swapcount(swp_entry_t entry) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - int count, tmp_count, n; - struct swap_info_struct *si; - struct swap_cluster_info *ci; - struct page *page; - pgoff_t offset; - unsigned char *map; - - si =3D _swap_info_get(slot); - if (!si) - return 0; - - offset =3D swp_slot_offset(slot); - - ci =3D swap_cluster_lock(si, offset); - - count =3D swap_count(si->swap_map[offset]); - if (!(count & COUNT_CONTINUED)) - goto out; - - count &=3D ~COUNT_CONTINUED; - n =3D SWAP_MAP_MAX + 1; - - page =3D vmalloc_to_page(si->swap_map + offset); - offset &=3D ~PAGE_MASK; - VM_BUG_ON(page_private(page) !=3D SWP_CONTINUED); - - do { - page =3D list_next_entry(page, lru); - map =3D kmap_local_page(page); - tmp_count =3D map[offset]; - kunmap_local(map); - - count +=3D (tmp_count & ~COUNT_CONTINUED) * n; - n *=3D (SWAP_CONT_MAX + 1); - } while (tmp_count & COUNT_CONTINUED); -out: - swap_cluster_unlock(ci); - return count; -} - -static bool swap_page_trans_huge_swapped(struct swap_info_struct *si, - swp_entry_t entry, int order) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_cluster_info *ci; - unsigned char *map =3D si->swap_map; - unsigned int nr_pages =3D 1 << order; - unsigned long roffset =3D swp_slot_offset(slot); - unsigned long offset =3D round_down(roffset, nr_pages); - int i; - bool ret =3D false; - - ci =3D swap_cluster_lock(si, offset); - if (nr_pages =3D=3D 1) { - if (swap_count(map[roffset])) - ret =3D true; - goto unlock_out; - } - for (i =3D 0; i < nr_pages; i++) { - if (swap_count(map[offset + i])) { - ret =3D true; - break; - } - } -unlock_out: - swap_cluster_unlock(ci); - return ret; -} - -static bool folio_swapped(struct folio *folio) -{ - swp_entry_t entry =3D folio->swap; - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *si =3D _swap_info_get(slot); - - if (!si) - return false; - - if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!folio_test_large(folio))) - return swap_entry_swapped(si, entry); - - return swap_page_trans_huge_swapped(si, entry, folio_order(folio)); -} - static bool folio_swapcache_freeable(struct folio *folio) { VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); @@ -1925,72 +1621,6 @@ bool folio_free_swap(struct folio *folio) return true; } =20 -/** - * free_swap_and_cache_nr() - Release reference on range of swap entries a= nd - * reclaim their cache if no more references re= main. - * @entry: First entry of range. - * @nr: Number of entries in range. - * - * For each swap entry in the contiguous range, release a reference. If an= y swap - * entries become free, try to reclaim their underlying folios, if present= . The - * offset range is defined by [entry.offset, entry.offset + nr). - */ -void free_swap_and_cache_nr(swp_entry_t entry, int nr) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - const unsigned long start_offset =3D swp_slot_offset(slot); - const unsigned long end_offset =3D start_offset + nr; - struct swap_info_struct *si; - bool any_only_cache =3D false; - unsigned long offset; - - si =3D swap_slot_tryget_swap_info(slot); - if (!si) - return; - - if (WARN_ON(end_offset > si->max)) - goto out; - - /* - * First free all entries in the range. - */ - any_only_cache =3D swap_slots_put_map_nr(si, slot, nr); - - /* - * Short-circuit the below loop if none of the entries had their - * reference drop to zero. - */ - if (!any_only_cache) - goto out; - - /* - * Now go back over the range trying to reclaim the swap cache. - */ - for (offset =3D start_offset; offset < end_offset; offset +=3D nr) { - nr =3D 1; - if (READ_ONCE(si->swap_map[offset]) =3D=3D SWAP_HAS_CACHE) { - /* - * Folios are always naturally aligned in swap so - * advance forward to the next boundary. Zero means no - * folio was found for the swap entry, so advance by 1 - * in this case. Negative value means folio was found - * but could not be reclaimed. Here we can still advance - * to the next boundary. - */ - nr =3D __try_to_reclaim_swap(si, offset, - TTRS_UNMAPPED | TTRS_FULL); - if (nr =3D=3D 0) - nr =3D 1; - else if (nr < 0) - nr =3D -nr; - nr =3D ALIGN(offset + 1, nr) - offset; - } - } - -out: - swap_slot_put_swap_info(si); -} - #ifdef CONFIG_HIBERNATION =20 swp_slot_t swap_slot_alloc_of_type(int type) @@ -2901,8 +2531,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) flush_percpu_swap_cluster(p); =20 destroy_swap_extents(p); - if (p->flags & SWP_CONTINUED) - free_swap_count_continuations(p); =20 if (!(p->flags & SWP_SOLIDSTATE)) atomic_dec(&nr_rotate_swap); @@ -3638,364 +3266,6 @@ void si_swapinfo(struct sysinfo *val) spin_unlock(&swap_lock); } =20 -/* - * Verify that nr swap entries are valid and increment their swap map coun= ts. - * - * Returns error code in following case. - * - success -> 0 - * - swp_entry is invalid -> EINVAL - * - swap-cache reference is requested but there is already one. -> EEXIST - * - swap-cache reference is requested but the entry is not used. -> ENOENT - * - swap-mapped reference requested but needs continued swap count. -> EN= OMEM - */ -static int __swap_duplicate(swp_entry_t entry, unsigned char usage, int nr) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *si; - struct swap_cluster_info *ci; - unsigned long offset; - unsigned char count; - unsigned char has_cache; - int err, i; - - si =3D swap_slot_to_info(slot); - if (WARN_ON_ONCE(!si)) { - pr_err("%s%08lx\n", Bad_file, entry.val); - return -EINVAL; - } - - offset =3D swp_slot_offset(slot); - VM_WARN_ON(nr > SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER); - VM_WARN_ON(usage =3D=3D 1 && nr > 1); - ci =3D swap_cluster_lock(si, offset); - - err =3D 0; - for (i =3D 0; i < nr; i++) { - count =3D si->swap_map[offset + i]; - - /* - * swapin_readahead() doesn't check if a swap entry is valid, so the - * swap entry could be SWAP_MAP_BAD. Check here with lock held. - */ - if (unlikely(swap_count(count) =3D=3D SWAP_MAP_BAD)) { - err =3D -ENOENT; - goto unlock_out; - } - - has_cache =3D count & SWAP_HAS_CACHE; - count &=3D ~SWAP_HAS_CACHE; - - if (!count && !has_cache) { - err =3D -ENOENT; - } else if (usage =3D=3D SWAP_HAS_CACHE) { - if (has_cache) - err =3D -EEXIST; - } else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX) { - err =3D -EINVAL; - } - - if (err) - goto unlock_out; - } - - for (i =3D 0; i < nr; i++) { - count =3D si->swap_map[offset + i]; - has_cache =3D count & SWAP_HAS_CACHE; - count &=3D ~SWAP_HAS_CACHE; - - if (usage =3D=3D SWAP_HAS_CACHE) - has_cache =3D SWAP_HAS_CACHE; - else if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX) - count +=3D usage; - else if (swap_count_continued(si, offset + i, count)) - count =3D COUNT_CONTINUED; - else { - /* - * Don't need to rollback changes, because if - * usage =3D=3D 1, there must be nr =3D=3D 1. - */ - err =3D -ENOMEM; - goto unlock_out; - } - - WRITE_ONCE(si->swap_map[offset + i], count | has_cache); - } - -unlock_out: - swap_cluster_unlock(ci); - return err; -} - -/* - * Help swapoff by noting that swap entry belongs to shmem/tmpfs - * (in which case its reference count is never incremented). - */ -void swap_shmem_alloc(swp_entry_t entry, int nr) -{ - __swap_duplicate(entry, SWAP_MAP_SHMEM, nr); -} - -/* - * Increase reference count of swap entry by 1. - * Returns 0 for success, or -ENOMEM if a swap_count_continuation is requi= red - * but could not be atomically allocated. Returns 0, just as if it succee= ded, - * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), wh= ich - * might occur if a page table entry has got corrupted. - */ -int swap_duplicate(swp_entry_t entry) -{ - int err =3D 0; - - while (!err && __swap_duplicate(entry, 1, 1) =3D=3D -ENOMEM) - err =3D add_swap_count_continuation(entry, GFP_ATOMIC); - return err; -} - -/* - * @entry: first swap entry from which we allocate nr swap cache. - * - * Called when allocating swap cache for existing swap entries, - * This can return error codes. Returns 0 at success. - * -EEXIST means there is a swap cache. - * Note: return code is different from swap_duplicate(). - */ -int swapcache_prepare(swp_entry_t entry, int nr) -{ - return __swap_duplicate(entry, SWAP_HAS_CACHE, nr); -} - -/* - * Caller should ensure entries belong to the same folio so - * the entries won't span cross cluster boundary. - */ -void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int n= r) -{ - swap_slots_put_cache(si, swp_entry_to_swp_slot(entry), nr); -} - -/* - * add_swap_count_continuation - called when a swap count is duplicated - * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entr= y's - * page of the original vmalloc'ed swap_map, to hold the continuation count - * (for that entry and for its neighbouring PAGE_SIZE swap entries). Call= ed - * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc. - * - * These continuation pages are seldom referenced: the common paths all wo= rk - * on the original swap_map, only referring to a continuation page when the - * low "digit" of a count is incremented or decremented through SWAP_MAP_M= AX. - * - * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding - * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL) - * can be called after dropping locks. - */ -int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask) -{ - struct swap_info_struct *si; - struct swap_cluster_info *ci; - struct page *head; - struct page *page; - struct page *list_page; - pgoff_t offset; - unsigned char count; - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - int ret =3D 0; - - /* - * When debugging, it's easier to use __GFP_ZERO here; but it's better - * for latency not to zero a page while GFP_ATOMIC and holding locks. - */ - page =3D alloc_page(gfp_mask | __GFP_HIGHMEM); - - si =3D swap_slot_tryget_swap_info(slot); - if (!si) { - /* - * An acceptable race has occurred since the failing - * __swap_duplicate(): the swap device may be swapoff - */ - goto outer; - } - - offset =3D swp_slot_offset(slot); - - ci =3D swap_cluster_lock(si, offset); - - count =3D swap_count(si->swap_map[offset]); - - if ((count & ~COUNT_CONTINUED) !=3D SWAP_MAP_MAX) { - /* - * The higher the swap count, the more likely it is that tasks - * will race to add swap count continuation: we need to avoid - * over-provisioning. - */ - goto out; - } - - if (!page) { - ret =3D -ENOMEM; - goto out; - } - - head =3D vmalloc_to_page(si->swap_map + offset); - offset &=3D ~PAGE_MASK; - - spin_lock(&si->cont_lock); - /* - * Page allocation does not initialize the page's lru field, - * but it does always reset its private field. - */ - if (!page_private(head)) { - BUG_ON(count & COUNT_CONTINUED); - INIT_LIST_HEAD(&head->lru); - set_page_private(head, SWP_CONTINUED); - si->flags |=3D SWP_CONTINUED; - } - - list_for_each_entry(list_page, &head->lru, lru) { - unsigned char *map; - - /* - * If the previous map said no continuation, but we've found - * a continuation page, free our allocation and use this one. - */ - if (!(count & COUNT_CONTINUED)) - goto out_unlock_cont; - - map =3D kmap_local_page(list_page) + offset; - count =3D *map; - kunmap_local(map); - - /* - * If this continuation count now has some space in it, - * free our allocation and use this one. - */ - if ((count & ~COUNT_CONTINUED) !=3D SWAP_CONT_MAX) - goto out_unlock_cont; - } - - list_add_tail(&page->lru, &head->lru); - page =3D NULL; /* now it's attached, don't free it */ -out_unlock_cont: - spin_unlock(&si->cont_lock); -out: - swap_cluster_unlock(ci); - swap_slot_put_swap_info(si); -outer: - if (page) - __free_page(page); - return ret; -} - -/* - * swap_count_continued - when the original swap_map count is incremented - * from SWAP_MAP_MAX, check if there is already a continuation page to car= ry - * into, carry if so, or else fail until a new continuation page is alloca= ted; - * when the original swap_map count is decremented from 0 with continuatio= n, - * borrow from the continuation and report whether it still holds more. - * Called while __swap_duplicate() or caller of swap_entry_put_locked() - * holds cluster lock. - */ -static bool swap_count_continued(struct swap_info_struct *si, - pgoff_t offset, unsigned char count) -{ - struct page *head; - struct page *page; - unsigned char *map; - bool ret; - - head =3D vmalloc_to_page(si->swap_map + offset); - if (page_private(head) !=3D SWP_CONTINUED) { - BUG_ON(count & COUNT_CONTINUED); - return false; /* need to add count continuation */ - } - - spin_lock(&si->cont_lock); - offset &=3D ~PAGE_MASK; - page =3D list_next_entry(head, lru); - map =3D kmap_local_page(page) + offset; - - if (count =3D=3D SWAP_MAP_MAX) /* initial increment from swap_map */ - goto init_map; /* jump over SWAP_CONT_MAX checks */ - - if (count =3D=3D (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */ - /* - * Think of how you add 1 to 999 - */ - while (*map =3D=3D (SWAP_CONT_MAX | COUNT_CONTINUED)) { - kunmap_local(map); - page =3D list_next_entry(page, lru); - BUG_ON(page =3D=3D head); - map =3D kmap_local_page(page) + offset; - } - if (*map =3D=3D SWAP_CONT_MAX) { - kunmap_local(map); - page =3D list_next_entry(page, lru); - if (page =3D=3D head) { - ret =3D false; /* add count continuation */ - goto out; - } - map =3D kmap_local_page(page) + offset; -init_map: *map =3D 0; /* we didn't zero the page */ - } - *map +=3D 1; - kunmap_local(map); - while ((page =3D list_prev_entry(page, lru)) !=3D head) { - map =3D kmap_local_page(page) + offset; - *map =3D COUNT_CONTINUED; - kunmap_local(map); - } - ret =3D true; /* incremented */ - - } else { /* decrementing */ - /* - * Think of how you subtract 1 from 1000 - */ - BUG_ON(count !=3D COUNT_CONTINUED); - while (*map =3D=3D COUNT_CONTINUED) { - kunmap_local(map); - page =3D list_next_entry(page, lru); - BUG_ON(page =3D=3D head); - map =3D kmap_local_page(page) + offset; - } - BUG_ON(*map =3D=3D 0); - *map -=3D 1; - if (*map =3D=3D 0) - count =3D 0; - kunmap_local(map); - while ((page =3D list_prev_entry(page, lru)) !=3D head) { - map =3D kmap_local_page(page) + offset; - *map =3D SWAP_CONT_MAX | count; - count =3D COUNT_CONTINUED; - kunmap_local(map); - } - ret =3D count =3D=3D COUNT_CONTINUED; - } -out: - spin_unlock(&si->cont_lock); - return ret; -} - -/* - * free_swap_count_continuations - swapoff free all the continuation pages - * appended to the swap_map, after swap_map is quiesced, before vfree'ing = it. - */ -static void free_swap_count_continuations(struct swap_info_struct *si) -{ - pgoff_t offset; - - for (offset =3D 0; offset < si->max; offset +=3D PAGE_SIZE) { - struct page *head; - head =3D vmalloc_to_page(si->swap_map + offset); - if (page_private(head)) { - struct page *page, *next; - - list_for_each_entry_safe(page, next, &head->lru, lru) { - list_del(&page->lru); - __free_page(page); - } - } - } -} - #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP) static bool __has_usable_swap(void) { diff --git a/mm/vswap.c b/mm/vswap.c index 64747493ca9f7..318933071edc6 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -24,6 +24,8 @@ * For now, there is a one-to-one correspondence between a virtual swap sl= ot * and its associated physical swap slot. * + * I. Allocation + * * Virtual swap slots are organized into PMD-sized clusters, analogous to * physical swap allocator. However, unlike the physical swap allocator, * the clusters are dynamically allocated and freed on-demand. There is no @@ -32,6 +34,26 @@ * * This allows us to avoid the overhead of pre-allocating a large number of * virtual swap clusters. + * + * II. Swap Entry Lifecycle + * + * The swap entry's lifecycle is managed at the virtual swap layer. Concep= tually, + * each virtual swap slot has a reference count, which includes: + * + * 1. The number of page table entries that refer to the virtual swap slot= , i.e + * its swap count. + * + * 2. Whether the virtual swap slot has been added to the swap cache - if = so, + * its reference count is incremented by 1. + * + * Each virtual swap slot starts out with a reference count of 1 (since it= is + * about to be added to the swap cache). Its reference count is incremente= d or + * decremented every time it is mapped to or unmapped from a PTE, as well = as + * when it is added to or removed from the swap cache. Finally, when its + * reference count reaches 0, the virtual swap slot is freed. + * + * Note that we do not have a reference count field per se - it is derived= from + * the swap_count and the in_swapcache fields. */ =20 /** @@ -42,6 +64,8 @@ * @swap_cache: The folio in swap cache. * @shadow: The shadow entry. * @memcgid: The memcg id of the owning memcg, if any. + * @swap_count: The number of page table entries that refer to the swap en= try. + * @in_swapcache: Whether the swap entry is (about to be) pinned in swap c= ache. */ struct swp_desc { swp_slot_t slot; @@ -50,9 +74,14 @@ struct swp_desc { struct folio *swap_cache; void *shadow; }; + + unsigned int swap_count; + #ifdef CONFIG_MEMCG unsigned short memcgid; #endif + + bool in_swapcache; }; =20 #define VSWAP_CLUSTER_SHIFT HPAGE_PMD_ORDER @@ -249,6 +278,8 @@ static void __vswap_alloc_from_cluster(struct vswap_clu= ster *cluster, int start) #ifdef CONFIG_MEMCG desc->memcgid =3D 0; #endif + desc->swap_count =3D 0; + desc->in_swapcache =3D true; } cluster->count +=3D nr; } @@ -452,7 +483,7 @@ static inline void release_vswap_slot(struct vswap_clus= ter *cluster, * Update the physical-to-virtual swap slot mapping. * Caller must ensure the physical swap slot's cluster is locked. */ -static void vswap_rmap_set(struct swap_cluster_info *ci, swp_slot_t slot, +void vswap_rmap_set(struct swap_cluster_info *ci, swp_slot_t slot, unsigned long vswap, int nr) { atomic_long_t *table; @@ -466,45 +497,50 @@ static void vswap_rmap_set(struct swap_cluster_info *= ci, swp_slot_t slot, __swap_table_set(ci, ci_off + i, vswap ? vswap + i : 0); } =20 -/** - * vswap_free - free a virtual swap slot. - * @entry: the virtual swap slot to free - * @ci: the physical swap slot's cluster (optional, can be NULL) +/* + * Entered with the cluster locked, but might unlock the cluster. + * This is because several operations, such as releasing physical swap slo= ts + * (i.e swap_slot_free_nr()) require the cluster to be unlocked to avoid + * deadlocks. * - * If @ci is NULL, this function is called to clean up a virtual swap entry - * when no linkage has been established between physical and virtual swap = slots. - * If @ci is provided, the caller must ensure it is locked. + * This is safe, because: + * + * 1. The swap entry to be freed has refcnt (swap count and swapcache pin) + * down to 0, so no one can change its internal state + * + * 2. The swap entry to be freed still holds a refcnt to the cluster, keep= ing + * the cluster itself valid. + * + * We will exit the function with the cluster re-locked. */ -void vswap_free(swp_entry_t entry, struct swap_cluster_info *ci) +static void vswap_free(struct vswap_cluster *cluster, struct swp_desc *des= c, + swp_entry_t entry) { - struct vswap_cluster *cluster =3D NULL; - struct swp_desc *desc; + struct zswap_entry *zswap_entry; + swp_slot_t slot; =20 - if (!entry.val) - return; + /* Clear shadow if present */ + if (xa_is_value(desc->shadow)) + desc->shadow =3D NULL; =20 - zswap_invalidate(entry); - mem_cgroup_uncharge_swap(entry, 1); + slot =3D desc->slot; + desc->slot.val =3D 0; =20 - /* do not immediately erase the virtual slot to prevent its reuse */ - rcu_read_lock(); - desc =3D vswap_iter(&cluster, entry.val); - if (!desc) { - rcu_read_unlock(); - return; + zswap_entry =3D desc->zswap_entry; + if (zswap_entry) { + desc->zswap_entry =3D NULL; + zswap_entry_free(zswap_entry); } + spin_unlock(&cluster->lock); =20 - /* Clear shadow if present */ - if (xa_is_value(desc->shadow)) - desc->shadow =3D NULL; + mem_cgroup_uncharge_swap(entry, 1); =20 - if (desc->slot.val) - vswap_rmap_set(ci, desc->slot, 0, 1); + if (slot.val) + swap_slot_free_nr(slot, 1); =20 + spin_lock(&cluster->lock); /* erase forward mapping and release the virtual slot for reallocation */ release_vswap_slot(cluster, entry.val); - spin_unlock(&cluster->lock); - rcu_read_unlock(); } =20 /** @@ -538,8 +574,12 @@ int folio_alloc_swap(struct folio *folio) * fallback from zswap store failure). */ if (swap_slot_alloc(&slot, order)) { - for (i =3D 0; i < nr; i++) - vswap_free((swp_entry_t){entry.val + i}, NULL); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + VM_WARN_ON(!desc); + vswap_free(cluster, desc, (swp_entry_t){ entry.val + i }); + } + spin_unlock(&cluster->lock); entry.val =3D 0; return -ENOMEM; } @@ -603,9 +643,11 @@ swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry) rcu_read_unlock(); return (swp_slot_t){0}; } + slot =3D desc->slot; spin_unlock(&cluster->lock); rcu_read_unlock(); + return slot; } =20 @@ -635,6 +677,352 @@ swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot) return ret; } =20 +/* + * Decrease the swap count of nr contiguous swap entries by 1 (when the sw= ap + * entries are removed from a range of PTEs), and check if any of the swap + * entries are in swap cache only after its swap count is decreased. + * + * The check is racy, but it is OK because free_swap_and_cache_nr() only u= se + * the result as a hint. + */ +static bool vswap_free_nr_any_cache_only(swp_entry_t entry, int nr) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + bool ret =3D false; + int i; + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val); + VM_WARN_ON(!desc); + ret |=3D (desc->swap_count =3D=3D 1 && desc->in_swapcache); + desc->swap_count--; + if (!desc->swap_count && !desc->in_swapcache) + vswap_free(cluster, desc, entry); + entry.val++; + } + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return ret; +} + +/** + * swap_free_nr - decrease the swap count of nr contiguous swap entries by= 1 + * (when the swap entries are removed from a range of PTEs). + * @entry: the first entry in the range. + * @nr: the number of entries in the range. + */ +void swap_free_nr(swp_entry_t entry, int nr) +{ + vswap_free_nr_any_cache_only(entry, nr); +} + +static int swap_duplicate_nr(swp_entry_t entry, int nr) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + int i =3D 0; + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + if (!desc || (!desc->swap_count && !desc->in_swapcache)) + goto done; + desc->swap_count++; + } +done: + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + if (i && i < nr) + swap_free_nr(entry, i); + + return i =3D=3D nr ? 0 : -ENOENT; +} + +/** + * swap_duplicate - increase the swap count of the swap entry by 1 (i.e wh= en + * the swap entry is stored at a new PTE). + * @entry: the swap entry. + * + * Return: -ENONENT, if we try to duplicate a non-existent swap entry. + */ +int swap_duplicate(swp_entry_t entry) +{ + return swap_duplicate_nr(entry, 1); +} + + +bool folio_swapped(struct folio *folio) +{ + struct vswap_cluster *cluster =3D NULL; + swp_entry_t entry =3D folio->swap; + int i, nr =3D folio_nr_pages(folio); + struct swp_desc *desc; + bool swapped =3D false; + + if (!entry.val) + return false; + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + if (desc && desc->swap_count) { + swapped =3D true; + break; + } + } + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return swapped; +} + +/** + * swp_swapcount - return the swap count of the swap entry. + * @id: the swap entry. + * + * Note that all the swap count functions are identical in the new design, + * since we no longer need swap count continuation. + * + * Return: the swap count of the swap entry. + */ +int swp_swapcount(swp_entry_t entry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + unsigned int ret; + + rcu_read_lock(); + desc =3D vswap_iter(&cluster, entry.val); + ret =3D desc ? desc->swap_count : 0; + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + return ret; +} + +int __swap_count(swp_entry_t entry) +{ + return swp_swapcount(entry); +} + +bool swap_entry_swapped(swp_entry_t entry) +{ + return !!swp_swapcount(entry); +} + +void swap_shmem_alloc(swp_entry_t entry, int nr) +{ + swap_duplicate_nr(entry, nr); +} + +void swapcache_clear(swp_entry_t entry, int nr) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + int i; + + if (!nr) + return; + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val); + desc->in_swapcache =3D false; + if (!desc->swap_count) + vswap_free(cluster, desc, entry); + entry.val++; + } + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); +} + +int swapcache_prepare(swp_entry_t entry, int nr) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + int i, ret =3D 0; + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + + if (!desc) { + ret =3D -ENOENT; + goto done; + } + + if (!desc->swap_count && !desc->in_swapcache) { + ret =3D -ENOENT; + goto done; + } + + if (desc->in_swapcache) { + ret =3D -EEXIST; + goto done; + } + + desc->in_swapcache =3D true; + } +done: + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + if (i && i < nr) + swapcache_clear(entry, i); + if (i < nr && !ret) + ret =3D -ENOENT; + return ret; +} + +/** + * is_swap_cached - check if the swap entry is cached + * @entry: swap entry to check + * + * Returns true if the swap entry is cached, false otherwise. + */ +bool is_swap_cached(swp_entry_t entry) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + bool cached; + + rcu_read_lock(); + desc =3D vswap_iter(&cluster, entry.val); + cached =3D desc ? desc->in_swapcache : false; + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + return cached; +} + +/** + * vswap_only_has_cache - check if all the slots in the range are still va= lid, + * and are in swap cache only (i.e not stored in any + * PTEs). + * @entry: the first slot in the range. + * @nr: the number of slots in the range. + * + * Return: true if all the slots in the range are still valid, and are in = swap + * cache only, or false otherwise. + */ +bool vswap_only_has_cache(swp_entry_t entry, int nr) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + int i =3D 0; + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + if (!desc || desc->swap_count || !desc->in_swapcache) + goto done; + } +done: + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return i =3D=3D nr; +} + +/** + * non_swapcache_batch - count the longest range starting from a particular + * swap slot that are stil valid, but not in swap ca= che. + * @entry: the first slot to check. + * @max_nr: the maximum number of slots to check. + * + * Return: the number of slots in the longest range that are still valid, = but + * not in swap cache. + */ +int non_swapcache_batch(swp_entry_t entry, int max_nr) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + int i; + + if (!entry.val) + return 0; + + rcu_read_lock(); + for (i =3D 0; i < max_nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + if (!desc || desc->in_swapcache || !desc->swap_count) + goto done; + } +done: + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return i; +} + +/** + * free_swap_and_cache_nr() - Release a swap count on range of swap entrie= s and + * reclaim their cache if no more references re= main. + * @entry: First entry of range. + * @nr: Number of entries in range. + * + * For each swap entry in the contiguous range, release a swap count. If a= ny + * swap entries have their swap count decremented to zero, try to reclaim = their + * associated swap cache pages. + */ +void free_swap_and_cache_nr(swp_entry_t entry, int nr) +{ + int i =3D 0, incr =3D 1; + struct folio *folio; + + if (vswap_free_nr_any_cache_only(entry, nr)) { + while (i < nr) { + incr =3D 1; + if (vswap_only_has_cache(entry, 1)) { + folio =3D swap_cache_get_folio(entry); + if (!folio) + goto next; + + if (!folio_trylock(folio)) { + folio_put(folio); + goto next; + } + + if (!folio_matches_swap_entry(folio, entry)) { + folio_unlock(folio); + folio_put(folio); + goto next; + } + + /* + * Folios are always naturally aligned in swap so + * advance forward to the next boundary. + */ + incr =3D ALIGN(entry.val + 1, folio_nr_pages(folio)) - entry.val; + folio_free_swap(folio); + folio_unlock(folio); + folio_put(folio); + } +next: + i +=3D incr; + entry.val +=3D incr; + } + } +} + +/* + * Called after dropping swapcache to decrease refcnt to swap entries. + */ +void put_swap_folio(struct folio *folio, swp_entry_t entry) +{ + int nr =3D folio_nr_pages(folio); + + VM_WARN_ON(!folio_test_locked(folio)); + swapcache_clear(entry, nr); +} + bool tryget_swap_entry(swp_entry_t entry, struct swap_info_struct **si) { struct vswap_cluster *cluster; @@ -869,8 +1257,8 @@ void *swap_cache_get_shadow(swp_entry_t entry) * Context: Caller must ensure @entry is valid and protect the cluster with * reference count or locks. * - * The caller also needs to update the corresponding swap_map slots with - * SWAP_HAS_CACHE bit to avoid race or conflict. + * The caller also needs to obtain the swap entries' swap cache pins to av= oid + * race or conflict. */ void swap_cache_add_folio(struct folio *folio, swp_entry_t entry, void **s= hadowp) { diff --git a/mm/zswap.c b/mm/zswap.c index 72441131f094e..e46349f9c90bb 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -703,7 +703,7 @@ static void zswap_entry_cache_free(struct zswap_entry *= entry) * Carries out the common pattern of freeing an entry's zsmalloc allocatio= n, * freeing the entry itself, and decrementing the number of stored pages. */ -static void zswap_entry_free(struct zswap_entry *entry) +void zswap_entry_free(struct zswap_entry *entry) { zswap_lru_del(&zswap_list_lru, entry); zs_free(entry->pool->zs_pool, entry->handle); @@ -1627,18 +1627,6 @@ int zswap_load(struct folio *folio) return 0; } =20 -void zswap_invalidate(swp_entry_t swp) -{ - struct zswap_entry *entry; - - if (zswap_empty(swp)) - return; - - entry =3D zswap_entry_erase(swp); - if (entry) - zswap_entry_free(entry); -} - /********************************* * debugfs functions **********************************/ --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-ot1-f51.google.com (mail-ot1-f51.google.com [209.85.210.51]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9995F35EDC1 for ; Sun, 8 Feb 2026 21:59:12 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.51 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587953; cv=none; b=Ga1Zelk49QbfL+lNLAq54APtGFOiw1ef+ul2hwsIbM80OAOTymaub84yRccK21YgOmRVpuXi4+EnbY1LE5YwZm7dxVCcyQsudEGbYUr076f2kkaQn3xs/TAv/r1m+3HEpBJvhKE6CILTOX2luTwAE/zBplhrU9joQYp7P1cjTa0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587953; c=relaxed/simple; bh=vWlPyTOaBTunUX0BNNJOtxtXZN+2/4+4XM8QxVMmPhE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=SP+XjLIAqDf05YLrSZ2fBCgiNh8vRnVGII/HQnh8dvB8iizDJdZyy2vNv6P4rvxFSgdAw0crbtGHpL8468Q+sQc+PzH2ArQexP7FR1cBW1R2it6mqRI49Lk1/h8bNqoW3Hu7fE4PNEipjzgwdjvBnVZKyw/i34PPB3vQfd55bg8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=AM7xwZHD; arc=none smtp.client-ip=209.85.210.51 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.b="AM7xwZHD" Received: by mail-ot1-f51.google.com with SMTP id 46e09a7af769-7cfdf7e7d19so2137959a34.2 for ; Sun, 08 Feb 2026 13:59:12 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587951; x=1771192751; 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; bh=ruceNSX4J0gFFUSUTt6Ls7KI6XV9ahGZQUD7Wf6LUkY=; b=AM7xwZHD89tEZOV6pjR8Qw/NK/16Vnt0H62jOzlWB6n2IYfP+8O10l5tar34T2Xdgn PfA8KBW3HT6BmBr9u7RgfFh0XAA7KwadYHyfuPwtYQ3RwZxOB3rSWpjNWX1O3o/9R2U7 hwvYNl75cY2YyZz5xfAqsSt7k7PspZQaLdhbJUGvH3NYZKM10hq0gxZeWcqCAIcpGb5M nnXog8zfpbpnQ7bnfrOOYt7nefAd5jE6AzzNWOZF9padm8ZIy33WbApeoJGfTqaSnHnt sUaxNTdmWWiinyzYIaG2nqcOw46mCyA08r2BUW+Ue9cREcs2cZYoZo7sRRyixlnbZ3U8 bRig== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587951; x=1771192751; 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; bh=ruceNSX4J0gFFUSUTt6Ls7KI6XV9ahGZQUD7Wf6LUkY=; b=LG6tCRMNkZH0CgMMmNAwz5SY48+89lE4QZcG/B6EBYlvqXgFFmJe3zRm4TPnLLf5hS kIPUhdqHB2q1kcqZAuBLovgVHCcVGgWKALzCdDJg83FIgbKUxoCt87iniNWDzuQZKQC/ +SBxAiupsiRQz3K2uMpXHWC/jhX4OdLoNslx/a3qBv4ug9qMgSiLbyNLtDu5fCaSP0Lm uKSUop/puF8tmcbWYYmRG7pJGdNrJJpVgV2+HFfTzj9dxZCAf66+e6ZIdjBWAmmqwfK8 iT3FzGQrLMbZwzf1sc8/DC5d7qBz5N9Ln+LsxeGJLJfvf96H1kbvaJkd69ZTgu1nOHgu pcwg== X-Forwarded-Encrypted: i=1; AJvYcCVikuO+zkzZoLz3z7AYzdmwTYRACLhCNc70kvjJHkAJ5L14KxljCcUJZD9YLH57DRFj48J/1inoAWAWfq4=@vger.kernel.org X-Gm-Message-State: AOJu0YxpaYJhU5Hf63Ght5kaWqrB2OQFPPhuphf+hhFVsrTXZ4cNXbMm My1WgUew8Otn9enb8IicUBna36KtPbT7v9XWQiF0P/TZvX4lsqpl8tw/ X-Gm-Gg: AZuq6aIrJ3Dr9ElaCJCuX6LxTv4IJLch5AAA+/NzhaHKiCsUsn7ptJaZ1+MyFGoVOrJ cGjK0LpJC9HMvBuP2Nr+0ZOKqmwPEhMftt9Snd5VXhrJeVGCnKOcAO8ajA8wwjbbVRnevEjJYLU scB7olZotrIaivG2LCfK/nIiumTUYeyHUCT0vlf/e9mrqJIsoAlTdOM6nWRmn7/Lz/vloNcLIG9 Ez0j8mw924/WgC5gKNJ0oXJ+CYYlD1bt5iVBdXU/Ddz2sjR9rj7ThbnmeFargPAS4Zk6Ec57Y0n 8uXH6vX4ON3XR3sSRuizOSKbbPCSYROvA7wkgZ29ksL2DwzwsVrW+utwvfq8fmjo/mLmlx/4xy/ Jjj8/ULY+nDZkodwo/OQIDJ67bjEFNJlzOQhR+HlA2Kxzq7/woge1FNLaJ+7pnGyYneTX4Cj8mG bZynvI/l3UlY32eSFR1AxyBZ4OEeW+qbnTQg== X-Received: by 2002:a05:6830:628c:b0:7d1:9217:94e with SMTP id 46e09a7af769-7d464489f8dmr5885223a34.26.1770587951179; Sun, 08 Feb 2026 13:59:11 -0800 (PST) Received: from localhost ([2a03:2880:10ff:4e::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d46470da04sm6394262a34.7.2026.02.08.13.59.10 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:10 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 14/20] mm: swap: decouple virtual swap slot from backing store Date: Sun, 8 Feb 2026 13:58:27 -0800 Message-ID: <20260208215839.87595-15-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This patch presents the first real use case of the new virtual swap design. It leverages the virtualization of the swap space to decouple a swap entry and its backing storage. A swap entry can now be backed by one of the following options: 1. A physical swap slot (i.e on a physical swapfile/swap partition). 2. A "zero swap page", i.e the swapped out page is a zero page. 3. A compressed object in the zswap pool. 4. An in-memory page. This can happen when a page is loaded (exclusively) from the zswap pool, or if the page is rejected by zswap and zswap writeback is disabled. This allows us to use zswap and the zero swap page optimization, without having to reserved a slot on a swapfile, or a swapfile at all. This translates to tens to hundreds of GBs of disk saving on hosts and workloads that have high memory usage, as well as removes this spurious limit on the usage of these optimizations. One implication of this change is that we need to be much more careful with THP swapin and batched swap free operations. The central requirement is the range of entries we are working with must have no mixed backing states: 1. For now, zswap-backed entries are not supported for these batched operations. 2. All the entries must be backed by the same type. 3. If the swap entries in the batch are backed by in-memory folio, it must be the same folio (i.e they correspond to the subpages of that folio). 4. If the swap entries in the batch are backed by slots on swapfiles, it must be the same swapfile, and these physical swap slots must also be contiguous. For now, we still charge virtual swap slots towards the memcg's swap usage. In a following patch, we will change this behavior and only charge physical (i.e on swapfile) swap slots towards the memcg's swap usage. Signed-off-by: Nhat Pham --- include/linux/swap.h | 14 + include/linux/zswap.h | 3 +- mm/internal.h | 14 +- mm/memcontrol.c | 65 +++-- mm/memory.c | 84 ++++-- mm/page_io.c | 74 ++--- mm/shmem.c | 6 +- mm/swap.h | 32 +-- mm/swap_state.c | 29 +- mm/swapfile.c | 8 - mm/vmscan.c | 19 +- mm/vswap.c | 638 ++++++++++++++++++++++++++++++++++-------- mm/zswap.c | 45 ++- 13 files changed, 729 insertions(+), 302 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index aae2e502d9975..54df972608047 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -658,12 +658,26 @@ static inline bool mem_cgroup_swap_full(struct folio = *folio) =20 int vswap_init(void); void vswap_exit(void); +bool vswap_alloc_swap_slot(struct folio *folio); swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry); swp_entry_t swp_slot_to_swp_entry(swp_slot_t slot); bool tryget_swap_entry(swp_entry_t entry, struct swap_info_struct **si); void put_swap_entry(swp_entry_t entry, struct swap_info_struct *si); bool folio_swapped(struct folio *folio); bool vswap_only_has_cache(swp_entry_t entry, int nr); +int non_swapcache_batch(swp_entry_t entry, int nr); +bool vswap_swapfile_backed(swp_entry_t entry, int nr); +bool vswap_folio_backed(swp_entry_t entry, int nr); +void vswap_store_folio(swp_entry_t entry, struct folio *folio); +void swap_zeromap_folio_set(struct folio *folio); +void vswap_assoc_zswap(swp_entry_t entry, struct zswap_entry *zswap_entry); +bool vswap_can_swapin_thp(swp_entry_t entry, int nr); =20 +static inline struct swap_info_struct *vswap_get_device(swp_entry_t entry) +{ + swp_slot_t slot =3D swp_entry_to_swp_slot(entry); + + return slot.val ? swap_slot_tryget_swap_info(slot) : NULL; +} #endif /* __KERNEL__*/ #endif /* _LINUX_SWAP_H */ diff --git a/include/linux/zswap.h b/include/linux/zswap.h index 07b2936c38f29..f33b4433a5ee8 100644 --- a/include/linux/zswap.h +++ b/include/linux/zswap.h @@ -33,9 +33,8 @@ void zswap_lruvec_state_init(struct lruvec *lruvec); void zswap_folio_swapin(struct folio *folio); bool zswap_is_enabled(void); bool zswap_never_enabled(void); -void *zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry); +void zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry); void *zswap_entry_load(swp_entry_t swpentry); -void *zswap_entry_erase(swp_entry_t swpentry); bool zswap_empty(swp_entry_t swpentry); void zswap_entry_free(struct zswap_entry *entry); =20 diff --git a/mm/internal.h b/mm/internal.h index 7ced0def684ca..cfe97501e4885 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -327,19 +327,7 @@ static inline swp_entry_t swap_nth(swp_entry_t entry, = long n) return (swp_entry_t) { entry.val + n }; } =20 -/* similar to swap_nth, but check the backing physical slots as well. */ -static inline swp_entry_t swap_move(swp_entry_t entry, long delta) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry), next_slot; - swp_entry_t next_entry =3D swap_nth(entry, delta); - - next_slot =3D swp_entry_to_swp_slot(next_entry); - if (swp_slot_type(slot) !=3D swp_slot_type(next_slot) || - swp_slot_offset(slot) + delta !=3D swp_slot_offset(next_slot)) - next_entry.val =3D 0; - - return next_entry; -} +swp_entry_t swap_move(swp_entry_t entry, long delta); =20 /** * pte_move_swp_offset - Move the swap entry offset field of a swap pte diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 86f43b7e5f710..2ba5811e7edba 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -5247,10 +5247,18 @@ void __mem_cgroup_uncharge_swap(swp_entry_t entry, = unsigned int nr_pages) rcu_read_unlock(); } =20 +static bool mem_cgroup_may_zswap(struct mem_cgroup *original_memcg); + long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg) { - long nr_swap_pages =3D get_nr_swap_pages(); + long nr_swap_pages, nr_zswap_pages =3D 0; + + if (zswap_is_enabled() && (mem_cgroup_disabled() || do_memsw_account() || + mem_cgroup_may_zswap(memcg))) { + nr_zswap_pages =3D PAGE_COUNTER_MAX; + } =20 + nr_swap_pages =3D max_t(long, nr_zswap_pages, get_nr_swap_pages()); if (mem_cgroup_disabled() || do_memsw_account()) return nr_swap_pages; for (; !mem_cgroup_is_root(memcg); memcg =3D parent_mem_cgroup(memcg)) @@ -5419,6 +5427,29 @@ static struct cftype swap_files[] =3D { }; =20 #ifdef CONFIG_ZSWAP +static bool mem_cgroup_may_zswap(struct mem_cgroup *original_memcg) +{ + struct mem_cgroup *memcg; + + for (memcg =3D original_memcg; !mem_cgroup_is_root(memcg); + memcg =3D parent_mem_cgroup(memcg)) { + unsigned long max =3D READ_ONCE(memcg->zswap_max); + unsigned long pages; + + if (max =3D=3D PAGE_COUNTER_MAX) + continue; + if (max =3D=3D 0) + return false; + + /* Force flush to get accurate stats for charging */ + __mem_cgroup_flush_stats(memcg, true); + pages =3D memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE; + if (pages >=3D max) + return false; + } + return true; +} + /** * obj_cgroup_may_zswap - check if this cgroup can zswap * @objcg: the object cgroup @@ -5433,34 +5464,15 @@ static struct cftype swap_files[] =3D { */ bool obj_cgroup_may_zswap(struct obj_cgroup *objcg) { - struct mem_cgroup *memcg, *original_memcg; + struct mem_cgroup *memcg; bool ret =3D true; =20 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) return true; =20 - original_memcg =3D get_mem_cgroup_from_objcg(objcg); - for (memcg =3D original_memcg; !mem_cgroup_is_root(memcg); - memcg =3D parent_mem_cgroup(memcg)) { - unsigned long max =3D READ_ONCE(memcg->zswap_max); - unsigned long pages; - - if (max =3D=3D PAGE_COUNTER_MAX) - continue; - if (max =3D=3D 0) { - ret =3D false; - break; - } - - /* Force flush to get accurate stats for charging */ - __mem_cgroup_flush_stats(memcg, true); - pages =3D memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE; - if (pages < max) - continue; - ret =3D false; - break; - } - mem_cgroup_put(original_memcg); + memcg =3D get_mem_cgroup_from_objcg(objcg); + ret =3D mem_cgroup_may_zswap(memcg); + mem_cgroup_put(memcg); return ret; } =20 @@ -5604,6 +5616,11 @@ static struct cftype zswap_files[] =3D { }, { } /* terminate */ }; +#else +static inline bool mem_cgroup_may_zswap(struct mem_cgroup *original_memcg) +{ + return false; +} #endif /* CONFIG_ZSWAP */ =20 static int __init mem_cgroup_swap_init(void) diff --git a/mm/memory.c b/mm/memory.c index 641e3f65edc00..a16bf84ebaaf9 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4362,6 +4362,15 @@ static inline bool should_try_to_free_swap(struct fo= lio *folio, if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) || folio_test_mlocked(folio)) return true; + + /* + * Mixed and/or non-swapfile backends cannot be re-used for future swapou= ts + * anyway. Try to free swap space unless the folio is backed by contiguous + * physical swap slots. + */ + if (!vswap_swapfile_backed(folio->swap, folio_nr_pages(folio))) + return true; + /* * If we want to map a page that's in the swapcache writable, we * have to detect via the refcount if we're really the exclusive @@ -4623,12 +4632,12 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) struct folio *swapcache, *folio =3D NULL; DECLARE_WAITQUEUE(wait, current); struct page *page; - struct swap_info_struct *si =3D NULL; + struct swap_info_struct *si =3D NULL, *stable_si; rmap_t rmap_flags =3D RMAP_NONE; bool need_clear_cache =3D false; bool swapoff_locked =3D false; bool exclusive =3D false; - softleaf_t entry; + softleaf_t orig_entry, entry; pte_t pte; vm_fault_t ret =3D 0; void *shadow =3D NULL; @@ -4641,6 +4650,11 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) goto out; =20 entry =3D softleaf_from_pte(vmf->orig_pte); + /* + * entry might change if we get a large folio - remember the original ent= ry + * for unlocking swapoff etc. + */ + orig_entry =3D entry; if (unlikely(!softleaf_is_swap(entry))) { if (softleaf_is_migration(entry)) { migration_entry_wait(vma->vm_mm, vmf->pmd, @@ -4705,7 +4719,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) swapcache =3D folio; =20 if (!folio) { - if (data_race(si->flags & SWP_SYNCHRONOUS_IO) && + if (si && data_race(si->flags & SWP_SYNCHRONOUS_IO) && __swap_count(entry) =3D=3D 1) { /* skip swapcache */ folio =3D alloc_swap_folio(vmf); @@ -4736,6 +4750,17 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) } need_clear_cache =3D true; =20 + /* + * Recheck to make sure the entire range is still + * THP-swapin-able. Note that before we call + * swapcache_prepare(), entries in the range can + * still have their backing status changed. + */ + if (!vswap_can_swapin_thp(entry, nr_pages)) { + schedule_timeout_uninterruptible(1); + goto out_page; + } + memcg1_swapin(entry, nr_pages); =20 shadow =3D swap_cache_get_shadow(entry); @@ -4916,27 +4941,40 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) * swapcache -> certainly exclusive. */ exclusive =3D true; - } else if (exclusive && folio_test_writeback(folio) && - data_race(si->flags & SWP_STABLE_WRITES)) { + } else if (exclusive && folio_test_writeback(folio)) { /* - * This is tricky: not all swap backends support - * concurrent page modifications while under writeback. - * - * So if we stumble over such a page in the swapcache - * we must not set the page exclusive, otherwise we can - * map it writable without further checks and modify it - * while still under writeback. + * We need to look up the swap device again here, because + * the si we got from tryget_swap_entry() might have changed + * before we pin the backend. * - * For these problematic swap backends, simply drop the - * exclusive marker: this is perfectly fine as we start - * writeback only if we fully unmapped the page and - * there are no unexpected references on the page after - * unmapping succeeded. After fully unmapped, no - * further GUP references (FOLL_GET and FOLL_PIN) can - * appear, so dropping the exclusive marker and mapping - * it only R/O is fine. + * With the folio locked and loaded into the swap cache, we can + * now guarantee a stable backing state. */ - exclusive =3D false; + stable_si =3D vswap_get_device(entry); + if (stable_si && data_race(stable_si->flags & SWP_STABLE_WRITES)) { + /* + * This is tricky: not all swap backends support + * concurrent page modifications while under writeback. + * + * So if we stumble over such a page in the swapcache + * we must not set the page exclusive, otherwise we can + * map it writable without further checks and modify it + * while still under writeback. + * + * For these problematic swap backends, simply drop the + * exclusive marker: this is perfectly fine as we start + * writeback only if we fully unmapped the page and + * there are no unexpected references on the page after + * unmapping succeeded. After fully unmapped, no + * further GUP references (FOLL_GET and FOLL_PIN) can + * appear, so dropping the exclusive marker and mapping + * it only R/O is fine. + */ + exclusive =3D false; + } + + if (stable_si) + swap_slot_put_swap_info(stable_si); } } =20 @@ -5045,7 +5083,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) wake_up(&swapcache_wq); } if (swapoff_locked) - put_swap_entry(entry, si); + put_swap_entry(orig_entry, si); return ret; out_nomap: if (vmf->pte) @@ -5064,7 +5102,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) wake_up(&swapcache_wq); } if (swapoff_locked) - put_swap_entry(entry, si); + put_swap_entry(orig_entry, si); return ret; } =20 diff --git a/mm/page_io.c b/mm/page_io.c index 5de3705572955..675ec6445609b 100644 --- a/mm/page_io.c +++ b/mm/page_io.c @@ -201,44 +201,6 @@ static bool is_folio_zero_filled(struct folio *folio) return true; } =20 -static void swap_zeromap_folio_set(struct folio *folio) -{ - struct obj_cgroup *objcg =3D get_obj_cgroup_from_folio(folio); - struct swap_info_struct *sis =3D - __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); - int nr_pages =3D folio_nr_pages(folio); - swp_entry_t entry; - swp_slot_t slot; - unsigned int i; - - for (i =3D 0; i < folio_nr_pages(folio); i++) { - entry =3D page_swap_entry(folio_page(folio, i)); - slot =3D swp_entry_to_swp_slot(entry); - set_bit(swp_slot_offset(slot), sis->zeromap); - } - - count_vm_events(SWPOUT_ZERO, nr_pages); - if (objcg) { - count_objcg_events(objcg, SWPOUT_ZERO, nr_pages); - obj_cgroup_put(objcg); - } -} - -static void swap_zeromap_folio_clear(struct folio *folio) -{ - struct swap_info_struct *sis =3D - __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); - swp_entry_t entry; - swp_slot_t slot; - unsigned int i; - - for (i =3D 0; i < folio_nr_pages(folio); i++) { - entry =3D page_swap_entry(folio_page(folio, i)); - slot =3D swp_entry_to_swp_slot(entry); - clear_bit(swp_slot_offset(slot), sis->zeromap); - } -} - /* * We may have stale swap cache pages in memory: notice * them here and get rid of the unnecessary final write. @@ -260,23 +222,22 @@ int swap_writeout(struct folio *folio, struct swap_io= cb **swap_plug) goto out_unlock; } =20 - /* - * Use a bitmap (zeromap) to avoid doing IO for zero-filled pages. - * The bits in zeromap are protected by the locked swapcache folio - * and atomic updates are used to protect against read-modify-write - * corruption due to other zero swap entries seeing concurrent updates. - */ if (is_folio_zero_filled(folio)) { swap_zeromap_folio_set(folio); goto out_unlock; } =20 /* - * Clear bits this folio occupies in the zeromap to prevent zero data - * being read in from any previous zero writes that occupied the same - * swap entries. + * Release swap backends to make sure we do not have mixed backends + * + * The only exception is if the folio is already backed by a + * contiguous range of physical swap slots (for e.g, from a previous + * swapout attempt when zswap is disabled). + * + * Keep that backend to avoid reallocation of physical swap slots. */ - swap_zeromap_folio_clear(folio); + if (!vswap_swapfile_backed(folio->swap, folio_nr_pages(folio))) + vswap_store_folio(folio->swap, folio); =20 if (zswap_store(folio)) { count_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT); @@ -287,6 +248,12 @@ int swap_writeout(struct folio *folio, struct swap_ioc= b **swap_plug) return AOP_WRITEPAGE_ACTIVATE; } =20 + /* fall back to physical swap device */ + if (!vswap_alloc_swap_slot(folio)) { + folio_mark_dirty(folio); + return AOP_WRITEPAGE_ACTIVATE; + } + __swap_writepage(folio, swap_plug); return 0; out_unlock: @@ -618,14 +585,11 @@ static void swap_read_folio_bdev_async(struct folio *= folio, =20 void swap_read_folio(struct folio *folio, struct swap_iocb **plug) { - struct swap_info_struct *sis =3D - __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); - bool synchronous =3D sis->flags & SWP_SYNCHRONOUS_IO; - bool workingset =3D folio_test_workingset(folio); + struct swap_info_struct *sis; + bool synchronous, workingset =3D folio_test_workingset(folio); unsigned long pflags; bool in_thrashing; =20 - VM_BUG_ON_FOLIO(!folio_test_swapcache(folio) && !synchronous, folio); VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); VM_BUG_ON_FOLIO(folio_test_uptodate(folio), folio); =20 @@ -651,6 +615,10 @@ void swap_read_folio(struct folio *folio, struct swap_= iocb **plug) /* We have to read from slower devices. Increase zswap protection. */ zswap_folio_swapin(folio); =20 + sis =3D __swap_slot_to_info(swp_entry_to_swp_slot(folio->swap)); + synchronous =3D sis->flags & SWP_SYNCHRONOUS_IO; + VM_BUG_ON_FOLIO(!folio_test_swapcache(folio) && !synchronous, folio); + if (data_race(sis->flags & SWP_FS_OPS)) { swap_read_folio_fs(folio, plug); } else if (synchronous) { diff --git a/mm/shmem.c b/mm/shmem.c index 780571c830e5b..3a346cca114ab 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -1459,7 +1459,7 @@ static unsigned int shmem_find_swap_entries(struct ad= dress_space *mapping, * swapin error entries can be found in the mapping. But they're * deliberately ignored here as we've done everything we can do. */ - if (swp_slot_type(slot) !=3D type) + if (!slot.val || swp_slot_type(slot) !=3D type) continue; =20 indices[folio_batch_count(fbatch)] =3D xas.xa_index; @@ -1604,7 +1604,7 @@ int shmem_writeout(struct folio *folio, struct swap_i= ocb **plug, if ((info->flags & SHMEM_F_LOCKED) || sbinfo->noswap) goto redirty; =20 - if (!total_swap_pages) + if (!zswap_is_enabled() && !total_swap_pages) goto redirty; =20 /* @@ -2341,7 +2341,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, /* Look it up and read it in.. */ folio =3D swap_cache_get_folio(swap); if (!folio) { - if (data_race(si->flags & SWP_SYNCHRONOUS_IO)) { + if (si && data_race(si->flags & SWP_SYNCHRONOUS_IO)) { /* Direct swapin skipping swap cache & readahead */ folio =3D shmem_swap_alloc_folio(inode, vma, index, index_entry, order, gfp); diff --git a/mm/swap.h b/mm/swap.h index ae97cf9712c5c..d41e6a0e70753 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -310,35 +310,15 @@ static inline unsigned int folio_swap_flags(struct fo= lio *folio) { swp_slot_t swp_slot =3D swp_entry_to_swp_slot(folio->swap); =20 + /* The folio might not be backed by any physical swap slots + * (for e.g zswap-backed only). + */ + if (!swp_slot.val) + return 0; return __swap_slot_to_info(swp_slot)->flags; } =20 -/* - * Return the count of contiguous swap entries that share the same - * zeromap status as the starting entry. If is_zeromap is not NULL, - * it will return the zeromap status of the starting entry. - */ -static inline int swap_zeromap_batch(swp_entry_t entry, int max_nr, - bool *is_zeromap) -{ - swp_slot_t slot =3D swp_entry_to_swp_slot(entry); - struct swap_info_struct *sis =3D __swap_slot_to_info(slot); - unsigned long start =3D swp_slot_offset(slot); - unsigned long end =3D start + max_nr; - bool first_bit; - - first_bit =3D test_bit(start, sis->zeromap); - if (is_zeromap) - *is_zeromap =3D first_bit; - - if (max_nr <=3D 1) - return max_nr; - if (first_bit) - return find_next_zero_bit(sis->zeromap, end, start) - start; - else - return find_next_bit(sis->zeromap, end, start) - start; -} - +int swap_zeromap_batch(swp_entry_t entry, int max_nr, bool *is_zeromap); int non_swapcache_batch(swp_entry_t entry, int max_nr); =20 #else /* CONFIG_SWAP */ diff --git a/mm/swap_state.c b/mm/swap_state.c index 1827527e88d33..ad80bf098b63f 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -179,6 +179,10 @@ struct folio *__read_swap_cache_async(swp_entry_t entr= y, gfp_t gfp_mask, struct folio *result =3D NULL; void *shadow =3D NULL; =20 + /* we might get an unsed entry from cluster readahead - just skip */ + if (!entry.val) + return NULL; + *new_page_allocated =3D false; for (;;) { int err; @@ -213,8 +217,20 @@ struct folio *__read_swap_cache_async(swp_entry_t entr= y, gfp_t gfp_mask, * Swap entry may have been freed since our caller observed it. */ err =3D swapcache_prepare(entry, 1); - if (!err) + if (!err) { + /* This might be invoked by swap_cluster_readahead(), which can + * race with shmem_swapin_folio(). The latter might have already + * called swap_cache_del_folio(), allowing swapcache_prepare() + * to succeed here. This can lead to reading bogus data to populate + * the page. To prevent this, skip folio-backed virtual swap slots, + * and let caller retry if necessary. + */ + if (vswap_folio_backed(entry, 1)) { + swapcache_clear(entry, 1); + goto put_and_return; + } break; + } else if (err !=3D -EEXIST) goto put_and_return; =20 @@ -391,11 +407,18 @@ struct folio *swap_cluster_readahead(swp_entry_t entr= y, gfp_t gfp_mask, unsigned long offset =3D slot_offset; unsigned long start_offset, end_offset; unsigned long mask; - struct swap_info_struct *si =3D __swap_slot_to_info(slot); + struct swap_info_struct *si =3D swap_slot_tryget_swap_info(slot); struct blk_plug plug; struct swap_iocb *splug =3D NULL; bool page_allocated; =20 + /* + * The swap entry might not be backed by any physical swap slot. In that + * case, just skip readahead and bring in the target entry. + */ + if (!si) + goto skip; + mask =3D swapin_nr_pages(offset) - 1; if (!mask) goto skip; @@ -429,6 +452,8 @@ struct folio *swap_cluster_readahead(swp_entry_t entry,= gfp_t gfp_mask, swap_read_unplug(splug); lru_add_drain(); /* Push any new pages onto the LRU now */ skip: + if (si) + swap_slot_put_swap_info(si); /* The page was likely read above, so no need for plugging here */ folio =3D __read_swap_cache_async(entry, gfp_mask, mpol, ilx, &page_allocated, false); diff --git a/mm/swapfile.c b/mm/swapfile.c index 6c5e46bf40701..1aa29dd220f9a 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -1210,14 +1210,6 @@ static void swap_range_free(struct swap_info_struct = *si, unsigned long offset, { unsigned long end =3D offset + nr_entries - 1; void (*swap_slot_free_notify)(struct block_device *, unsigned long); - unsigned int i; - - /* - * Use atomic clear_bit operations only on zeromap instead of non-atomic - * bitmap_clear to prevent adjacent bits corruption due to simultaneous w= rites. - */ - for (i =3D 0; i < nr_entries; i++) - clear_bit(offset + i, si->zeromap); =20 if (si->flags & SWP_BLKDEV) swap_slot_free_notify =3D diff --git a/mm/vmscan.c b/mm/vmscan.c index c9ec1a1458b4e..6b200a6bb1160 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -365,10 +365,11 @@ static inline bool can_reclaim_anon_pages(struct mem_= cgroup *memcg, { if (memcg =3D=3D NULL) { /* - * For non-memcg reclaim, is there - * space in any swap device? + * For non-memcg reclaim: + * + * Check if zswap is enabled or if there is space in any swap device? */ - if (get_nr_swap_pages() > 0) + if (zswap_is_enabled() || get_nr_swap_pages() > 0) return true; } else { /* Is the memcg below its swap limit? */ @@ -2640,12 +2641,12 @@ static void get_scan_count(struct lruvec *lruvec, s= truct scan_control *sc, static bool can_age_anon_pages(struct lruvec *lruvec, struct scan_control *sc) { - /* Aging the anon LRU is valuable if swap is present: */ - if (total_swap_pages > 0) - return true; - - /* Also valuable if anon pages can be demoted: */ - return can_demote(lruvec_pgdat(lruvec)->node_id, sc, + /* + * Aging the anon LRU is valuable if zswap or physical swap is available = or + * anon pages can be demoted + */ + return zswap_is_enabled() || total_swap_pages > 0 || + can_demote(lruvec_pgdat(lruvec)->node_id, sc, lruvec_memcg(lruvec)); } =20 diff --git a/mm/vswap.c b/mm/vswap.c index 318933071edc6..fb6179ce3ace7 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -11,6 +11,7 @@ #include #include #include +#include "internal.h" #include "swap.h" #include "swap_table.h" =20 @@ -54,22 +55,48 @@ * * Note that we do not have a reference count field per se - it is derived= from * the swap_count and the in_swapcache fields. + * + * III. Backing State + * + * Each virtual swap slot can be backed by: + * + * 1. A slot on a physical swap device (i.e a swapfile or a swap partition= ). + * 2. A swapped out zero-filled page. + * 3. A compressed object in zswap. + * 4. An in-memory folio, that is not backed by neither a physical swap de= vice + * nor zswap (i.e only in swap cache). This is used for pages that are + * rejected by zswap, but not (yet) backed by a physical swap device, + * (for e.g, due to zswap.writeback =3D 0), or for pages that were prev= iously + * stored in zswap, but has since been loaded back into memory (and has= its + * zswap copy invalidated). */ =20 +/* The backing state options of a virtual swap slot */ +enum swap_type { + VSWAP_SWAPFILE, + VSWAP_ZERO, + VSWAP_ZSWAP, + VSWAP_FOLIO +}; + /** * Swap descriptor - metadata of a swapped out page. * * @slot: The handle to the physical swap slot backing this page. * @zswap_entry: The zswap entry associated with this swap slot. - * @swap_cache: The folio in swap cache. + * @swap_cache: The folio in swap cache. If the swap entry backing type is + * VSWAP_FOLIO, the backend is also stored here. * @shadow: The shadow entry. - * @memcgid: The memcg id of the owning memcg, if any. * @swap_count: The number of page table entries that refer to the swap en= try. + * @memcgid: The memcg id of the owning memcg, if any. * @in_swapcache: Whether the swap entry is (about to be) pinned in swap c= ache. + * @type: The backing store type of the swap entry. */ struct swp_desc { - swp_slot_t slot; - struct zswap_entry *zswap_entry; + union { + swp_slot_t slot; + struct zswap_entry *zswap_entry; + }; union { struct folio *swap_cache; void *shadow; @@ -78,10 +105,10 @@ struct swp_desc { unsigned int swap_count; =20 #ifdef CONFIG_MEMCG - unsigned short memcgid; + unsigned short memcgid:16; #endif - - bool in_swapcache; + bool in_swapcache:1; + enum swap_type type:2; }; =20 #define VSWAP_CLUSTER_SHIFT HPAGE_PMD_ORDER @@ -266,15 +293,16 @@ static bool cluster_is_alloc_candidate(struct vswap_c= luster *cluster) return cluster->count + (1 << (cluster->order)) <=3D VSWAP_CLUSTER_SIZE; } =20 -static void __vswap_alloc_from_cluster(struct vswap_cluster *cluster, int = start) +static void __vswap_alloc_from_cluster(struct vswap_cluster *cluster, + int start, struct folio *folio) { int i, nr =3D 1 << cluster->order; struct swp_desc *desc; =20 for (i =3D 0; i < nr; i++) { desc =3D &cluster->descriptors[start + i]; - desc->slot.val =3D 0; - desc->zswap_entry =3D NULL; + desc->type =3D VSWAP_FOLIO; + desc->swap_cache =3D folio; #ifdef CONFIG_MEMCG desc->memcgid =3D 0; #endif @@ -284,7 +312,8 @@ static void __vswap_alloc_from_cluster(struct vswap_clu= ster *cluster, int start) cluster->count +=3D nr; } =20 -static unsigned long vswap_alloc_from_cluster(struct vswap_cluster *cluste= r) +static unsigned long vswap_alloc_from_cluster(struct vswap_cluster *cluste= r, + struct folio *folio) { int nr =3D 1 << cluster->order; unsigned long i =3D cluster->id ? 0 : nr; @@ -303,16 +332,16 @@ static unsigned long vswap_alloc_from_cluster(struct = vswap_cluster *cluster) bitmap_set(cluster->bitmap, i, nr); =20 refcount_add(nr, &cluster->refcnt); - __vswap_alloc_from_cluster(cluster, i); + __vswap_alloc_from_cluster(cluster, i, folio); return i + (cluster->id << VSWAP_CLUSTER_SHIFT); } =20 /* Allocate a contiguous range of virtual swap slots */ -static swp_entry_t vswap_alloc(int order) +static swp_entry_t vswap_alloc(struct folio *folio) { struct xa_limit limit =3D vswap_cluster_map_limit; struct vswap_cluster *local, *cluster; - int nr =3D 1 << order; + int order =3D folio_order(folio), nr =3D 1 << order; bool need_caching =3D true; u32 cluster_id; swp_entry_t entry; @@ -325,7 +354,7 @@ static swp_entry_t vswap_alloc(int order) cluster =3D this_cpu_read(percpu_vswap_cluster.clusters[order]); if (cluster) { spin_lock(&cluster->lock); - entry.val =3D vswap_alloc_from_cluster(cluster); + entry.val =3D vswap_alloc_from_cluster(cluster, folio); need_caching =3D !entry.val; =20 if (!entry.val || !cluster_is_alloc_candidate(cluster)) { @@ -352,7 +381,7 @@ static swp_entry_t vswap_alloc(int order) if (!spin_trylock(&cluster->lock)) continue; =20 - entry.val =3D vswap_alloc_from_cluster(cluster); + entry.val =3D vswap_alloc_from_cluster(cluster, folio); list_del_init(&cluster->list); cluster->full =3D !entry.val || !cluster_is_alloc_candidate(cluster); need_caching =3D !cluster->full; @@ -384,7 +413,7 @@ static swp_entry_t vswap_alloc(int order) if (!cluster_id) entry.val +=3D nr; __vswap_alloc_from_cluster(cluster, - (entry.val & VSWAP_CLUSTER_MASK)); + (entry.val & VSWAP_CLUSTER_MASK), folio); /* Mark the allocated range in the bitmap */ bitmap_set(cluster->bitmap, (entry.val & VSWAP_CLUSTER_MASK), nr); need_caching =3D cluster_is_alloc_candidate(cluster); @@ -497,6 +526,84 @@ void vswap_rmap_set(struct swap_cluster_info *ci, swp_= slot_t slot, __swap_table_set(ci, ci_off + i, vswap ? vswap + i : 0); } =20 +/* + * Caller needs to handle races with other operations themselves. + * + * Specifically, this function is safe to be called in contexts where the = swap + * entry has been added to the swap cache and the associated folio is lock= ed. + * We cannot race with other accessors, and the swap entry is guaranteed t= o be + * valid the whole time (since swap cache implies one refcount). + * + * We cannot assume that the backends will be of the same type, + * contiguous, etc. We might have a large folio coalesced from subpages wi= th + * mixed backend, which is only rectified when it is reclaimed. + */ + static void release_backing(swp_entry_t entry, int nr) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + unsigned long flush_nr, phys_swap_start =3D 0, phys_swap_end =3D 0; + unsigned int phys_swap_type =3D 0; + bool need_flushing_phys_swap =3D false; + swp_slot_t flush_slot; + int i; + + VM_WARN_ON(!entry.val); + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + VM_WARN_ON(!desc); + + /* + * We batch contiguous physical swap slots for more efficient + * freeing. + */ + if (phys_swap_start !=3D phys_swap_end && + (desc->type !=3D VSWAP_SWAPFILE || + swp_slot_type(desc->slot) !=3D phys_swap_type || + swp_slot_offset(desc->slot) !=3D phys_swap_end)) { + need_flushing_phys_swap =3D true; + flush_slot =3D swp_slot(phys_swap_type, phys_swap_start); + flush_nr =3D phys_swap_end - phys_swap_start; + phys_swap_start =3D phys_swap_end =3D 0; + } + + if (desc->type =3D=3D VSWAP_ZSWAP && desc->zswap_entry) { + zswap_entry_free(desc->zswap_entry); + } else if (desc->type =3D=3D VSWAP_SWAPFILE) { + if (!phys_swap_start) { + /* start a new contiguous range of phys swap */ + phys_swap_start =3D swp_slot_offset(desc->slot); + phys_swap_end =3D phys_swap_start + 1; + phys_swap_type =3D swp_slot_type(desc->slot); + } else { + /* extend the current contiguous range of phys swap */ + phys_swap_end++; + } + } + + desc->slot.val =3D 0; + + if (need_flushing_phys_swap) { + spin_unlock(&cluster->lock); + cluster =3D NULL; + swap_slot_free_nr(flush_slot, flush_nr); + need_flushing_phys_swap =3D false; + } + } + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + /* Flush any remaining physical swap range */ + if (phys_swap_start) { + flush_slot =3D swp_slot(phys_swap_type, phys_swap_start); + flush_nr =3D phys_swap_end - phys_swap_start; + swap_slot_free_nr(flush_slot, flush_nr); + } + } + /* * Entered with the cluster locked, but might unlock the cluster. * This is because several operations, such as releasing physical swap slo= ts @@ -516,35 +623,21 @@ void vswap_rmap_set(struct swap_cluster_info *ci, swp= _slot_t slot, static void vswap_free(struct vswap_cluster *cluster, struct swp_desc *des= c, swp_entry_t entry) { - struct zswap_entry *zswap_entry; - swp_slot_t slot; - /* Clear shadow if present */ if (xa_is_value(desc->shadow)) desc->shadow =3D NULL; - - slot =3D desc->slot; - desc->slot.val =3D 0; - - zswap_entry =3D desc->zswap_entry; - if (zswap_entry) { - desc->zswap_entry =3D NULL; - zswap_entry_free(zswap_entry); - } spin_unlock(&cluster->lock); =20 + release_backing(entry, 1); mem_cgroup_uncharge_swap(entry, 1); =20 - if (slot.val) - swap_slot_free_nr(slot, 1); - - spin_lock(&cluster->lock); /* erase forward mapping and release the virtual slot for reallocation */ + spin_lock(&cluster->lock); release_vswap_slot(cluster, entry.val); } =20 /** - * folio_alloc_swap - allocate swap space for a folio. + * folio_alloc_swap - allocate virtual swap space for a folio. * @folio: the folio. * * Return: 0, if the allocation succeeded, -ENOMEM, if the allocation fail= ed. @@ -552,38 +645,77 @@ static void vswap_free(struct vswap_cluster *cluster,= struct swp_desc *desc, int folio_alloc_swap(struct folio *folio) { struct vswap_cluster *cluster =3D NULL; - struct swap_info_struct *si; - struct swap_cluster_info *ci; - int i, nr =3D folio_nr_pages(folio), order =3D folio_order(folio); + int i, nr =3D folio_nr_pages(folio); struct swp_desc *desc; swp_entry_t entry; - swp_slot_t slot; =20 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio); =20 - entry =3D vswap_alloc(folio_order(folio)); + entry =3D vswap_alloc(folio); if (!entry.val) return -ENOMEM; =20 /* - * XXX: for now, we always allocate a physical swap slot for each virtual - * swap slot, and their lifetime are coupled. This will change once we - * decouple virtual swap slots from their backing states, and only alloca= te - * physical swap slots for them on demand (i.e on zswap writeback, or - * fallback from zswap store failure). + * XXX: for now, we charge towards the memory cgroup's swap limit on virt= ual + * swap slots allocation. This will be changed soon - we will only charge= on + * physical swap slots allocation. */ - if (swap_slot_alloc(&slot, order)) { + if (mem_cgroup_try_charge_swap(folio, entry)) { + rcu_read_lock(); for (i =3D 0; i < nr; i++) { desc =3D vswap_iter(&cluster, entry.val + i); VM_WARN_ON(!desc); vswap_free(cluster, desc, (swp_entry_t){ entry.val + i }); } spin_unlock(&cluster->lock); + rcu_read_unlock(); + atomic_add(nr, &vswap_alloc_reject); entry.val =3D 0; return -ENOMEM; } =20 + swap_cache_add_folio(folio, entry, NULL); + + return 0; +} + +/** + * vswap_alloc_swap_slot - allocate physical swap space for a folio that is + * already associated with virtual swap slots. + * @folio: folio we want to allocate physical swap space for. + * + * Note that this does NOT release existing swap backends of the folio. + * Callers need to handle this themselves. + + * Return: true if the folio is now backed by physical swap slots, false + * otherwise. + */ +bool vswap_alloc_swap_slot(struct folio *folio) +{ + int i, nr =3D folio_nr_pages(folio); + struct vswap_cluster *cluster =3D NULL; + struct swap_info_struct *si; + struct swap_cluster_info *ci; + swp_slot_t slot =3D { .val =3D 0 }; + swp_entry_t entry =3D folio->swap; + struct swp_desc *desc; + bool fallback =3D false; + + /* + * We might have already allocated a backing physical swap slot in past + * attempts (for instance, when we disable zswap). If the entire range is + * already swapfile-backed we can skip swapfile case. + */ + if (vswap_swapfile_backed(entry, nr)) + return true; + + if (swap_slot_alloc(&slot, folio_order(folio))) + return false; + + if (!slot.val) + return false; + /* establish the vrtual <-> physical swap slots linkages. */ si =3D __swap_slot_to_info(slot); ci =3D swap_cluster_lock(si, swp_slot_offset(slot)); @@ -595,29 +727,29 @@ int folio_alloc_swap(struct folio *folio) desc =3D vswap_iter(&cluster, entry.val + i); VM_WARN_ON(!desc); =20 + if (desc->type =3D=3D VSWAP_FOLIO) { + /* case 1: fallback from zswap store failure */ + fallback =3D true; + if (!folio) + folio =3D desc->swap_cache; + else + VM_WARN_ON(folio !=3D desc->swap_cache); + } else { + /* + * Case 2: zswap writeback. + * + * No need to free zswap entry here - it will be freed once zswap + * writeback suceeds. + */ + VM_WARN_ON(desc->type !=3D VSWAP_ZSWAP); + VM_WARN_ON(fallback); + } + desc->type =3D VSWAP_SWAPFILE; desc->slot.val =3D slot.val + i; } - if (cluster) - spin_unlock(&cluster->lock); + spin_unlock(&cluster->lock); rcu_read_unlock(); - - /* - * XXX: for now, we charge towards the memory cgroup's swap limit on virt= ual - * swap slots allocation. This is acceptable because as noted above, each - * virtual swap slot corresponds to a physical swap slot. Once we have - * decoupled virtual and physical swap slots, we will only charge when we - * actually allocate a physical swap slot. - */ - if (mem_cgroup_try_charge_swap(folio, entry)) - goto out_free; - - swap_cache_add_folio(folio, entry, NULL); - - return 0; - -out_free: - put_swap_folio(folio, entry); - return -ENOMEM; + return true; } =20 /** @@ -625,7 +757,9 @@ int folio_alloc_swap(struct folio *folio) * virtual swap slot. * @entry: the virtual swap slot. * - * Return: the physical swap slot corresponding to the virtual swap slot. + * Return: the physical swap slot corresponding to the virtual swap slot, = if + * exists, or the zero physical swap slot if the virtual swap slot is not + * backed by any physical slot on a swapfile. */ swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry) { @@ -644,7 +778,10 @@ swp_slot_t swp_entry_to_swp_slot(swp_entry_t entry) return (swp_slot_t){0}; } =20 - slot =3D desc->slot; + if (desc->type !=3D VSWAP_SWAPFILE) + slot.val =3D 0; + else + slot =3D desc->slot; spin_unlock(&cluster->lock); rcu_read_unlock(); =20 @@ -962,6 +1099,293 @@ int non_swapcache_batch(swp_entry_t entry, int max_n= r) return i; } =20 +/** + * vswap_store_folio - set a folio as the backing of a range of virtual sw= ap + * slots. + * @entry: the first virtual swap slot in the range. + * @folio: the folio. + */ +void vswap_store_folio(swp_entry_t entry, struct folio *folio) +{ + struct vswap_cluster *cluster =3D NULL; + int i, nr =3D folio_nr_pages(folio); + struct swp_desc *desc; + + VM_BUG_ON(!folio_test_locked(folio)); + VM_BUG_ON(folio->swap.val !=3D entry.val); + + release_backing(entry, nr); + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + VM_WARN_ON(!desc); + desc->type =3D VSWAP_FOLIO; + desc->swap_cache =3D folio; + } + spin_unlock(&cluster->lock); + rcu_read_unlock(); +} + +/** + * swap_zeromap_folio_set - mark a range of virtual swap slots correspondi= ng to + * a folio as zero-filled. + * @folio: the folio + */ +void swap_zeromap_folio_set(struct folio *folio) +{ + struct obj_cgroup *objcg =3D get_obj_cgroup_from_folio(folio); + struct vswap_cluster *cluster =3D NULL; + swp_entry_t entry =3D folio->swap; + int i, nr =3D folio_nr_pages(folio); + struct swp_desc *desc; + + VM_BUG_ON(!folio_test_locked(folio)); + VM_BUG_ON(!entry.val); + + release_backing(entry, nr); + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + VM_WARN_ON(!desc); + desc->type =3D VSWAP_ZERO; + } + spin_unlock(&cluster->lock); + rcu_read_unlock(); + + count_vm_events(SWPOUT_ZERO, nr); + if (objcg) { + count_objcg_events(objcg, SWPOUT_ZERO, nr); + obj_cgroup_put(objcg); + } +} + +/* + * Iterate through the entire range of virtual swap slots, returning the + * longest contiguous range of slots starting from the first slot that sat= isfies: + * + * 1. If the first slot is zero-mapped, the entire range should be + * zero-mapped. + * 2. If the first slot is backed by a swapfile, the entire range should + * be backed by a range of contiguous swap slots on the same swapfile. + * 3. If the first slot is zswap-backed, the entire range should be + * zswap-backed. + * 4. If the first slot is backed by a folio, the entire range should + * be backed by the same folio. + * + * Note that this check is racy unless we can ensure that the entire range + * has their backing state stable - for instance, if the caller was the one + * who set the swap cache pin. + */ +static int vswap_check_backing(swp_entry_t entry, enum swap_type *type, in= t nr) +{ + unsigned int swapfile_type; + struct vswap_cluster *cluster =3D NULL; + enum swap_type first_type; + struct swp_desc *desc; + pgoff_t first_offset; + struct folio *folio; + int i =3D 0; + + if (!entry.val) + return 0; + + rcu_read_lock(); + for (i =3D 0; i < nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + if (!desc) + goto done; + + if (!i) { + first_type =3D desc->type; + if (first_type =3D=3D VSWAP_SWAPFILE) { + swapfile_type =3D swp_slot_type(desc->slot); + first_offset =3D swp_slot_offset(desc->slot); + } else if (first_type =3D=3D VSWAP_FOLIO) { + folio =3D desc->swap_cache; + } + } else if (desc->type !=3D first_type) { + goto done; + } else if (first_type =3D=3D VSWAP_SWAPFILE && + (swp_slot_type(desc->slot) !=3D swapfile_type || + swp_slot_offset(desc->slot) !=3D first_offset + i)) { + goto done; + } else if (first_type =3D=3D VSWAP_FOLIO && desc->swap_cache !=3D folio)= { + goto done; + } + } +done: + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + if (type) + *type =3D first_type; + return i; +} + +/** + * vswap_swapfile_backed - check if the virtual swap slots are backed by p= hysical + * swap slots. + * @entry: the first entry in the range. + * @nr: the number of entries in the range. + */ +bool vswap_swapfile_backed(swp_entry_t entry, int nr) +{ + enum swap_type type; + + return vswap_check_backing(entry, &type, nr) =3D=3D nr + && type =3D=3D VSWAP_SWAPFILE; +} + +/** + * vswap_folio_backed - check if the virtual swap slots are backed by in-m= emory + * pages. + * @entry: the first virtual swap slot in the range. + * @nr: the number of slots in the range. + */ +bool vswap_folio_backed(swp_entry_t entry, int nr) +{ + enum swap_type type; + + return vswap_check_backing(entry, &type, nr) =3D=3D nr && type =3D=3D VSW= AP_FOLIO; +} + +/** + * vswap_can_swapin_thp - check if the swap entries can be swapped in as a= THP. + * @entry: the first virtual swap slot in the range. + * @nr: the number of slots in the range. + * + * For now, we can only swap in a THP if the entire range is zero-filled, = or if + * the entire range is backed by a contiguous range of physical swap slots= on a + * swapfile. + */ +bool vswap_can_swapin_thp(swp_entry_t entry, int nr) +{ + enum swap_type type; + + return vswap_check_backing(entry, &type, nr) =3D=3D nr && + (type =3D=3D VSWAP_ZERO || type =3D=3D VSWAP_SWAPFILE); +} + +/** + * swap_move - increment the swap slot by delta, checking the backing stat= e and + * return 0 if the backing state does not match (i.e wrong bac= king + * state type, or wrong offset on the backing stores). + * @entry: the original virtual swap slot. + * @delta: the offset to increment the original slot. + * + * Note that this function is racy unless we can pin the backing state of = these + * swap slots down with swapcache_prepare(). + * + * Caller should only rely on this function as a best-effort hint otherwis= e, + * and should double-check after ensuring the whole range is pinned down. + * + * Return: the incremented virtual swap slot if the backing state matches,= or + * 0 if the backing state does not match. + */ +swp_entry_t swap_move(swp_entry_t entry, long delta) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc, *next_desc; + swp_entry_t next_entry; + struct folio *folio =3D NULL, *next_folio =3D NULL; + enum swap_type type, next_type; + swp_slot_t slot =3D {0}, next_slot =3D {0}; + + next_entry.val =3D entry.val + delta; + + rcu_read_lock(); + + /* Look up first descriptor and get its type and backing store */ + desc =3D vswap_iter(&cluster, entry.val); + if (!desc) { + rcu_read_unlock(); + return (swp_entry_t){0}; + } + + type =3D desc->type; + if (type =3D=3D VSWAP_ZSWAP) { + /* zswap not supported for move */ + spin_unlock(&cluster->lock); + rcu_read_unlock(); + return (swp_entry_t){0}; + } + if (type =3D=3D VSWAP_FOLIO) + folio =3D desc->swap_cache; + else if (type =3D=3D VSWAP_SWAPFILE) + slot =3D desc->slot; + + /* Look up second descriptor and get its type and backing store */ + next_desc =3D vswap_iter(&cluster, next_entry.val); + if (!next_desc) { + rcu_read_unlock(); + return (swp_entry_t){0}; + } + + next_type =3D next_desc->type; + if (next_type =3D=3D VSWAP_FOLIO) + next_folio =3D next_desc->swap_cache; + else if (next_type =3D=3D VSWAP_SWAPFILE) + next_slot =3D next_desc->slot; + + if (cluster) + spin_unlock(&cluster->lock); + + rcu_read_unlock(); + + /* Check if types match */ + if (next_type !=3D type) + return (swp_entry_t){0}; + + /* Check backing state consistency */ + if (type =3D=3D VSWAP_SWAPFILE && + (swp_slot_type(next_slot) !=3D swp_slot_type(slot) || + swp_slot_offset(next_slot) !=3D + swp_slot_offset(slot) + delta)) + return (swp_entry_t){0}; + + if (type =3D=3D VSWAP_FOLIO && next_folio !=3D folio) + return (swp_entry_t){0}; + + return next_entry; +} + +/* + * Return the count of contiguous swap entries that share the same + * VSWAP_ZERO status as the starting entry. If is_zeromap is not NULL, + * it will return the VSWAP_ZERO status of the starting entry. + */ +int swap_zeromap_batch(swp_entry_t entry, int max_nr, bool *is_zeromap) +{ + struct vswap_cluster *cluster =3D NULL; + struct swp_desc *desc; + int i =3D 0; + bool is_zero =3D false; + + VM_WARN_ON(!entry.val); + + rcu_read_lock(); + for (i =3D 0; i < max_nr; i++) { + desc =3D vswap_iter(&cluster, entry.val + i); + if (!desc) + goto done; + + if (!i) + is_zero =3D (desc->type =3D=3D VSWAP_ZERO); + else if ((desc->type =3D=3D VSWAP_ZERO) !=3D is_zero) + goto done; + } +done: + if (cluster) + spin_unlock(&cluster->lock); + rcu_read_unlock(); + if (i && is_zeromap) + *is_zeromap =3D is_zero; + + return i; +} + /** * free_swap_and_cache_nr() - Release a swap count on range of swap entrie= s and * reclaim their cache if no more references re= main. @@ -1028,11 +1452,6 @@ bool tryget_swap_entry(swp_entry_t entry, struct swa= p_info_struct **si) struct vswap_cluster *cluster; swp_slot_t slot; =20 - slot =3D swp_entry_to_swp_slot(entry); - *si =3D swap_slot_tryget_swap_info(slot); - if (!*si) - return false; - /* * Ensure the cluster and its associated data structures (swap cache etc.) * remain valid. @@ -1041,11 +1460,30 @@ bool tryget_swap_entry(swp_entry_t entry, struct sw= ap_info_struct **si) cluster =3D xa_load(&vswap_cluster_map, VSWAP_CLUSTER_IDX(entry)); if (!cluster || !refcount_inc_not_zero(&cluster->refcnt)) { rcu_read_unlock(); - swap_slot_put_swap_info(*si); *si =3D NULL; return false; } rcu_read_unlock(); + + slot =3D swp_entry_to_swp_slot(entry); + /* + * Note that this function does not provide any guarantee that the virtual + * swap slot's backing state will be stable. This has several implication= s: + * + * 1. We have to obtain a reference to the swap device itself, because we + * need swap device's metadata in certain scenarios, for example when we + * need to inspect the swap device flag in do_swap_page(). + * + * 2. The swap device we are looking up here might be outdated by the tim= e we + * return to the caller. It is perfectly OK, if the swap_info_struct is o= nly + * used in a best-effort manner (i.e optimization). If we need the precise + * backing state, we need to re-check after the entry is pinned in swapca= che. + */ + if (slot.val) + *si =3D swap_slot_tryget_swap_info(slot); + else + *si =3D NULL; + return true; } =20 @@ -1288,7 +1726,7 @@ void swap_cache_add_folio(struct folio *folio, swp_en= try_t entry, void **shadowp old =3D desc->shadow; =20 /* Warn if slot is already occupied by a folio */ - VM_WARN_ON_FOLIO(old && !xa_is_value(old), folio); + VM_WARN_ON_FOLIO(old && !xa_is_value(old) && old !=3D folio, folio); =20 /* Save shadow if found and not yet saved */ if (shadowp && xa_is_value(old) && !*shadowp) @@ -1415,29 +1853,22 @@ void __swap_cache_replace_folio(struct folio *old, = struct folio *new) * @entry: the zswap entry to store * * Stores a zswap entry in the swap descriptor for the given swap entry. - * The cluster is locked during the store operation. - * - * Return: the old zswap entry if one existed, NULL otherwise + * Releases the old backend if one existed. */ -void *zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry) +void zswap_entry_store(swp_entry_t swpentry, struct zswap_entry *entry) { struct vswap_cluster *cluster =3D NULL; struct swp_desc *desc; - void *old; + + release_backing(swpentry, 1); =20 rcu_read_lock(); desc =3D vswap_iter(&cluster, swpentry.val); - if (!desc) { - rcu_read_unlock(); - return NULL; - } - - old =3D desc->zswap_entry; + VM_WARN_ON(!desc); desc->zswap_entry =3D entry; + desc->type =3D VSWAP_ZSWAP; spin_unlock(&cluster->lock); rcu_read_unlock(); - - return old; } =20 /** @@ -1452,6 +1883,7 @@ void *zswap_entry_load(swp_entry_t swpentry) { struct vswap_cluster *cluster =3D NULL; struct swp_desc *desc; + enum swap_type type; void *zswap_entry; =20 rcu_read_lock(); @@ -1461,41 +1893,15 @@ void *zswap_entry_load(swp_entry_t swpentry) return NULL; } =20 + type =3D desc->type; zswap_entry =3D desc->zswap_entry; spin_unlock(&cluster->lock); rcu_read_unlock(); =20 - return zswap_entry; -} - -/** - * zswap_entry_erase - erase a zswap entry for a swap entry - * @swpentry: the swap entry - * - * Erases the zswap entry from the swap descriptor for the given swap entr= y. - * The cluster is locked during the erase operation. - * - * Return: the zswap entry that was erased, NULL if none existed - */ -void *zswap_entry_erase(swp_entry_t swpentry) -{ - struct vswap_cluster *cluster =3D NULL; - struct swp_desc *desc; - void *old; - - rcu_read_lock(); - desc =3D vswap_iter(&cluster, swpentry.val); - if (!desc) { - rcu_read_unlock(); + if (type !=3D VSWAP_ZSWAP) return NULL; - } =20 - old =3D desc->zswap_entry; - desc->zswap_entry =3D NULL; - spin_unlock(&cluster->lock); - rcu_read_unlock(); - - return old; + return zswap_entry; } =20 bool zswap_empty(swp_entry_t swpentry) diff --git a/mm/zswap.c b/mm/zswap.c index e46349f9c90bb..c5e1d252cb463 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -991,8 +991,9 @@ static int zswap_writeback_entry(struct zswap_entry *en= try, { struct folio *folio; struct mempolicy *mpol; - bool folio_was_allocated; + bool folio_was_allocated, phys_swap_alloced =3D false; struct swap_info_struct *si; + struct zswap_entry *new_entry =3D NULL; int ret =3D 0; =20 /* try to allocate swap cache folio */ @@ -1027,18 +1028,23 @@ static int zswap_writeback_entry(struct zswap_entry= *entry, * old compressed data. Only when this is successful can the entry * be dereferenced. */ - if (entry !=3D zswap_entry_load(swpentry)) { + new_entry =3D zswap_entry_load(swpentry); + if (entry !=3D new_entry) { ret =3D -ENOMEM; goto out; } =20 + if (!vswap_alloc_swap_slot(folio)) { + ret =3D -ENOMEM; + goto out; + } + phys_swap_alloced =3D true; + if (!zswap_decompress(entry, folio)) { ret =3D -EIO; goto out; } =20 - zswap_entry_erase(swpentry); - count_vm_event(ZSWPWB); if (entry->objcg) count_objcg_events(entry->objcg, ZSWPWB, 1); @@ -1056,6 +1062,8 @@ static int zswap_writeback_entry(struct zswap_entry *= entry, =20 out: if (ret && ret !=3D -EEXIST) { + if (phys_swap_alloced) + zswap_entry_store(swpentry, new_entry); swap_cache_del_folio(folio); folio_unlock(folio); } @@ -1401,7 +1409,7 @@ static bool zswap_store_page(struct page *page, struct zswap_pool *pool) { swp_entry_t page_swpentry =3D page_swap_entry(page); - struct zswap_entry *entry, *old; + struct zswap_entry *entry; =20 /* allocate entry */ entry =3D zswap_entry_cache_alloc(GFP_KERNEL, page_to_nid(page)); @@ -1413,15 +1421,12 @@ static bool zswap_store_page(struct page *page, if (!zswap_compress(page, entry, pool)) goto compress_failed; =20 - old =3D zswap_entry_store(page_swpentry, entry); - /* * We may have had an existing entry that became stale when * the folio was redirtied and now the new version is being - * swapped out. Get rid of the old. + * swapped out. zswap_entry_store() will get rid of the old. */ - if (old) - zswap_entry_free(old); + zswap_entry_store(page_swpentry, entry); =20 /* * The entry is successfully compressed and stored in the tree, there is @@ -1533,18 +1538,13 @@ bool zswap_store(struct folio *folio) * the possibly stale entries which were previously stored at the * offsets corresponding to each page of the folio. Otherwise, * writeback could overwrite the new data in the swapfile. + * + * The only exception is if we still have a full contiguous + * range of physical swap slots backing the folio. Keep them for + * fallback disk swapping. */ - if (!ret) { - unsigned type =3D swp_type(swp); - pgoff_t offset =3D swp_offset(swp); - struct zswap_entry *entry; - - for (index =3D 0; index < nr_pages; ++index) { - entry =3D zswap_entry_erase(swp_entry(type, offset + index)); - if (entry) - zswap_entry_free(entry); - } - } + if (!ret && !vswap_swapfile_backed(swp, nr_pages)) + vswap_store_folio(swp, folio); =20 return ret; } @@ -1619,8 +1619,7 @@ int zswap_load(struct folio *folio) */ if (swapcache) { folio_mark_dirty(folio); - zswap_entry_erase(swp); - zswap_entry_free(entry); + vswap_store_folio(swp, folio); } =20 folio_unlock(folio); --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oo1-f42.google.com (mail-oo1-f42.google.com [209.85.161.42]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1219034321C for ; Sun, 8 Feb 2026 21:59:14 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.161.42 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587955; cv=none; b=cW9J8TXdx7jM8/z4CmaXZK3hE8oA2L8Wf6A9HG54k7GePcWouIwhOjHeqdkRv2cIwRSNGCRWCISI/HNORECL2quB+VBKtAf0fO+suRHWF9Aj5LrtlqXPpk2ULFstAe7UiiwVZW4pShaUKeHZ6Pb4gh5jZ03yKwstUoXnUlpkglY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587955; c=relaxed/simple; bh=XBmrk0o39FAOIaDvlicMy3Eh3cFwDg1bVSNwmZISXsU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=QDlHrOUug9yemeUESjCB61VO/S8xd32k+WUUPfwySot3QsFfAOPx/1/MnXTG9BlkToD9cgFKMRX7nnH+BtiPBWWV/ZvCvXG/hvH2BMvS0h6VMKnp1txZLN19cvBLsotnhv03SujOzukEQKksTtrQsOq2pAcWLNaG+ScVYhMb9ug= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=FfpipKKC; arc=none smtp.client-ip=209.85.161.42 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.b="FfpipKKC" Received: by mail-oo1-f42.google.com with SMTP id 006d021491bc7-662f5c5507cso2560559eaf.3 for ; Sun, 08 Feb 2026 13:59:14 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587954; x=1771192754; 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; bh=7QY06q/ir2j1hW+S2SjYAeivUq/qdnGKxDWe/px5J+A=; b=FfpipKKCVpCqx7HM3BYiH/RMENXLSiIR/koRgxvzc0aEp5P9xmN9glHJwl8q2XaKHZ dcckmxhxAPICg0IQe3X0r4r8iUR4Xuz/gGZ33/nZ7uTyUCFjtF1TO+0JlCTXC6YxGM1/ WVqJtenzA4TS0JTlwjdQD+dj48Gerb4OgoMt1Dx6J4arQkRjDZGjwUSPbdHPwYjzXftz Z76+33cpHzq2aWrLh2jFkYDNSA+ocGivVuBHJZc0tdR7ob3swV1fECOPqZ8fFdTUShpZ QuZz+vjdwRZGV2kzem/qq0xI+RfM6dQtbWW2XIp43UGUwWpjiLyTVJlQEMQbrvSknzLT q13Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587954; x=1771192754; 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; bh=7QY06q/ir2j1hW+S2SjYAeivUq/qdnGKxDWe/px5J+A=; b=sbuucBbgy8zHhE+JtNd7wWNXdlqED7UXcce4X/Vjbtt3TybRZJJIqO42cVHe0Kqrn+ j8Q3irf5guyIL9yylekYT/9nwcFP/Y3K9Ue5GkvfKE2RSKznSbOKbiIZKzd8hn6QBQd2 xB4MpR9xOTs2qVU5RAfykNSEvUqmM9SENH+f/EcP3W6zYCjtncF2rgrI7uFGp8K52Byw 6rPOb9bT7Nq7NuhG9HXBQV/shNcXXg1gqZH1JiDIlLm4vbpq+hH3UjgkikYxSc33cvLH waOo9h4XPE2a0U2H8XfVP+Du9kFFVxnRNonyVMLJZDGTToIMoksVNA+S1vUTdy8NWVQZ i+AA== X-Forwarded-Encrypted: i=1; AJvYcCXi6V/w+n4ilJ2U5IPge/easaDlKED2bRRYAYVkpxdS/V1gv0y4V1ogdT94aliILjNGjsSfCWfMhCBasuk=@vger.kernel.org X-Gm-Message-State: AOJu0Yys4Zu911XvckWpASHRyXmwFI17foj86jT1LWENkg7jsODqYHLF n5VWT6hr97Uf2oVIA011ywmlPxnSOwFCu8z8xnQfcKok3htIqQfdWoM4 X-Gm-Gg: AZuq6aLcnP65hEyoiIgiKcbRz457knE/69JCgBz+inpBBjc5lfxyv/2SLY5djB8GcAS sX+APa9m/a96irQsB5hZdwnJkYjlvdbdq0r0bByHQIwj1U6GBomlXXEbyzbge76uwx1wGAOoUnx gg9TtSg/fKxWaaysgXu6KBv5CfA142iBRKE1ABcW5t+x2Fpd8AXx4g240+/sYMyzb7sszgZAYS5 rzaoWriGBaTIJRw6x3my2g38zQCftZSwcVVDm3C8hVDBDIplUJUpkp7d0YDnumDxVtH/w6B/vas qm7VviAQLOKNRwGfO/hA6Ukvk+EA56jk9YYJBqdHXHIHmm6nOYbwLWUqVe/AnI+WQBvdT/hxwMe 7Okv6amOJz1tZLFH5Qm9/gbCKPDm0tWJOASRxin+V2KzsiFm7OSm+S5RNs8+XZKIVpiFeti6c2b rWdQugGS3l2K+sIb1egLWIFwHNiBnq3Eo73tCnR0EYyRo= X-Received: by 2002:a05:6820:16a6:b0:659:9a49:8f50 with SMTP id 006d021491bc7-66d32bfa23emr4293572eaf.21.1770587954007; Sun, 08 Feb 2026 13:59:14 -0800 (PST) Received: from localhost ([2a03:2880:10ff:8::]) by smtp.gmail.com with ESMTPSA id 006d021491bc7-66d391ae639sm4737086eaf.7.2026.02.08.13.59.11 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:12 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 15/20] zswap: do not start zswap shrinker if there is no physical swap slots Date: Sun, 8 Feb 2026 13:58:28 -0800 Message-ID: <20260208215839.87595-16-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" When swap is virtualized, we no longer pre-allocate a slot on swapfile for each zswap entry. Do not start the zswap shrinker if there is no physical swap slots available. Signed-off-by: Nhat Pham --- mm/zswap.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/mm/zswap.c b/mm/zswap.c index c5e1d252cb463..9d1822753d321 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -1211,6 +1211,14 @@ static unsigned long zswap_shrinker_count(struct shr= inker *shrinker, if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg)) return 0; =20 + /* + * When swap is virtualized, we do not have any swap slots on swapfile + * preallocated for zswap objects. If there is no slot available, we + * cannot writeback and should just bail out here. + */ + if (!get_nr_swap_pages()) + return 0; + /* * The shrinker resumes swap writeback, which will enter block * and may enter fs. XXX: Harmonize with vmscan.c __GFP_FS --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oi1-f177.google.com (mail-oi1-f177.google.com [209.85.167.177]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 528793624A6 for ; Sun, 8 Feb 2026 21:59:16 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587956; cv=none; b=Jl/qEwpzcsyr8UzFIWKZc9JvSKW0cnaU7BfZ+hTEcnyldnvC13MRDo39Jo/IJ4NGXC/HUWp1z6HiCv9dXrUAgwogubX/IKzgPsjKp44Zo8Wf0GWFlO7aYGLHtqMuzSAaxDBPmd3HItGpLkVQ/F2RJO9+u6eDPoc8x49dKzF52vc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587956; c=relaxed/simple; bh=ivEurp8BxVVC73UF2YIA0sGKcn4Rvv3bpTlATH+RAvk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=mQLPf993TaCUR8DmoeO3Fz4xHRVlttsGmPkr/xCxyUVaqAtC9SQMmxJw3ZOvidMT/5SSWrmoyHAfv7xnj9mi5E9s9BWzzSCgUMDla+r0lxKEIr1/Sr+OsKhi3ahDMkk/cuc0YVZEgyLysxDegzcmCUorDeRjBiGK1J3/PgEs6rM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=dc+40F81; arc=none smtp.client-ip=209.85.167.177 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.b="dc+40F81" Received: by mail-oi1-f177.google.com with SMTP id 5614622812f47-45f171cb842so2677473b6e.1 for ; Sun, 08 Feb 2026 13:59:16 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587955; x=1771192755; 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; bh=Jcq3gcBJps8FZtjddhB+nxOnBeH87BfFsdWVB5x664k=; b=dc+40F81wBkKVyu/C1B8+cc6caEzLYJpuLJ5W1W7TCSfYcL1XO+XOyilRv9LlWonXn 35OOuT+QXQwaq/ALiu5BGgNmHiH4aHE1ssRQ/wuGyDbuYl8OjY7NbztQKhaua5sfltdo nmO6h++U9Ff/Bh4Vz4432XeartFzGtpqOWE5AILXz9GTAHyY96PfJHcp/pbPa5W7R3we bepL9sYvx5RYKRzzm3zfgHPmkK2NSfPGLr15A/g4gPdNT+0qMSaxtuLX2Bo57nZWLgLg 0kA67K/WKPLEY6Oys0CBHHMbmT3EwDh3UQXzktcSbFe+ZSwRMVDQlHH5sGZw+JYExWfU lpsQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587955; x=1771192755; 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; bh=Jcq3gcBJps8FZtjddhB+nxOnBeH87BfFsdWVB5x664k=; b=XRL2RFQDMCZor2ykDkDyUrWkOyUWMzugp7CLpALMdEU0WaR4mZgBH69+dx+QZb2XVT /1q3xDowM8JvzEYG+tOmp3p5Mar0YoBGbfTKfkEEFZhAee9WgQoOjY5B09OpbJKjNIY6 r9hYp+RU5CYR2Gzs1vTFQYTtsgprDMGrGAAt3tTCJH1SAa8bUgtz2exZwYWJgtfFNXwc Bp5hJjrPo0MlBItRZ6d/MOpKtIpc6Hafgff5HOJKG/jHLqOXj5SrcUjo03GmZw+2ce8Z G/8tZ7tAdYf8IqhLfP1sz4gZ8E0F/jbUUKu50Jj1jtVo4/vLTffHOkRmeI3vdGRjVQby 0g9w== X-Forwarded-Encrypted: i=1; AJvYcCVW2X75cy3qT+usbFCmuUvW7Ys1VCzMFHu2ILJYTd4VMGGKeXce81h+oiz/4ey75FP+++94DdSvoZVMBO8=@vger.kernel.org X-Gm-Message-State: AOJu0Yy6tgDyxtx9Re++RM8fo018PZh7O5h6KvTsLgfKXvUapdTcd4d9 nANqZ1esi6GKdUq4k/XxGM9f5gDcCsoNEaK6kdfQWi0+ElHeYzWwCUET X-Gm-Gg: AZuq6aIQ/rRwGQSx0jtpGRL4Ghl5t/5HWnBrRWUwoqTx2KPKA9p9EIbvsGIiz/DU4XR x2T1hVS8R2KvcDloKSZh5EV7MWgraztYu6Kqi52T2uB5J4O2gvWvULJpvlNw6Zwlj9Z7Ban4Xsh aHbgkF7NeCMxkmGPWnOOKCfH86trMk9m+qTHz9PgULo8xo3xQo4w6mtRW+AJbLAq6PAvJn/N8Qh qX87S9XkvDWo4QLOP38J2HTbtHrSlZmmBy+QXCBI/ZfAsTZjuvbP2N4coclnfhddVPEcRLobOs/ d2BULp1+hp8hJiVIXf9oC2Gt1mi7sOtirZ6mGj/aQMOLLe6IR1BfZeOaxkML+iV+w2xXoFgoVRO 23Lr16qlmrN5sodHElP2p7I+foxKkJCqsUeQX9hYEVoaoyRSFOftKiwMCv/Hk/YODm7wkQfBN8D olmdwNjYrl5qLuGn0C1g58W3cTSnZseZPm X-Received: by 2002:a05:6808:2220:b0:45f:103c:2483 with SMTP id 5614622812f47-462fcbe429bmr4183659b6e.23.1770587955253; Sun, 08 Feb 2026 13:59:15 -0800 (PST) Received: from localhost ([2a03:2880:10ff:5::]) by smtp.gmail.com with ESMTPSA id 5614622812f47-462fe9a12f5sm5510710b6e.5.2026.02.08.13.59.14 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:14 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 16/20] swap: do not unnecesarily pin readahead swap entries Date: Sun, 8 Feb 2026 13:58:29 -0800 Message-ID: <20260208215839.87595-17-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" When we perform swap readahead, the target entry is already pinned by the caller. No need to pin swap entries in the readahead window that belongs in the same virtual swap cluster as the target swap entry. Signed-off-by: Nhat Pham --- mm/swap.h | 1 + mm/swap_state.c | 22 +++++++++------------- mm/vswap.c | 10 ++++++++++ 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/mm/swap.h b/mm/swap.h index d41e6a0e70753..08a6369a6dfad 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -213,6 +213,7 @@ void swap_cache_lock(swp_entry_t entry); void swap_cache_unlock(swp_entry_t entry); void vswap_rmap_set(struct swap_cluster_info *ci, swp_slot_t slot, unsigned long vswap, int nr); +bool vswap_same_cluster(swp_entry_t entry1, swp_entry_t entry2); =20 static inline struct address_space *swap_address_space(swp_entry_t entry) { diff --git a/mm/swap_state.c b/mm/swap_state.c index ad80bf098b63f..e8e0905c7723f 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -553,22 +553,18 @@ static struct folio *swap_vma_readahead(swp_entry_t t= arg_entry, gfp_t gfp_mask, pte_unmap(pte); pte =3D NULL; /* - * Readahead entry may come from a device that we are not - * holding a reference to, try to grab a reference, or skip. - * - * XXX: for now, always try to pin the swap entries in the - * readahead window to avoid the annoying conversion to physical - * swap slots. Once we move all swap metadata to virtual swap - * layer, we can simply compare the clusters of the target - * swap entry and the current swap entry, and pin the latter - * swap entry's cluster if it differ from the former's. + * The target entry is already pinned - if the readahead entry + * belongs to the same cluster, it's already protected. */ - swapoff_locked =3D tryget_swap_entry(entry, &si); - if (!swapoff_locked) - continue; + if (!vswap_same_cluster(entry, targ_entry)) { + swapoff_locked =3D tryget_swap_entry(entry, &si); + if (!swapoff_locked) + continue; + } folio =3D __read_swap_cache_async(entry, gfp_mask, mpol, ilx, &page_allocated, false); - put_swap_entry(entry, si); + if (swapoff_locked) + put_swap_entry(entry, si); if (!folio) continue; if (page_allocated) { diff --git a/mm/vswap.c b/mm/vswap.c index fb6179ce3ace7..7563107eb8eee 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -1503,6 +1503,16 @@ void put_swap_entry(swp_entry_t entry, struct swap_i= nfo_struct *si) rcu_read_unlock(); } =20 +/* + * Check if two virtual swap entries belong to the same vswap cluster. + * Useful for optimizing readahead when entries in the same cluster + * share protection from a pinned target entry. + */ +bool vswap_same_cluster(swp_entry_t entry1, swp_entry_t entry2) +{ + return VSWAP_CLUSTER_IDX(entry1) =3D=3D VSWAP_CLUSTER_IDX(entry2); +} + static int vswap_cpu_dead(unsigned int cpu) { struct percpu_vswap_cluster *percpu_cluster; --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oa1-f50.google.com (mail-oa1-f50.google.com [209.85.160.50]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5659934321C for ; Sun, 8 Feb 2026 21:59:18 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.50 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587958; cv=none; b=p15yoEXhPubAP6dVFGONsOIw8+gvt/pKNCvRs647POaUDZxYlx51qT3KdJD9XNwgAuNxpodJDq+FoyJQuvLyDSdTRgvXe2EBVWzCyQGTfhOEn83Cb6lNaeqsit5lyrjfmHTPGxLaediFQTyy2w+nX9wOleuR6ScJsQK89ltts/U= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587958; c=relaxed/simple; bh=dR6T7pstuCqgQMWtQrm6D0fc/evHR/Uw+D+DUpIeiPM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=mE57AJ1YfgjbDkItBMzbV90MRn4+FIruuIakja/FWJRi6i//61b6k1jhrF0eIPq4wbKpEvz+g2W2DR0QoR4jLAIzFXRFg6egGdnczf96dzmjQZ2i6xFgR+gG4//El/Zpqfh6oTuHfLFM3eetnhnR4NUhR+V0z/wXj/pQ/V26vaU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=lzHchwVW; arc=none smtp.client-ip=209.85.160.50 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.b="lzHchwVW" Received: by mail-oa1-f50.google.com with SMTP id 586e51a60fabf-40946982a78so1137428fac.2 for ; Sun, 08 Feb 2026 13:59:18 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587957; x=1771192757; 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; bh=YdV+3Aw+NBxu35sOMXTrxQg3lkskWJESSW2tnr6DOts=; b=lzHchwVWFMR2YvvnlatYNHmu3ebjPVTNwwZPPQphTmGW23av5KikGiUs1o/3rV9WGO vksiQcQLj0hAK6iJcZnzS9z7dNDYqPu2sklav/1GkeYOf7JROb2dw7VM9w6kHW28T+5R rwkTuUHJ19VLOqqk8z75KuiP07FXVdnWuNokU5wFN7tl6eD0h1Ay3NCrrgZSADVOavT3 8JHns1bkH2OvI2s5lZ4/hO2PnNT2qhh4gO4Y0sBszefECiMQrlax4sx10yLo9puoT9Ym k53yV1iJt8EF2zmLHYBi3IoSk2JVxAxVMuDYehiJ0gLgU40FTztW4zVP8RpYcX7vw2FD IDtA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587957; x=1771192757; 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; bh=YdV+3Aw+NBxu35sOMXTrxQg3lkskWJESSW2tnr6DOts=; b=fXIM3SHTxmikzkTmJJ6J5QCIImzYPP1KaTMWLi9yeZWxYgeKBTqoa+JG4gjGtG3Xe3 gRMiE9vHObZcZ1b04o6ugq2piIdvmtfVx/zfWoPTkgkIFOJqQvyxISMIe0L7GPrQU13u eA2jhq3wNLrThybDGAjfeN+4Mt67SUm87KUEhwY6hRu3tesbfV+tBYDnML/e9CMibHSC 86iun0yUA9aPg8nkgBR8mVHhFRYJe6WxoflOSE252LlPPt9WtXw5bLrBYX7olR8XDHkS yn6/wsdi/W/APa+z/E+3eDnP6ydJXAr5pCKg2NsqWQ74XnkSOq4bnaqWbpd/gLDKHTV2 AT/Q== X-Forwarded-Encrypted: i=1; AJvYcCWaZwuxoK1ce+/Q2hQxKvyLfAE/Rj2QUSwfzn2zX0J2GCDVZg58bWdWHvx+rUO/JeYtTh3gtguR/6Y2nT0=@vger.kernel.org X-Gm-Message-State: AOJu0YxSHTRIeDhBa/LpWe0Rot+ESEwJjGq0AKzLuZ0X7Nl5+0Hlhroh s68nWD8eG8igrcay5PE5s6DOa4mVt1l2YaWMpxyLDxOEFMEK01x+fcNxc6v/Zg== X-Gm-Gg: AZuq6aLCGZEN2DQ16NymrHkmqViw+WCS5c/XLhLjAWE1veJz3Jzu2z5Hk7lCK8K8ed+ HDP8CtNWDsC820ryYoXS6bFOPsqvGI+VX8MWE+J3cMkFmVzjqhhChTUc4Qfh7hofTwFU6k0xNp8 gr5p2M6HAymfL8tiOYQnUtD1Pz7+rPgBqqklLAyHYA2cr9l2sGqXAp1bqAzv/MCbTnYGYmi4+EC jT4SHAY4psYVl9ER5Yl96qnCE04mwX7jNN0M917UotsEpbuo9LAW/cQan+J5lCGj9SYafGT0meH oMcY5BMRd5vtSuPqLzEs19XalSM8KVeYbWh/ZuOHn8V7xay0psNFiIVEykYl+6dlJM/VHAIWMA5 QpP9vmxt7Z0kfBiZL8hOiQlzqpQBrCdj4ncwbi2IDP5dAhj4gc89ZI24jfCGacgwFCddG7AGX7x v30asgmDLRqdfKpGgGwl9+k1XhNZyHS9/V7/nh9kp7UtE= X-Received: by 2002:a05:6870:829e:b0:332:8989:4ef8 with SMTP id 586e51a60fabf-40a96ec6c37mr4495223fac.31.1770587957178; Sun, 08 Feb 2026 13:59:17 -0800 (PST) Received: from localhost ([2a03:2880:10ff:3::]) by smtp.gmail.com with ESMTPSA id 586e51a60fabf-40a99355b7fsm6268799fac.8.2026.02.08.13.59.15 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:16 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 17/20] swapfile: remove zeromap bitmap Date: Sun, 8 Feb 2026 13:58:30 -0800 Message-ID: <20260208215839.87595-18-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Zero swap entries are now treated as a separate, decoupled backend in the virtual swap layer. The zeromap bitmap of physical swapfile is no longer used - remove it. This does not have any behavioral change, and save 1 bit per swap page in terms of memory overhead. Signed-off-by: Nhat Pham --- include/linux/swap.h | 1 - mm/swapfile.c | 30 +++++------------------------- 2 files changed, 5 insertions(+), 26 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 54df972608047..9cd45eab313f8 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -260,7 +260,6 @@ struct swap_info_struct { signed char type; /* strange name for an index */ unsigned int max; /* extent of the swap_map */ unsigned char *swap_map; /* vmalloc'ed array of usage counts */ - unsigned long *zeromap; /* kvmalloc'ed bitmap to track zero pages */ struct swap_cluster_info *cluster_info; /* cluster info. Only for SSD */ struct list_head free_clusters; /* free clusters list */ struct list_head full_clusters; /* full clusters list */ diff --git a/mm/swapfile.c b/mm/swapfile.c index 1aa29dd220f9a..e1cb01b821ff3 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -2317,8 +2317,7 @@ static int setup_swap_extents(struct swap_info_struct= *sis, sector_t *span) =20 static void setup_swap_info(struct swap_info_struct *si, int prio, unsigned char *swap_map, - struct swap_cluster_info *cluster_info, - unsigned long *zeromap) + struct swap_cluster_info *cluster_info) { si->prio =3D prio; /* @@ -2329,7 +2328,6 @@ static void setup_swap_info(struct swap_info_struct *= si, int prio, si->avail_list.prio =3D -si->prio; si->swap_map =3D swap_map; si->cluster_info =3D cluster_info; - si->zeromap =3D zeromap; } =20 static void _enable_swap_info(struct swap_info_struct *si) @@ -2347,12 +2345,11 @@ static void _enable_swap_info(struct swap_info_stru= ct *si) =20 static void enable_swap_info(struct swap_info_struct *si, int prio, unsigned char *swap_map, - struct swap_cluster_info *cluster_info, - unsigned long *zeromap) + struct swap_cluster_info *cluster_info) { spin_lock(&swap_lock); spin_lock(&si->lock); - setup_swap_info(si, prio, swap_map, cluster_info, zeromap); + setup_swap_info(si, prio, swap_map, cluster_info); spin_unlock(&si->lock); spin_unlock(&swap_lock); /* @@ -2370,7 +2367,7 @@ static void reinsert_swap_info(struct swap_info_struc= t *si) { spin_lock(&swap_lock); spin_lock(&si->lock); - setup_swap_info(si, si->prio, si->swap_map, si->cluster_info, si->zeromap= ); + setup_swap_info(si, si->prio, si->swap_map, si->cluster_info); _enable_swap_info(si); spin_unlock(&si->lock); spin_unlock(&swap_lock); @@ -2441,7 +2438,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) { struct swap_info_struct *p =3D NULL; unsigned char *swap_map; - unsigned long *zeromap; struct swap_cluster_info *cluster_info; struct file *swap_file, *victim; struct address_space *mapping; @@ -2536,8 +2532,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) p->swap_file =3D NULL; swap_map =3D p->swap_map; p->swap_map =3D NULL; - zeromap =3D p->zeromap; - p->zeromap =3D NULL; maxpages =3D p->max; cluster_info =3D p->cluster_info; p->max =3D 0; @@ -2549,7 +2543,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) kfree(p->global_cluster); p->global_cluster =3D NULL; vfree(swap_map); - kvfree(zeromap); free_cluster_info(cluster_info, maxpages); =20 inode =3D mapping->host; @@ -3013,7 +3006,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) sector_t span; unsigned long maxpages; unsigned char *swap_map =3D NULL; - unsigned long *zeromap =3D NULL; struct swap_cluster_info *cluster_info =3D NULL; struct folio *folio =3D NULL; struct inode *inode =3D NULL; @@ -3119,17 +3111,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, special= file, int, swap_flags) if (error) goto bad_swap_unlock_inode; =20 - /* - * Use kvmalloc_array instead of bitmap_zalloc as the allocation order mi= ght - * be above MAX_PAGE_ORDER incase of a large swap file. - */ - zeromap =3D kvmalloc_array(BITS_TO_LONGS(maxpages), sizeof(long), - GFP_KERNEL | __GFP_ZERO); - if (!zeromap) { - error =3D -ENOMEM; - goto bad_swap_unlock_inode; - } - if (si->bdev && bdev_stable_writes(si->bdev)) si->flags |=3D SWP_STABLE_WRITES; =20 @@ -3196,7 +3177,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) prio =3D DEF_SWAP_PRIO; if (swap_flags & SWAP_FLAG_PREFER) prio =3D swap_flags & SWAP_FLAG_PRIO_MASK; - enable_swap_info(si, prio, swap_map, cluster_info, zeromap); + enable_swap_info(si, prio, swap_map, cluster_info); =20 pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s= %s%s\n", K(si->pages), name->name, si->prio, nr_extents, @@ -3224,7 +3205,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) si->flags =3D 0; spin_unlock(&swap_lock); vfree(swap_map); - kvfree(zeromap); if (cluster_info) free_cluster_info(cluster_info, maxpages); if (inced_nr_rotate_swap) --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oi1-f169.google.com (mail-oi1-f169.google.com [209.85.167.169]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2CA373783A1 for ; Sun, 8 Feb 2026 21:59:21 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.169 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587961; cv=none; b=gKzcFgyVVGMVp7kJ5EeYgiwLrmy/cNoMdhlSn/9AY/IqmO2Du3+zndlmgvRsx06joKTU2+smNBAE9W/7f5eRpNaj4xHviOVoEL6cJg0oS2QILAPI33JVYT4aDHww1F31SPsCSIl6sSaSAq9oG/byjJb9/CtVpOYNc4nRu4vxfxo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587961; c=relaxed/simple; bh=/ca3nyTvcSF3Q5evcfrzx/MRu40Tc4y2RvBcpmh2s4c=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=G1mmZg4ygl2483KnSrx/UQCrEUyxKoIXfoCrmUGbT19miM+kXZoYTA8VEGDukorGQSUPaHxtdZX6MkrOMbTeRpweVHpXHkqAKNH+9MsNmXiKdNOvYJXOkxGxQvvyVC95EjdGo15T1S6Kamvg7K8TJVII/Uc5dsko8+2m8KddPNo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=B7j6AO8Y; arc=none smtp.client-ip=209.85.167.169 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.b="B7j6AO8Y" Received: by mail-oi1-f169.google.com with SMTP id 5614622812f47-45efe81556fso2601754b6e.2 for ; Sun, 08 Feb 2026 13:59:21 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587960; x=1771192760; 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; bh=dEUe6oTCoBFfM+Sx9vNYCw5ijDc8cAJk/jm6jmf+e+o=; b=B7j6AO8YN9leB9k7DzO8rSMj68ziEmpr37BWYkEVC1tSLosY0u3PLsnWkvi9OQ8V4V aAnT3XYpdSaE401l4YtI+t5b/Q+jf4E1Nh7Xjv6ylJaXOPk4hg39eoJZZ5tkpDBC4QUC hoT8UbLfoQhWiKEH9vmbfymqx6PCiLZ5sQaJ7S4psfOCSQunle196qEPfK2GtOUGelpG ko0dH9aRA1m3fXrRwZK0UHYq8De0MNBTTvSK4okSJkI1/vISLb4PBY0LF4UugMoXKdcp 1NZOqB6hhSZk4f6Aw+kK3d0JolNDxsrMHMsRrzXFMQqF2OmKrBreDRdg5hKT2dDDmx0B j9ng== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587960; x=1771192760; 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; bh=dEUe6oTCoBFfM+Sx9vNYCw5ijDc8cAJk/jm6jmf+e+o=; b=X7lVFtiTt/gpoLgmsqA9L2UPU/GDHi0fxa6MWcwOS9iqpyyW4GH2kso9uPVAalNAkf xmPu/CCp97A3netR71WUXFj1LcpJXpQn+cM7/bWDJQvcTGWzbyJhLC/mHRzhGApAmggS e5U1BH4YfRbyJqQ1yh83FbQzSoGh4gdNbT7W3dhDQYkXvVi/qGIQde9LHdDAurIuEdna KEwonMP1iYlbGPqYlYO/cSZZ6K9cflIKtfWWaPTy5b9VzXnsifnAlbHckE1JW32a/M9y q2WsKwQ763HAYjM2LT/lblLdrUEvNDuxO205FjtU1r7pmb2eqkkP53qLlL2jyPPlf7ij GZOA== X-Forwarded-Encrypted: i=1; AJvYcCV5QBbeq4GZEekIFDkSns3o6P0AzeAKPAyBH34yskOy2ZqOsOQhfatXy0W9FdbLV1i5vITV0g3aSsXXe6Y=@vger.kernel.org X-Gm-Message-State: AOJu0YzUy6ta9CRvkRIHFk1AEN7EabEI7d1I+fn+/jIzhaGomn489gC4 FFb7jQHteqrGtFOTaq4DX7/DA+iLjruH67gScgW7H8gZYS5ma0NY9e5A X-Gm-Gg: AZuq6aKl9g/dTzr9tjmqQMNTmXvpw29HRiGLpJjQwnpoLUYCPgYm6F7LWUEl+TBj8O+ HWsiVEqdUw+ImP3XMKMXOSmgPTWMFYAfWsLtuwE5XWHkWPleUmRdvznlg98/AArll+4R3kc7zKM zpQ4ZJYosbicMnQ79TX4KJaJz9gMVd4NiuuTfh1B++Qi3HHqfsSc7l0hoPM1ep+pzZbb/BwK2dD cxv9r4ejSomfJNLPss6iTYPta3DU7JNGb8oO3+1OWu+qO0rrJR89hhWjCjIIj5T52jrjKipUz3l AW8SHNue2Kt3CevxvauGmLGkx95YlgcHfhe1QhOxL8wZ3FlWCNXwqtTSwBTid0thj9No3GH9OV6 mNXWNmAQkuLwLSvcv8AAwndJluLtA0jg5DqfEwN0kacaGSWgonFqSbiZVJRGV/2SUsa9rUaT408 2UCYeqbkPoC+2YisfntYKYnOYJ8F1dSOsB X-Received: by 2002:a05:6808:158e:b0:45e:f0ef:cd75 with SMTP id 5614622812f47-462fcb77c7amr4638475b6e.65.1770587960064; Sun, 08 Feb 2026 13:59:20 -0800 (PST) Received: from localhost ([2a03:2880:10ff:2::]) by smtp.gmail.com with ESMTPSA id 5614622812f47-462fe9df04esm5291448b6e.7.2026.02.08.13.59.17 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:18 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 18/20] memcg: swap: only charge physical swap slots Date: Sun, 8 Feb 2026 13:58:31 -0800 Message-ID: <20260208215839.87595-19-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that zswap and the zero-filled swap page optimization no longer takes up any physical swap space, we should not charge towards the swap usage and limits of the memcg in these case. We will only record the memcg id on virtual swap slot allocation, and defer physical swap charging (i.e towards memory.swap.current) until the virtual swap slot is backed by an actual physical swap slot (on zswap store failure fallback or zswap writeback). Signed-off-by: Nhat Pham --- include/linux/swap.h | 16 +++++++++ mm/memcontrol-v1.c | 6 ++++ mm/memcontrol.c | 83 ++++++++++++++++++++++++++++++++------------ mm/vswap.c | 39 +++++++++------------ 4 files changed, 98 insertions(+), 46 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 9cd45eab313f8..a30d382fb5ee1 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -613,6 +613,22 @@ static inline void folio_throttle_swaprate(struct foli= o *folio, gfp_t gfp) #endif =20 #if defined(CONFIG_MEMCG) && defined(CONFIG_SWAP) +void __mem_cgroup_record_swap(struct folio *folio, swp_entry_t entry); +static inline void mem_cgroup_record_swap(struct folio *folio, + swp_entry_t entry) +{ + if (!mem_cgroup_disabled()) + __mem_cgroup_record_swap(folio, entry); +} + +void __mem_cgroup_clear_swap(swp_entry_t entry, unsigned int nr_pages); +static inline void mem_cgroup_clear_swap(swp_entry_t entry, + unsigned int nr_pages) +{ + if (!mem_cgroup_disabled()) + __mem_cgroup_clear_swap(entry, nr_pages); +} + int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry); static inline int mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry) diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c index 6eed14bff7426..4580a034dcf72 100644 --- a/mm/memcontrol-v1.c +++ b/mm/memcontrol-v1.c @@ -680,6 +680,12 @@ void memcg1_swapin(swp_entry_t entry, unsigned int nr_= pages) * memory+swap charge, drop the swap entry duplicate. */ mem_cgroup_uncharge_swap(entry, nr_pages); + + /* + * Clear the cgroup association now to prevent double memsw + * uncharging when the backends are released later. + */ + mem_cgroup_clear_swap(entry, nr_pages); } } =20 diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 2ba5811e7edba..50be8066bebec 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -5172,6 +5172,49 @@ int __init mem_cgroup_init(void) } =20 #ifdef CONFIG_SWAP +/** + * __mem_cgroup_record_swap - record the folio's cgroup for the swap entri= es. + * @folio: folio being swapped out. + * @entry: the first swap entry in the range. + */ +void __mem_cgroup_record_swap(struct folio *folio, swp_entry_t entry) +{ + unsigned int nr_pages =3D folio_nr_pages(folio); + struct mem_cgroup *memcg; + + /* Recording will be done by memcg1_swapout(). */ + if (do_memsw_account()) + return; + + memcg =3D folio_memcg(folio); + + VM_WARN_ON_ONCE_FOLIO(!memcg, folio); + if (!memcg) + return; + + memcg =3D mem_cgroup_id_get_online(memcg); + if (nr_pages > 1) + mem_cgroup_id_get_many(memcg, nr_pages - 1); + swap_cgroup_record(folio, mem_cgroup_id(memcg), entry); +} + +/** + * __mem_cgroup_clear_swap - clear cgroup information of the swap entries. + * @folio: folio being swapped out. + * @entry: the first swap entry in the range. + */ +void __mem_cgroup_clear_swap(swp_entry_t entry, unsigned int nr_pages) +{ + unsigned short id =3D swap_cgroup_clear(entry, nr_pages); + struct mem_cgroup *memcg; + + rcu_read_lock(); + memcg =3D mem_cgroup_from_id(id); + if (memcg) + mem_cgroup_id_put_many(memcg, nr_pages); + rcu_read_unlock(); +} + /** * __mem_cgroup_try_charge_swap - try charging swap space for a folio * @folio: folio being added to swap @@ -5190,34 +5233,24 @@ int __mem_cgroup_try_charge_swap(struct folio *foli= o, swp_entry_t entry) if (do_memsw_account()) return 0; =20 - memcg =3D folio_memcg(folio); - - VM_WARN_ON_ONCE_FOLIO(!memcg, folio); - if (!memcg) - return 0; - - if (!entry.val) { - memcg_memory_event(memcg, MEMCG_SWAP_FAIL); - return 0; - } - - memcg =3D mem_cgroup_id_get_online(memcg); + /* + * We already record the cgroup on virtual swap allocation. + * Note that the virtual swap slot holds a reference to memcg, + * so this lookup should be safe. + */ + rcu_read_lock(); + memcg =3D mem_cgroup_from_id(lookup_swap_cgroup_id(entry)); + rcu_read_unlock(); =20 if (!mem_cgroup_is_root(memcg) && !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) { memcg_memory_event(memcg, MEMCG_SWAP_MAX); memcg_memory_event(memcg, MEMCG_SWAP_FAIL); - mem_cgroup_id_put(memcg); return -ENOMEM; } =20 - /* Get references for the tail pages, too */ - if (nr_pages > 1) - mem_cgroup_id_get_many(memcg, nr_pages - 1); mod_memcg_state(memcg, MEMCG_SWAP, nr_pages); =20 - swap_cgroup_record(folio, mem_cgroup_id(memcg), entry); - return 0; } =20 @@ -5231,7 +5264,8 @@ void __mem_cgroup_uncharge_swap(swp_entry_t entry, un= signed int nr_pages) struct mem_cgroup *memcg; unsigned short id; =20 - id =3D swap_cgroup_clear(entry, nr_pages); + id =3D lookup_swap_cgroup_id(entry); + rcu_read_lock(); memcg =3D mem_cgroup_from_id(id); if (memcg) { @@ -5242,7 +5276,6 @@ void __mem_cgroup_uncharge_swap(swp_entry_t entry, un= signed int nr_pages) page_counter_uncharge(&memcg->swap, nr_pages); } mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages); - mem_cgroup_id_put_many(memcg, nr_pages); } rcu_read_unlock(); } @@ -5251,14 +5284,18 @@ static bool mem_cgroup_may_zswap(struct mem_cgroup = *original_memcg); =20 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg) { - long nr_swap_pages, nr_zswap_pages =3D 0; + long nr_swap_pages; =20 if (zswap_is_enabled() && (mem_cgroup_disabled() || do_memsw_account() || mem_cgroup_may_zswap(memcg))) { - nr_zswap_pages =3D PAGE_COUNTER_MAX; + /* + * No need to check swap cgroup limits, since zswap is not charged + * towards swap consumption. + */ + return PAGE_COUNTER_MAX; } =20 - nr_swap_pages =3D max_t(long, nr_zswap_pages, get_nr_swap_pages()); + nr_swap_pages =3D get_nr_swap_pages(); if (mem_cgroup_disabled() || do_memsw_account()) return nr_swap_pages; for (; !mem_cgroup_is_root(memcg); memcg =3D parent_mem_cgroup(memcg)) diff --git a/mm/vswap.c b/mm/vswap.c index 7563107eb8eee..2a071d5ae173c 100644 --- a/mm/vswap.c +++ b/mm/vswap.c @@ -543,6 +543,7 @@ void vswap_rmap_set(struct swap_cluster_info *ci, swp_s= lot_t slot, struct vswap_cluster *cluster =3D NULL; struct swp_desc *desc; unsigned long flush_nr, phys_swap_start =3D 0, phys_swap_end =3D 0; + unsigned long phys_swap_released =3D 0; unsigned int phys_swap_type =3D 0; bool need_flushing_phys_swap =3D false; swp_slot_t flush_slot; @@ -572,6 +573,7 @@ void vswap_rmap_set(struct swap_cluster_info *ci, swp_s= lot_t slot, if (desc->type =3D=3D VSWAP_ZSWAP && desc->zswap_entry) { zswap_entry_free(desc->zswap_entry); } else if (desc->type =3D=3D VSWAP_SWAPFILE) { + phys_swap_released++; if (!phys_swap_start) { /* start a new contiguous range of phys swap */ phys_swap_start =3D swp_slot_offset(desc->slot); @@ -602,6 +604,9 @@ void vswap_rmap_set(struct swap_cluster_info *ci, swp_s= lot_t slot, flush_nr =3D phys_swap_end - phys_swap_start; swap_slot_free_nr(flush_slot, flush_nr); } + + if (phys_swap_released) + mem_cgroup_uncharge_swap(entry, phys_swap_released); } =20 /* @@ -629,7 +634,7 @@ static void vswap_free(struct vswap_cluster *cluster, s= truct swp_desc *desc, spin_unlock(&cluster->lock); =20 release_backing(entry, 1); - mem_cgroup_uncharge_swap(entry, 1); + mem_cgroup_clear_swap(entry, 1); =20 /* erase forward mapping and release the virtual slot for reallocation */ spin_lock(&cluster->lock); @@ -644,9 +649,6 @@ static void vswap_free(struct vswap_cluster *cluster, s= truct swp_desc *desc, */ int folio_alloc_swap(struct folio *folio) { - struct vswap_cluster *cluster =3D NULL; - int i, nr =3D folio_nr_pages(folio); - struct swp_desc *desc; swp_entry_t entry; =20 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); @@ -656,25 +658,7 @@ int folio_alloc_swap(struct folio *folio) if (!entry.val) return -ENOMEM; =20 - /* - * XXX: for now, we charge towards the memory cgroup's swap limit on virt= ual - * swap slots allocation. This will be changed soon - we will only charge= on - * physical swap slots allocation. - */ - if (mem_cgroup_try_charge_swap(folio, entry)) { - rcu_read_lock(); - for (i =3D 0; i < nr; i++) { - desc =3D vswap_iter(&cluster, entry.val + i); - VM_WARN_ON(!desc); - vswap_free(cluster, desc, (swp_entry_t){ entry.val + i }); - } - spin_unlock(&cluster->lock); - rcu_read_unlock(); - atomic_add(nr, &vswap_alloc_reject); - entry.val =3D 0; - return -ENOMEM; - } - + mem_cgroup_record_swap(folio, entry); swap_cache_add_folio(folio, entry, NULL); =20 return 0; @@ -716,6 +700,15 @@ bool vswap_alloc_swap_slot(struct folio *folio) if (!slot.val) return false; =20 + if (mem_cgroup_try_charge_swap(folio, entry)) { + /* + * We have not updated the backing type of the virtual swap slot. + * Simply free up the physical swap slots here! + */ + swap_slot_free_nr(slot, nr); + return false; + } + /* establish the vrtual <-> physical swap slots linkages. */ si =3D __swap_slot_to_info(slot); ci =3D swap_cluster_lock(si, swp_slot_offset(slot)); --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-oi1-f178.google.com (mail-oi1-f178.google.com [209.85.167.178]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 64610378818 for ; Sun, 8 Feb 2026 21:59:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587964; cv=none; b=MYW1H1JKqlw2zmvkGDmG50ZoEl3EFp/gdHZQgJ+dv2rJ5viLpGIA6B7dH3Ql2v6KJ22KT43atGrWvWMXpnYCo/gq180kVhjHsV4EfWyT5K9sEX183Wd6yu8ggKDu+EiyZsD+968vJwaNDgVQydUWwGtcBdVS+4C67ikmZIhXcA8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587964; c=relaxed/simple; bh=4S//sVasRQpLuFOgTf1g1s/n9F4LnVnZLXTw2n2VLDM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=YNHXeZK06CYoem+BhY/3rPu2yihpAsyr/UR/JrMDwYk53VlV7MQbSV3J812sc/m4xRokipWfS5cT1qKzQUGaBevTbL6H7GWf4xhvEgBoTczuPu908wvqjPVUYXglx0VzevLDy+qaWCM6YCm2eeE6ucKCEiuU5NEvqK6pYRw+9OM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=YrEohGqx; arc=none smtp.client-ip=209.85.167.178 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.b="YrEohGqx" Received: by mail-oi1-f178.google.com with SMTP id 5614622812f47-460f3f9fdb1so2837341b6e.0 for ; Sun, 08 Feb 2026 13:59:24 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587963; x=1771192763; 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; bh=4m66NSEdK1BRkgjUBQQieU2eKX3oRCTL4lRkohCFyaM=; b=YrEohGqxyEl+V/349NtPW3y+wbhqqbDrIFD2jESanGzcnrsOuAem1ivgsPYN95d955 KPWXFtyDsWV4TTeyv1k1SfKv+GMjkoyM2/SpCTPDxZ7KuAAGWUmNe6lZvhyrFMGVL6Nv 7nlcvG+fyb/g3pHUFNtRVQUeWm5WjUtb8Ggnk9ERLH0ceTSFIFcv/7BIi2q5KfnDUG2d xL7Kdb7KFb079R4a5iYMlbmcgC0++yp7h1Em+K0258XSlt4lJIsHSHt3joIMR/S5sYqS OUdsGbAuXA+LsARa6iKmw8CfqqYbbz5TzsAOPNQCeAbY3MNod/KVt0zU9GXlGdJ5Frim 4bhA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587963; x=1771192763; 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; bh=4m66NSEdK1BRkgjUBQQieU2eKX3oRCTL4lRkohCFyaM=; b=mXCkEr/IofBIBNiCzwwfWL/Qzg7dr3VC9TOlV9s8RmOg/uTf9LY00zLtxOb69mojAu FyrqTycORxWdC+407xAfUWKX0WVTXzaVk47oURAqhvLqQsU3u72NqnD3R3MEQO3dhMwO TKcqDns4mTVyabSdZKHFX+EDylgw9kidjiL43u2PvuAmiXV7NIExDzrbvuaZmfCkWyk7 4q02WlfGU11unsZrC3u5uSpnsQKRa5AAAPkCwD0Re1+2GMzrp8c0Kj2cvF07ilf/kSVR 7328y8/t/lZBXRyO0I6P8S7wsF8qUjB3dD/E56d2Tk8sdh/VzsOwZp81RPiBXjpeWUjV vtZg== X-Forwarded-Encrypted: i=1; AJvYcCV+8hRTQTP1V/qcRXb52yTEGihdknU1dXjNmvHgL+W+ByFN3ku+tkXSYFmN30bxk198VRLPeb+qxcTbnb0=@vger.kernel.org X-Gm-Message-State: AOJu0Yzohmb3WBFeLq/jT4mCrxFT8O3US9YRveVjCx0o18vXBTYqB/uU CQpq3E6/5rV+Z6TlvtttEi49+akpSE5wuSHlpGR+OpjUG2xmGL+A5d6o X-Gm-Gg: AZuq6aKAHghOAIQ7KDEHAkJfBrLoCfNzNCLoJoXjvbVeCd0/NkuDAWFu4rg1Hu3MoHD mLfHp8yKFCGax38llTCK21SkMr7lYqBC585xnLki+EkKsNJCyZ++Ml5c5QBRNfRlxAnrh4Q6opV I7p1HrovoZIV+wZWE0t9WU+m09JBIirqzRJdYBLuwB3xnupOgQ+tIJ07NCXsiOhW66z70f7d/WL xa/CZ11g4PPm88iS0bjGvQwUhJD0CPcEEF/x4FNtcBeJwj40Y70pyvb+GnH4U3yxWGoK0d3oNMz VvAYzX8W6SyCckTznF2nkfJcHS/4bcm/9yViyTb0JGAnuQvDM302Bf1hP3lvk+zIZH3uqu+xc5V EEolNbzGoyTN7ppX3C/XdgV/ROjlriLhoiFsIpbCRoIkhdLn2zIs1E0EHDinBvFPe4oTuoQCTGG I85O425Y7fgDJ0LlALlTrHRJPGI0gvqqMn X-Received: by 2002:a05:6808:1903:b0:45a:3d58:6475 with SMTP id 5614622812f47-462e9b9a0d2mr7347861b6e.13.1770587963127; Sun, 08 Feb 2026 13:59:23 -0800 (PST) Received: from localhost ([2a03:2880:10ff:1::]) by smtp.gmail.com with ESMTPSA id 5614622812f47-462fe9a16a1sm5402674b6e.2.2026.02.08.13.59.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:21 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 19/20] swap: simplify swapoff using virtual swap Date: Sun, 8 Feb 2026 13:58:32 -0800 Message-ID: <20260208215839.87595-20-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This patch presents the second applications of virtual swap design - simplifying and optimizing swapoff. With virtual swap slots stored at page table entries and used as indices to various swap-related data structures, we no longer have to perform a page table walk in swapoff. Simply iterate through all the allocated swap slots on the swapfile, find their corresponding virtual swap slots, and fault them in. This is significantly cleaner, as well as slightly more performant, especially when there are a lot of unrelated VMAs (since the old swapoff code would have to traverse through all of them). In a simple benchmark, in which we swapoff a 32 GB swapfile that is 50% full, and in which there is a process that maps a 128GB file into memory: Baseline: sys: 11.48s New Design: sys: 9.96s Disregarding the real time reduction (which is mostly due to more IO asynchrony), the new design reduces the kernel CPU time by about 13%. Signed-off-by: Nhat Pham --- include/linux/shmem_fs.h | 7 +- mm/shmem.c | 184 +-------------- mm/swapfile.c | 474 +++++++++------------------------------ 3 files changed, 113 insertions(+), 552 deletions(-) diff --git a/include/linux/shmem_fs.h b/include/linux/shmem_fs.h index e2069b3179c41..bac6b6cafe89c 100644 --- a/include/linux/shmem_fs.h +++ b/include/linux/shmem_fs.h @@ -41,17 +41,13 @@ struct shmem_inode_info { unsigned long swapped; /* subtotal assigned to swap */ union { struct offset_ctx dir_offsets; /* stable directory offsets */ - struct { - struct list_head shrinklist; /* shrinkable hpage inodes */ - struct list_head swaplist; /* chain of maybes on swap */ - }; + struct list_head shrinklist; /* shrinkable hpage inodes */ }; struct timespec64 i_crtime; /* file creation time */ struct shared_policy policy; /* NUMA memory alloc policy */ struct simple_xattrs xattrs; /* list of xattrs */ pgoff_t fallocend; /* highest fallocate endindex */ unsigned int fsflags; /* for FS_IOC_[SG]ETFLAGS */ - atomic_t stop_eviction; /* hold when working on inode */ #ifdef CONFIG_TMPFS_QUOTA struct dquot __rcu *i_dquot[MAXQUOTAS]; #endif @@ -127,7 +123,6 @@ struct page *shmem_read_mapping_page_gfp(struct address= _space *mapping, int shmem_writeout(struct folio *folio, struct swap_iocb **plug, struct list_head *folio_list); void shmem_truncate_range(struct inode *inode, loff_t start, uoff_t end); -int shmem_unuse(unsigned int type); =20 #ifdef CONFIG_TRANSPARENT_HUGEPAGE unsigned long shmem_allowable_huge_orders(struct inode *inode, diff --git a/mm/shmem.c b/mm/shmem.c index 3a346cca114ab..61790752bdf6d 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -290,9 +290,6 @@ bool vma_is_shmem(const struct vm_area_struct *vma) return vma_is_anon_shmem(vma) || vma->vm_ops =3D=3D &shmem_vm_ops; } =20 -static LIST_HEAD(shmem_swaplist); -static DEFINE_SPINLOCK(shmem_swaplist_lock); - #ifdef CONFIG_TMPFS_QUOTA =20 static int shmem_enable_quotas(struct super_block *sb, @@ -1413,16 +1410,6 @@ static void shmem_evict_inode(struct inode *inode) } spin_unlock(&sbinfo->shrinklist_lock); } - while (!list_empty(&info->swaplist)) { - /* Wait while shmem_unuse() is scanning this inode... */ - wait_var_event(&info->stop_eviction, - !atomic_read(&info->stop_eviction)); - spin_lock(&shmem_swaplist_lock); - /* ...but beware of the race if we peeked too early */ - if (!atomic_read(&info->stop_eviction)) - list_del_init(&info->swaplist); - spin_unlock(&shmem_swaplist_lock); - } } =20 simple_xattrs_free(&info->xattrs, sbinfo->max_inodes ? &freed : NULL); @@ -1435,153 +1422,6 @@ static void shmem_evict_inode(struct inode *inode) #endif } =20 -static unsigned int shmem_find_swap_entries(struct address_space *mapping, - pgoff_t start, struct folio_batch *fbatch, - pgoff_t *indices, unsigned int type) -{ - XA_STATE(xas, &mapping->i_pages, start); - struct folio *folio; - swp_entry_t entry; - swp_slot_t slot; - - rcu_read_lock(); - xas_for_each(&xas, folio, ULONG_MAX) { - if (xas_retry(&xas, folio)) - continue; - - if (!xa_is_value(folio)) - continue; - - entry =3D radix_to_swp_entry(folio); - slot =3D swp_entry_to_swp_slot(entry); - - /* - * swapin error entries can be found in the mapping. But they're - * deliberately ignored here as we've done everything we can do. - */ - if (!slot.val || swp_slot_type(slot) !=3D type) - continue; - - indices[folio_batch_count(fbatch)] =3D xas.xa_index; - if (!folio_batch_add(fbatch, folio)) - break; - - if (need_resched()) { - xas_pause(&xas); - cond_resched_rcu(); - } - } - rcu_read_unlock(); - - return folio_batch_count(fbatch); -} - -/* - * Move the swapped pages for an inode to page cache. Returns the count - * of pages swapped in, or the error in case of failure. - */ -static int shmem_unuse_swap_entries(struct inode *inode, - struct folio_batch *fbatch, pgoff_t *indices) -{ - int i =3D 0; - int ret =3D 0; - int error =3D 0; - struct address_space *mapping =3D inode->i_mapping; - - for (i =3D 0; i < folio_batch_count(fbatch); i++) { - struct folio *folio =3D fbatch->folios[i]; - - error =3D shmem_swapin_folio(inode, indices[i], &folio, SGP_CACHE, - mapping_gfp_mask(mapping), NULL, NULL); - if (error =3D=3D 0) { - folio_unlock(folio); - folio_put(folio); - ret++; - } - if (error =3D=3D -ENOMEM) - break; - error =3D 0; - } - return error ? error : ret; -} - -/* - * If swap found in inode, free it and move page from swapcache to filecac= he. - */ -static int shmem_unuse_inode(struct inode *inode, unsigned int type) -{ - struct address_space *mapping =3D inode->i_mapping; - pgoff_t start =3D 0; - struct folio_batch fbatch; - pgoff_t indices[PAGEVEC_SIZE]; - int ret =3D 0; - - do { - folio_batch_init(&fbatch); - if (!shmem_find_swap_entries(mapping, start, &fbatch, - indices, type)) { - ret =3D 0; - break; - } - - ret =3D shmem_unuse_swap_entries(inode, &fbatch, indices); - if (ret < 0) - break; - - start =3D indices[folio_batch_count(&fbatch) - 1]; - } while (true); - - return ret; -} - -/* - * Read all the shared memory data that resides in the swap - * device 'type' back into memory, so the swap device can be - * unused. - */ -int shmem_unuse(unsigned int type) -{ - struct shmem_inode_info *info, *next; - int error =3D 0; - - if (list_empty(&shmem_swaplist)) - return 0; - - spin_lock(&shmem_swaplist_lock); -start_over: - list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) { - if (!info->swapped) { - list_del_init(&info->swaplist); - continue; - } - /* - * Drop the swaplist mutex while searching the inode for swap; - * but before doing so, make sure shmem_evict_inode() will not - * remove placeholder inode from swaplist, nor let it be freed - * (igrab() would protect from unlink, but not from unmount). - */ - atomic_inc(&info->stop_eviction); - spin_unlock(&shmem_swaplist_lock); - - error =3D shmem_unuse_inode(&info->vfs_inode, type); - cond_resched(); - - spin_lock(&shmem_swaplist_lock); - if (atomic_dec_and_test(&info->stop_eviction)) - wake_up_var(&info->stop_eviction); - if (error) - break; - if (list_empty(&info->swaplist)) - goto start_over; - next =3D list_next_entry(info, swaplist); - if (!info->swapped) - list_del_init(&info->swaplist); - } - spin_unlock(&shmem_swaplist_lock); - - return error; -} - /** * shmem_writeout - Write the folio to swap * @folio: The folio to write @@ -1668,24 +1508,9 @@ int shmem_writeout(struct folio *folio, struct swap_= iocb **plug, } =20 if (!folio_alloc_swap(folio)) { - bool first_swapped =3D shmem_recalc_inode(inode, 0, nr_pages); int error; =20 - /* - * Add inode to shmem_unuse()'s list of swapped-out inodes, - * if it's not already there. Do it now before the folio is - * removed from page cache, when its pagelock no longer - * protects the inode from eviction. And do it now, after - * we've incremented swapped, because shmem_unuse() will - * prune a !swapped inode from the swaplist. - */ - if (first_swapped) { - spin_lock(&shmem_swaplist_lock); - if (list_empty(&info->swaplist)) - list_add(&info->swaplist, &shmem_swaplist); - spin_unlock(&shmem_swaplist_lock); - } - + shmem_recalc_inode(inode, 0, nr_pages); swap_shmem_alloc(folio->swap, nr_pages); shmem_delete_from_page_cache(folio, swp_to_radix_entry(folio->swap)); =20 @@ -3106,7 +2931,6 @@ static struct inode *__shmem_get_inode(struct mnt_idm= ap *idmap, info =3D SHMEM_I(inode); memset(info, 0, (char *)inode - (char *)info); spin_lock_init(&info->lock); - atomic_set(&info->stop_eviction, 0); info->seals =3D F_SEAL_SEAL; info->flags =3D (flags & VM_NORESERVE) ? SHMEM_F_NORESERVE : 0; info->i_crtime =3D inode_get_mtime(inode); @@ -3115,7 +2939,6 @@ static struct inode *__shmem_get_inode(struct mnt_idm= ap *idmap, if (info->fsflags) shmem_set_inode_flags(inode, info->fsflags, NULL); INIT_LIST_HEAD(&info->shrinklist); - INIT_LIST_HEAD(&info->swaplist); simple_xattrs_init(&info->xattrs); cache_no_acl(inode); if (sbinfo->noswap) @@ -5785,11 +5608,6 @@ void __init shmem_init(void) BUG_ON(IS_ERR(shm_mnt)); } =20 -int shmem_unuse(unsigned int type) -{ - return 0; -} - int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) { return 0; diff --git a/mm/swapfile.c b/mm/swapfile.c index e1cb01b821ff3..9478707ce3ffa 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -1738,300 +1738,12 @@ unsigned int count_swap_pages(int type, int free) } #endif /* CONFIG_HIBERNATION */ =20 -static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte) +static bool swap_slot_allocated(struct swap_info_struct *si, + unsigned long offset) { - return pte_same(pte_swp_clear_flags(pte), swp_pte); -} - -/* - * No need to decide whether this PTE shares the swap entry with others, - * just let do_wp_page work it out if a write is requested later - to - * force COW, vm_page_prot omits write permission from any private vma. - */ -static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd, - unsigned long addr, swp_entry_t entry, struct folio *folio) -{ - struct page *page; - struct folio *swapcache; - spinlock_t *ptl; - pte_t *pte, new_pte, old_pte; - bool hwpoisoned =3D false; - int ret =3D 1; - - /* - * If the folio is removed from swap cache by others, continue to - * unuse other PTEs. try_to_unuse may try again if we missed this one. - */ - if (!folio_matches_swap_entry(folio, entry)) - return 0; - - swapcache =3D folio; - folio =3D ksm_might_need_to_copy(folio, vma, addr); - if (unlikely(!folio)) - return -ENOMEM; - else if (unlikely(folio =3D=3D ERR_PTR(-EHWPOISON))) { - hwpoisoned =3D true; - folio =3D swapcache; - } - - page =3D folio_file_page(folio, swp_offset(entry)); - if (PageHWPoison(page)) - hwpoisoned =3D true; - - pte =3D pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); - if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte), - swp_entry_to_pte(entry)))) { - ret =3D 0; - goto out; - } - - old_pte =3D ptep_get(pte); - - if (unlikely(hwpoisoned || !folio_test_uptodate(folio))) { - swp_entry_t swp_entry; - - dec_mm_counter(vma->vm_mm, MM_SWAPENTS); - if (hwpoisoned) { - swp_entry =3D make_hwpoison_entry(page); - } else { - swp_entry =3D make_poisoned_swp_entry(); - } - new_pte =3D swp_entry_to_pte(swp_entry); - ret =3D 0; - goto setpte; - } - - /* - * Some architectures may have to restore extra metadata to the page - * when reading from swap. This metadata may be indexed by swap entry - * so this must be called before swap_free(). - */ - arch_swap_restore(folio_swap(entry, folio), folio); - - dec_mm_counter(vma->vm_mm, MM_SWAPENTS); - inc_mm_counter(vma->vm_mm, MM_ANONPAGES); - folio_get(folio); - if (folio =3D=3D swapcache) { - rmap_t rmap_flags =3D RMAP_NONE; - - /* - * See do_swap_page(): writeback would be problematic. - * However, we do a folio_wait_writeback() just before this - * call and have the folio locked. - */ - VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio); - if (pte_swp_exclusive(old_pte)) - rmap_flags |=3D RMAP_EXCLUSIVE; - /* - * We currently only expect small !anon folios, which are either - * fully exclusive or fully shared. If we ever get large folios - * here, we have to be careful. - */ - if (!folio_test_anon(folio)) { - VM_WARN_ON_ONCE(folio_test_large(folio)); - VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); - folio_add_new_anon_rmap(folio, vma, addr, rmap_flags); - } else { - folio_add_anon_rmap_pte(folio, page, vma, addr, rmap_flags); - } - } else { /* ksm created a completely new copy */ - folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE); - folio_add_lru_vma(folio, vma); - } - new_pte =3D pte_mkold(mk_pte(page, vma->vm_page_prot)); - if (pte_swp_soft_dirty(old_pte)) - new_pte =3D pte_mksoft_dirty(new_pte); - if (pte_swp_uffd_wp(old_pte)) - new_pte =3D pte_mkuffd_wp(new_pte); -setpte: - set_pte_at(vma->vm_mm, addr, pte, new_pte); - swap_free(entry); -out: - if (pte) - pte_unmap_unlock(pte, ptl); - if (folio !=3D swapcache) { - folio_unlock(folio); - folio_put(folio); - } - return ret; -} - -static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd, - unsigned long addr, unsigned long end, - unsigned int type) -{ - pte_t *pte =3D NULL; - struct swap_info_struct *si; - - si =3D swap_info[type]; - do { - struct folio *folio; - unsigned long offset; - unsigned char swp_count; - softleaf_t entry; - swp_slot_t slot; - int ret; - pte_t ptent; - - if (!pte++) { - pte =3D pte_offset_map(pmd, addr); - if (!pte) - break; - } - - ptent =3D ptep_get_lockless(pte); - entry =3D softleaf_from_pte(ptent); - - if (!softleaf_is_swap(entry)) - continue; - - slot =3D swp_entry_to_swp_slot(entry); - if (swp_slot_type(slot) !=3D type) - continue; - - offset =3D swp_slot_offset(slot); - pte_unmap(pte); - pte =3D NULL; - - folio =3D swap_cache_get_folio(entry); - if (!folio) { - struct vm_fault vmf =3D { - .vma =3D vma, - .address =3D addr, - .real_address =3D addr, - .pmd =3D pmd, - }; - - folio =3D swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, - &vmf); - } - if (!folio) { - swp_count =3D READ_ONCE(si->swap_map[offset]); - if (swp_count =3D=3D 0 || swp_count =3D=3D SWAP_MAP_BAD) - continue; - return -ENOMEM; - } - - folio_lock(folio); - folio_wait_writeback(folio); - ret =3D unuse_pte(vma, pmd, addr, entry, folio); - if (ret < 0) { - folio_unlock(folio); - folio_put(folio); - return ret; - } - - folio_free_swap(folio); - folio_unlock(folio); - folio_put(folio); - } while (addr +=3D PAGE_SIZE, addr !=3D end); - - if (pte) - pte_unmap(pte); - return 0; -} - -static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud, - unsigned long addr, unsigned long end, - unsigned int type) -{ - pmd_t *pmd; - unsigned long next; - int ret; - - pmd =3D pmd_offset(pud, addr); - do { - cond_resched(); - next =3D pmd_addr_end(addr, end); - ret =3D unuse_pte_range(vma, pmd, addr, next, type); - if (ret) - return ret; - } while (pmd++, addr =3D next, addr !=3D end); - return 0; -} - -static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d, - unsigned long addr, unsigned long end, - unsigned int type) -{ - pud_t *pud; - unsigned long next; - int ret; - - pud =3D pud_offset(p4d, addr); - do { - next =3D pud_addr_end(addr, end); - if (pud_none_or_clear_bad(pud)) - continue; - ret =3D unuse_pmd_range(vma, pud, addr, next, type); - if (ret) - return ret; - } while (pud++, addr =3D next, addr !=3D end); - return 0; -} - -static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd, - unsigned long addr, unsigned long end, - unsigned int type) -{ - p4d_t *p4d; - unsigned long next; - int ret; - - p4d =3D p4d_offset(pgd, addr); - do { - next =3D p4d_addr_end(addr, end); - if (p4d_none_or_clear_bad(p4d)) - continue; - ret =3D unuse_pud_range(vma, p4d, addr, next, type); - if (ret) - return ret; - } while (p4d++, addr =3D next, addr !=3D end); - return 0; -} - -static int unuse_vma(struct vm_area_struct *vma, unsigned int type) -{ - pgd_t *pgd; - unsigned long addr, end, next; - int ret; - - addr =3D vma->vm_start; - end =3D vma->vm_end; - - pgd =3D pgd_offset(vma->vm_mm, addr); - do { - next =3D pgd_addr_end(addr, end); - if (pgd_none_or_clear_bad(pgd)) - continue; - ret =3D unuse_p4d_range(vma, pgd, addr, next, type); - if (ret) - return ret; - } while (pgd++, addr =3D next, addr !=3D end); - return 0; -} + unsigned char count =3D READ_ONCE(si->swap_map[offset]); =20 -static int unuse_mm(struct mm_struct *mm, unsigned int type) -{ - struct vm_area_struct *vma; - int ret =3D 0; - VMA_ITERATOR(vmi, mm, 0); - - mmap_read_lock(mm); - if (check_stable_address_space(mm)) - goto unlock; - for_each_vma(vmi, vma) { - if (vma->anon_vma && !is_vm_hugetlb_page(vma)) { - ret =3D unuse_vma(vma, type); - if (ret) - break; - } - - cond_resched(); - } -unlock: - mmap_read_unlock(mm); - return ret; + return count && swap_count(count) !=3D SWAP_MAP_BAD; } =20 /* @@ -2043,7 +1755,6 @@ static unsigned int find_next_to_unuse(struct swap_in= fo_struct *si, unsigned int prev) { unsigned int i; - unsigned char count; =20 /* * No need for swap_lock here: we're just looking @@ -2052,8 +1763,7 @@ static unsigned int find_next_to_unuse(struct swap_in= fo_struct *si, * allocations from this area (while holding swap_lock). */ for (i =3D prev + 1; i < si->max; i++) { - count =3D READ_ONCE(si->swap_map[i]); - if (count && swap_count(count) !=3D SWAP_MAP_BAD) + if (swap_slot_allocated(si, i)) break; if ((i % LATENCY_LIMIT) =3D=3D 0) cond_resched(); @@ -2065,101 +1775,139 @@ static unsigned int find_next_to_unuse(struct swa= p_info_struct *si, return i; } =20 +#define for_each_allocated_offset(si, offset) \ + while (swap_usage_in_pages(si) && \ + !signal_pending(current) && \ + (offset =3D find_next_to_unuse(si, offset)) !=3D 0) + +static struct folio *pagein(swp_entry_t entry, struct swap_iocb **splug, + struct mempolicy *mpol) +{ + bool folio_was_allocated; + struct folio *folio =3D __read_swap_cache_async(entry, GFP_KERNEL, mpol, + NO_INTERLEAVE_INDEX, &folio_was_allocated, false); + + if (folio_was_allocated) + swap_read_folio(folio, splug); + return folio; +} + static int try_to_unuse(unsigned int type) { - struct mm_struct *prev_mm; - struct mm_struct *mm; - struct list_head *p; - int retval =3D 0; struct swap_info_struct *si =3D swap_info[type]; + struct swap_iocb *splug =3D NULL; + struct mempolicy *mpol; + struct blk_plug plug; + unsigned long offset; struct folio *folio; swp_entry_t entry; swp_slot_t slot; - unsigned int i; + int ret =3D 0; =20 if (!swap_usage_in_pages(si)) goto success; =20 -retry: - retval =3D shmem_unuse(type); - if (retval) - return retval; - - prev_mm =3D &init_mm; - mmget(prev_mm); - - spin_lock(&mmlist_lock); - p =3D &init_mm.mmlist; - while (swap_usage_in_pages(si) && - !signal_pending(current) && - (p =3D p->next) !=3D &init_mm.mmlist) { + mpol =3D get_task_policy(current); + blk_start_plug(&plug); =20 - mm =3D list_entry(p, struct mm_struct, mmlist); - if (!mmget_not_zero(mm)) + /* first round - submit the reads */ + offset =3D 0; + for_each_allocated_offset(si, offset) { + slot =3D swp_slot(type, offset); + entry =3D swp_slot_to_swp_entry(slot); + if (!entry.val) continue; - spin_unlock(&mmlist_lock); - mmput(prev_mm); - prev_mm =3D mm; - retval =3D unuse_mm(mm, type); - if (retval) { - mmput(prev_mm); - return retval; - } =20 - /* - * Make sure that we aren't completely killing - * interactive performance. - */ - cond_resched(); - spin_lock(&mmlist_lock); + folio =3D pagein(entry, &splug, mpol); + if (folio) + folio_put(folio); } - spin_unlock(&mmlist_lock); + blk_finish_plug(&plug); + swap_read_unplug(splug); + splug =3D NULL; + lru_add_drain(); + + /* second round - updating the virtual swap slots' backing state */ + offset =3D 0; + for_each_allocated_offset(si, offset) { + slot =3D swp_slot(type, offset); +retry: + entry =3D swp_slot_to_swp_entry(slot); + if (!entry.val) { + if (!swap_slot_allocated(si, offset)) + continue; =20 - mmput(prev_mm); + if (signal_pending(current)) { + ret =3D -EINTR; + goto out; + } =20 - i =3D 0; - while (swap_usage_in_pages(si) && - !signal_pending(current) && - (i =3D find_next_to_unuse(si, i)) !=3D 0) { + /* we might be racing with zswap writeback or disk swapout */ + schedule_timeout_uninterruptible(1); + goto retry; + } =20 - slot =3D swp_slot(type, i); - entry =3D swp_slot_to_swp_entry(slot); - folio =3D swap_cache_get_folio(entry); - if (!folio) - continue; + /* try to allocate swap cache folio */ + folio =3D pagein(entry, &splug, mpol); + if (!folio) { + if (!swp_slot_to_swp_entry(swp_slot(type, offset)).val) + continue; =20 + ret =3D -ENOMEM; + pr_err("swapoff: unable to allocate swap cache folio for %lu\n", + entry.val); + goto out; + } + + folio_lock(folio); /* - * It is conceivable that a racing task removed this folio from - * swap cache just before we acquired the page lock. The folio - * might even be back in swap cache on another swap area. But - * that is okay, folio_free_swap() only removes stale folios. + * We need to check if the folio is still in swap cache, and is still + * backed by the physical swap slot we are trying to release. + * + * We can, for instance, race with zswap writeback, obtaining the + * temporary folio it allocated for decompression and writeback, which + * would be promptly deleted from swap cache. By the time we lock that + * folio, it might have already contained stale data. + * + * Concurrent swap operations might have also come in before we + * reobtain the folio's lock, deleting the folio from swap cache, + * invalidating the virtual swap slot, then swapping out the folio + * again to a different swap backends. + * + * In all of these cases, we must retry the physical -> virtual lookup. */ - folio_lock(folio); + if (!folio_matches_swap_slot(folio, entry, slot)) { + folio_unlock(folio); + folio_put(folio); + if (signal_pending(current)) { + ret =3D -EINTR; + goto out; + } + schedule_timeout_uninterruptible(1); + goto retry; + } + folio_wait_writeback(folio); - folio_free_swap(folio); + vswap_store_folio(entry, folio); + folio_mark_dirty(folio); folio_unlock(folio); folio_put(folio); } =20 - /* - * Lets check again to see if there are still swap entries in the map. - * If yes, we would need to do retry the unuse logic again. - * Under global memory pressure, swap entries can be reinserted back - * into process space after the mmlist loop above passes over them. - * - * Limit the number of retries? No: when mmget_not_zero() - * above fails, that mm is likely to be freeing swap from - * exit_mmap(), which proceeds at its own independent pace; - * and even shmem_writeout() could have been preempted after - * folio_alloc_swap(), temporarily hiding that swap. It's easy - * and robust (though cpu-intensive) just to keep retrying. - */ - if (swap_usage_in_pages(si)) { - if (!signal_pending(current)) - goto retry; - return -EINTR; + /* concurrent swappers might still be releasing physical swap slots... */ + while (swap_usage_in_pages(si)) { + if (signal_pending(current)) { + ret =3D -EINTR; + goto out; + } + schedule_timeout_uninterruptible(1); } =20 +out: + swap_read_unplug(splug); + if (ret) + return ret; + success: /* * Make sure that further cleanups after try_to_unuse() returns happen --=20 2.47.3 From nobody Wed Feb 11 06:53:33 2026 Received: from mail-ot1-f45.google.com (mail-ot1-f45.google.com [209.85.210.45]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8E6A7378D73 for ; Sun, 8 Feb 2026 21:59:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.45 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587966; cv=none; b=iFsrtPBxSuTDBNOnSFqnmK5xK1BWxiffqDk2fnvjetpywCRysOHg+kf3EvxQGjiyLGnuVe8SWOa9zXm3balOmvePB4iob1eYfKuBNXli/+RY3oVwCfS8U/o5dr7/xsmIDBrqzVLJJ74g5gX80gZRFQB9T0NC/AFIt7FXynC7NBI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770587966; c=relaxed/simple; bh=VEosGorbCN3vXTzEpm7A1BGYOplMIFk+kHkexBvQWFc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Wc6aTEipKkdHWRSNF4bN9TUd7H1FsCe4z1EltkJVy89XKlordKW0WXKwzvyXs0FvJimjm0x2VYAoo8mWc/8AJD8Gm0sfKqSehM7B3wf9XUu/M75vq9BPfwT6dMn4+rGAfUgNK2+IF/lrcZQxgxs4ciEKq5/BJlS5glQW85+biQU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=dDXXA8RL; arc=none smtp.client-ip=209.85.210.45 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.b="dDXXA8RL" Received: by mail-ot1-f45.google.com with SMTP id 46e09a7af769-7d148dd3421so871239a34.0 for ; Sun, 08 Feb 2026 13:59:26 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1770587965; x=1771192765; 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; bh=c90iUpuT0uTrBpR1ziQiggNR562GhjEZFfLgw7gtP4Q=; b=dDXXA8RLnhOvLHRBEyN3N+J0sOH+ta9LNuqDprGnUFouUVmgUQj3NxdKS6uO2ZGxMj hrjVXCFNMW4g96g3RnnYUeWellgHeBbxa7LiO1HfoMy7zJxh60yvIAP//1rK6gWnnCXD e72QWQsjRJbRdFmKyxKtFbqdgFV1hG+SMOW5RB/3u2I1z55lFXK2qB86YyYa6v12s5V3 gtSiPWeGIMvsH93TdEe6IijIZbQd83ZUFxqp8eXo6yAKTQYje5HAd+T8BMGSQ3P3Gb8m 2kA1DunEe5KRYSxSKRuqsSgdimftZv1g7kQZHIL8oofd4S6zN9KuihZqaVKRB57NH74C L3ew== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1770587965; x=1771192765; 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; bh=c90iUpuT0uTrBpR1ziQiggNR562GhjEZFfLgw7gtP4Q=; b=izJtuODownPQLjs0nbODQpjnMo/61OlqJo9TvO+wc1yv5//7ZB2Z3WJZh1kiTsc9Uu ZVB2hUqXUvLLPiQB+lJuAikxZlriZ+guK5TIpURFbJ7v8ajF0lc7I+OOgevYHMzE+CEI oDO+H2hFz4vd7Y1JH/DKLdwN7k8pazxgeBjJB/A0/OBXYVdYxg6KR1QtkpEY6S27jEsI D0jKn9EV/uS7gob5hoXLSETDtPvdlc+v5xR9NtldC7TqutUoufnD/h1pKujc/wG5e7qC GKhjFImvC54yalF4B++G2rAYIt0kdwMRkzmAdYZu7n+vz3c/Jugox0AYEQqY21u+ImIA V1Dg== X-Forwarded-Encrypted: i=1; AJvYcCVdukNQna5fE1xk88qx8hSeVfEV/+GqhV/aNefalTwkWXoj11kuzA1KhrD6jWI9np42ANGmxlTiduusVM8=@vger.kernel.org X-Gm-Message-State: AOJu0YzngY03T1drP1ImY5DazsGKTWckrSvDIuuGiOz3BmvZbVRGp2KZ ZR7z641boIjITiFadyGYOATuTOnv2AWmziGEcWIa8KcAGts22Ij2hIwm X-Gm-Gg: AZuq6aL9hXwePZ6/eKhoS9FpXQA53fpEPyccS+/FBMQ7GKQtDRjJmgaggXZaVe4r2yA Lp0VKVoiudPJdXOxMYrQz3eyYZ94eZpiTdmwmiQZdbQULKOwvWjMxVaiABe2xakV+5No4VbcJ6i 6nvGe3gYI1M/8kCWhV1r3OduB+k9GH+5pjm6krGoYDhGrbBoNZMGy9m1rlXuSqpeYO1fNjEfGRa 0Cqpmp2HtofpDsxqkUTQqa3BbVQzO3GZ+AhkjcxSWanHlSgAvvBWV8zk72qvTc5J3s6213TXp59 bUAd83TZNzhmfnp9vYZ4oETIv/y/hXokIb+hHqIVC8Z1tWpLmSnUMybSyUeMF2j4w9eJkOn9No4 LaUZnYAN+E8QMWosLZV9xMUAkjFntMfdVSWyAHFb6q0aPCDY5GrJmE4P0vURfaOJrrO/LOZjVz3 7GpC4lra2tfqsUz7mpFInEmgzaiFQapdbI2Q== X-Received: by 2002:a05:6830:6f47:b0:7d1:8ad3:ce7 with SMTP id 46e09a7af769-7d4643e7eb1mr4865896a34.1.1770587965213; Sun, 08 Feb 2026 13:59:25 -0800 (PST) Received: from localhost ([2a03:2880:10ff:40::]) by smtp.gmail.com with ESMTPSA id 46e09a7af769-7d46479954bsm6335454a34.21.2026.02.08.13.59.23 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 08 Feb 2026 13:59:24 -0800 (PST) From: Nhat Pham To: linux-mm@kvack.org Cc: akpm@linux-foundation.org, hannes@cmpxchg.org, hughd@google.com, yosry.ahmed@linux.dev, mhocko@kernel.org, roman.gushchin@linux.dev, shakeel.butt@linux.dev, muchun.song@linux.dev, len.brown@intel.com, chengming.zhou@linux.dev, kasong@tencent.com, chrisl@kernel.org, huang.ying.caritas@gmail.com, ryan.roberts@arm.com, shikemeng@huaweicloud.com, viro@zeniv.linux.org.uk, baohua@kernel.org, bhe@redhat.com, osalvador@suse.de, lorenzo.stoakes@oracle.com, christophe.leroy@csgroup.eu, pavel@kernel.org, kernel-team@meta.com, linux-kernel@vger.kernel.org, cgroups@vger.kernel.org, linux-pm@vger.kernel.org, peterx@redhat.com, riel@surriel.com, joshua.hahnjy@gmail.com, npache@redhat.com, gourry@gourry.net, axelrasmussen@google.com, yuanchu@google.com, weixugc@google.com, rafael@kernel.org, jannh@google.com, pfalcato@suse.de, zhengqi.arch@bytedance.com Subject: [PATCH v3 20/20] swapfile: replace the swap map with bitmaps Date: Sun, 8 Feb 2026 13:58:33 -0800 Message-ID: <20260208215839.87595-21-nphamcs@gmail.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260208215839.87595-1-nphamcs@gmail.com> References: <20260208215839.87595-1-nphamcs@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that we have moved the swap count state to virtual swap layer, each swap map entry only has 3 possible states: free, allocated, and bad. Replace the swap map with 2 bitmaps (one for allocated state and one for bad state), saving 6 bits per swap entry. Signed-off-by: Nhat Pham --- include/linux/swap.h | 3 +- mm/swapfile.c | 81 +++++++++++++++++++++++--------------------- 2 files changed, 44 insertions(+), 40 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index a30d382fb5ee1..a02ce3fb2358b 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -259,7 +259,8 @@ struct swap_info_struct { struct plist_node list; /* entry in swap_active_head */ signed char type; /* strange name for an index */ unsigned int max; /* extent of the swap_map */ - unsigned char *swap_map; /* vmalloc'ed array of usage counts */ + unsigned long *swap_map; /* bitmap for allocated state */ + unsigned long *bad_map; /* bitmap for bad state */ struct swap_cluster_info *cluster_info; /* cluster info. Only for SSD */ struct list_head free_clusters; /* free clusters list */ struct list_head full_clusters; /* full clusters list */ diff --git a/mm/swapfile.c b/mm/swapfile.c index 9478707ce3ffa..b7661ffa312be 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -760,25 +760,19 @@ static bool cluster_reclaim_range(struct swap_info_st= ruct *si, struct swap_cluster_info *ci, unsigned long start, unsigned long end) { - unsigned char *map =3D si->swap_map; unsigned long offset =3D start; int nr_reclaim; =20 spin_unlock(&ci->lock); do { - switch (READ_ONCE(map[offset])) { - case 0: + if (!test_bit(offset, si->swap_map)) { offset++; - break; - case SWAP_MAP_ALLOCATED: + } else { nr_reclaim =3D __try_to_reclaim_swap(si, offset, TTRS_ANYWAY); if (nr_reclaim > 0) offset +=3D nr_reclaim; else goto out; - break; - default: - goto out; } } while (offset < end); out: @@ -787,11 +781,7 @@ static bool cluster_reclaim_range(struct swap_info_str= uct *si, * Recheck the range no matter reclaim succeeded or not, the slot * could have been be freed while we are not holding the lock. */ - for (offset =3D start; offset < end; offset++) - if (READ_ONCE(map[offset])) - return false; - - return true; + return find_next_bit(si->swap_map, end, start) >=3D end; } =20 static bool cluster_scan_range(struct swap_info_struct *si, @@ -800,15 +790,16 @@ static bool cluster_scan_range(struct swap_info_struc= t *si, bool *need_reclaim) { unsigned long offset, end =3D start + nr_pages; - unsigned char *map =3D si->swap_map; - unsigned char count; =20 if (cluster_is_empty(ci)) return true; =20 for (offset =3D start; offset < end; offset++) { - count =3D READ_ONCE(map[offset]); - if (!count) + /* Bad slots cannot be used for allocation */ + if (test_bit(offset, si->bad_map)) + return false; + + if (!test_bit(offset, si->swap_map)) continue; =20 if (swap_cache_only(si, offset)) { @@ -841,7 +832,7 @@ static bool cluster_alloc_range(struct swap_info_struct= *si, struct swap_cluster if (cluster_is_empty(ci)) ci->order =3D order; =20 - memset(si->swap_map + start, usage, nr_pages); + bitmap_set(si->swap_map, start, nr_pages); swap_range_alloc(si, nr_pages); ci->count +=3D nr_pages; =20 @@ -1404,7 +1395,7 @@ static struct swap_info_struct *_swap_info_get(swp_sl= ot_t slot) offset =3D swp_slot_offset(slot); if (offset >=3D si->max) goto bad_offset; - if (data_race(!si->swap_map[swp_slot_offset(slot)])) + if (data_race(!test_bit(offset, si->swap_map))) goto bad_free; return si; =20 @@ -1518,8 +1509,7 @@ static void swap_slots_free(struct swap_info_struct *= si, swp_slot_t slot, unsigned int nr_pages) { unsigned long offset =3D swp_slot_offset(slot); - unsigned char *map =3D si->swap_map + offset; - unsigned char *map_end =3D map + nr_pages; + unsigned long end =3D offset + nr_pages; =20 /* It should never free entries across different clusters */ VM_BUG_ON(ci !=3D __swap_offset_to_cluster(si, offset + nr_pages - 1)); @@ -1527,10 +1517,8 @@ static void swap_slots_free(struct swap_info_struct = *si, VM_BUG_ON(ci->count < nr_pages); =20 ci->count -=3D nr_pages; - do { - VM_BUG_ON(!swap_is_last_ref(*map)); - *map =3D 0; - } while (++map < map_end); + VM_BUG_ON(find_next_zero_bit(si->swap_map, end, offset) < end); + bitmap_clear(si->swap_map, offset, nr_pages); =20 swap_range_free(si, offset, nr_pages); =20 @@ -1741,9 +1729,7 @@ unsigned int count_swap_pages(int type, int free) static bool swap_slot_allocated(struct swap_info_struct *si, unsigned long offset) { - unsigned char count =3D READ_ONCE(si->swap_map[offset]); - - return count && swap_count(count) !=3D SWAP_MAP_BAD; + return test_bit(offset, si->swap_map); } =20 /* @@ -2064,7 +2050,7 @@ static int setup_swap_extents(struct swap_info_struct= *sis, sector_t *span) } =20 static void setup_swap_info(struct swap_info_struct *si, int prio, - unsigned char *swap_map, + unsigned long *swap_map, struct swap_cluster_info *cluster_info) { si->prio =3D prio; @@ -2092,7 +2078,7 @@ static void _enable_swap_info(struct swap_info_struct= *si) } =20 static void enable_swap_info(struct swap_info_struct *si, int prio, - unsigned char *swap_map, + unsigned long *swap_map, struct swap_cluster_info *cluster_info) { spin_lock(&swap_lock); @@ -2185,7 +2171,8 @@ static void flush_percpu_swap_cluster(struct swap_inf= o_struct *si) SYSCALL_DEFINE1(swapoff, const char __user *, specialfile) { struct swap_info_struct *p =3D NULL; - unsigned char *swap_map; + unsigned long *swap_map; + unsigned long *bad_map; struct swap_cluster_info *cluster_info; struct file *swap_file, *victim; struct address_space *mapping; @@ -2280,6 +2267,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) p->swap_file =3D NULL; swap_map =3D p->swap_map; p->swap_map =3D NULL; + bad_map =3D p->bad_map; + p->bad_map =3D NULL; maxpages =3D p->max; cluster_info =3D p->cluster_info; p->max =3D 0; @@ -2290,7 +2279,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) mutex_unlock(&swapon_mutex); kfree(p->global_cluster); p->global_cluster =3D NULL; - vfree(swap_map); + kvfree(swap_map); + kvfree(bad_map); free_cluster_info(cluster_info, maxpages); =20 inode =3D mapping->host; @@ -2638,18 +2628,20 @@ static unsigned long read_swap_header(struct swap_i= nfo_struct *si, =20 static int setup_swap_map(struct swap_info_struct *si, union swap_header *swap_header, - unsigned char *swap_map, + unsigned long *swap_map, + unsigned long *bad_map, unsigned long maxpages) { unsigned long i; =20 - swap_map[0] =3D SWAP_MAP_BAD; /* omit header page */ + set_bit(0, bad_map); /* omit header page */ + for (i =3D 0; i < swap_header->info.nr_badpages; i++) { unsigned int page_nr =3D swap_header->info.badpages[i]; if (page_nr =3D=3D 0 || page_nr > swap_header->info.last_page) return -EINVAL; if (page_nr < maxpages) { - swap_map[page_nr] =3D SWAP_MAP_BAD; + set_bit(page_nr, bad_map); si->pages--; } } @@ -2753,7 +2745,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) int nr_extents; sector_t span; unsigned long maxpages; - unsigned char *swap_map =3D NULL; + unsigned long *swap_map =3D NULL, *bad_map =3D NULL; struct swap_cluster_info *cluster_info =3D NULL; struct folio *folio =3D NULL; struct inode *inode =3D NULL; @@ -2849,16 +2841,24 @@ SYSCALL_DEFINE2(swapon, const char __user *, specia= lfile, int, swap_flags) maxpages =3D si->max; =20 /* OK, set up the swap map and apply the bad block list */ - swap_map =3D vzalloc(maxpages); + swap_map =3D kvcalloc(BITS_TO_LONGS(maxpages), sizeof(long), GFP_KERNEL); if (!swap_map) { error =3D -ENOMEM; goto bad_swap_unlock_inode; } =20 - error =3D setup_swap_map(si, swap_header, swap_map, maxpages); + bad_map =3D kvcalloc(BITS_TO_LONGS(maxpages), sizeof(long), GFP_KERNEL); + if (!bad_map) { + error =3D -ENOMEM; + goto bad_swap_unlock_inode; + } + + error =3D setup_swap_map(si, swap_header, swap_map, bad_map, maxpages); if (error) goto bad_swap_unlock_inode; =20 + si->bad_map =3D bad_map; + if (si->bdev && bdev_stable_writes(si->bdev)) si->flags |=3D SWP_STABLE_WRITES; =20 @@ -2952,7 +2952,10 @@ SYSCALL_DEFINE2(swapon, const char __user *, special= file, int, swap_flags) si->swap_file =3D NULL; si->flags =3D 0; spin_unlock(&swap_lock); - vfree(swap_map); + if (swap_map) + kvfree(swap_map); + if (bad_map) + kvfree(bad_map); if (cluster_info) free_cluster_info(cluster_info, maxpages); if (inced_nr_rotate_swap) --=20 2.47.3