From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pj1-f50.google.com (mail-pj1-f50.google.com [209.85.216.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 1EE932777F9 for ; Fri, 5 Sep 2025 19:14:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.50 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099657; cv=none; b=Pl130S7l53Q3E5Z2OFSXQcPUtYMKb9K6NZWms2CQ3jchh+ZJ9OIK8gvfKrwdQC+yBW9F9ezMtZgrw9ngXFtil3x3CNeVFbJSfuhyA4wpuDPG6s7NZgVqee5c1LPlPr5cEqSyiKBoB7M8KosVGXNeVYD8rT4NLG/sxpkm83x9Ofo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099657; c=relaxed/simple; bh=r2PiSmvp7lENt4UzDGlEHexJO+ZJZ3uQ82kgLLOsfyM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=r80UmQbaeN011DVewH2TxzxT+aZHVGkIjO7MNL0Ad5DkicyhOLq3V+Tt4nsPidHcb457xH+HI7F/k2NyU/6LQlAGD3qtsDlx1wh8uFSW4ahjWUpzKEMBD6k2EE9syZ462WAS1wOQ5Nrd6iBsXgLvtudm0FB1LJXT6WfSLSaqz6E= 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=BZyifgjr; arc=none smtp.client-ip=209.85.216.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="BZyifgjr" Received: by mail-pj1-f50.google.com with SMTP id 98e67ed59e1d1-329b76008c6so1995316a91.1 for ; Fri, 05 Sep 2025 12:14:15 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099655; x=1757704455; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=mDUEHfmrXgAZbUz97jq88NraGjuVdKEjUr0PaaBBO7Q=; b=BZyifgjr1nFAe4mng897L94Ubo+zjSre4oZpgwdKENlERcI3o54Qal/sQQ9MtEzJtd 582Dek+k+gqYKzy/JjlgjB9T8YYk8Mzg25yMAJZ2oC3SULPly05XivS6mA7pJrvO4aEw zcv8hTIFvyzFWm15GR8+NOOoDJAENDMW43Vk0AEmQOmTRGMaay4wwwrcB3GFC6opP7H+ am0scKMHVEByEtx0K7ZBho4KpaSx+0keH5YzbGzOZOxzwTi+rxovn4R20PWny42CkIXx 0ze7l2/4xgvRD3q4HfeYNCHxwfo50cfd0sPPcdWDOVun4uz4LuvXeveNEbAU0BP34ZaR qquA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099655; x=1757704455; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=mDUEHfmrXgAZbUz97jq88NraGjuVdKEjUr0PaaBBO7Q=; b=X+VnGGAJFRYPGa1oX8E02YRnFyVil2ZPfaMQL6mO+kG8E7+0hl09RzbXm2grYsIdSt 2PfGkMogzkQNiv0UX/xck45em+KD/j5ZWNMqzOwSBh2wPGnmQI5hTVtMvHplaLJ+OCY+ hNqT1rYOPK/ps7hZj0P/uBMSFzrAnO9nQpwl5GiSnrWoJfYya0dj/euSyNrxbb9b/HIU K7kMgegNG94FtGblAzL+SVUmkRS2xkQ+7q6HwT/F0jrr19J97jfDwM6o29V08vvkYiLY Mcr9wXkWFIpQ53BsSvMfjPMo8CvGIRSVfWPcuCX3mCAxg5kZV6QZcLesL+VFZQyhXy38 nIaA== X-Forwarded-Encrypted: i=1; AJvYcCXR+RDpyYNhENayEG+lJ2xkEwHHuJDnx+CinjifceoPMAy4lFhuOvDiA3kjH+kuhb4/GTxrf4IJ/th5KO4=@vger.kernel.org X-Gm-Message-State: AOJu0YzBWfnpUw2XR8UGYM8vTFgTTBV4T5BS9f1J+0PFzzK6Kl5xfYLG m5snOAb0k7fBd/TK/uf7fiIOuBbrBHxbN1lKpgT4ysUYka4a8soBR57N X-Gm-Gg: ASbGncuQzKEQNo6rNTT390nGT+KBF8jL7nyfdwQmp2wgILNmd0DknVYIx7gColA6MxD 9EFfvc7nlVAML8m1biqzNneINEvWx1doGFS2HOqT3LbLPlr85OLd6Ws3gMniNOR+3cc7qmOAudO 9FA9bJDttj+I+VcmZx06zU9AiMd1fx2Cf5AWrqAYBugoW9FSM1W1tWIEdxlJQNWgEd9tJaFpqWG HlxPsrgHl3IkczfIUfFhGcxztQoSu3aQEDwEP5T9IfxCGEExeDOFxvwj1tsu7GVDILECRQJ+EGW P5WKbjZXF63FCJ0t4Y4UfjwdZMqE4CbarSFrCZ7XoJhI9jWQHWu6ZBcgSSWNO3bq1LzLEg49trr J8Nmpt0Y6vkQfSB4kF6mMEJX9tmAEP1UO2i14dye5N+atAt+9Ll3Fs8ts3Q== X-Google-Smtp-Source: AGHT+IFPaS/I+N/+xz/fo7KOHBQ+1G56h6y7Mrud0IexC4riD+dfbvjDQQ24r7ZekKYjTXvTtyxS7A== X-Received: by 2002:a17:90a:c2c7:b0:32b:dbf1:31b7 with SMTP id 98e67ed59e1d1-32d43f03db6mr11645a91.2.1757099655135; Fri, 05 Sep 2025 12:14:15 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.10 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:14 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 01/15] docs/mm: add document for swap table Date: Sat, 6 Sep 2025 03:13:43 +0800 Message-ID: <20250905191357.78298-2-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song From: Chris Li Swap table is the new swap cache. Signed-off-by: Chris Li Signed-off-by: Kairui Song Suggested-by: Chris Li --- Documentation/mm/swap-table.rst | 72 +++++++++++++++++++++++++++++++++ MAINTAINERS | 1 + 2 files changed, 73 insertions(+) create mode 100644 Documentation/mm/swap-table.rst diff --git a/Documentation/mm/swap-table.rst b/Documentation/mm/swap-table.= rst new file mode 100644 index 000000000000..929cd91aa984 --- /dev/null +++ b/Documentation/mm/swap-table.rst @@ -0,0 +1,72 @@ +.. 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 swap + outed folio. This is the normal state for a swap outed page. + +Swap Table +---------- + +The previous swap cache is implemented by XAray. 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. + +Each swap cluster contains 512 entries, so a swap table stores one cluster +worth of swap cache values, which is exactly one page. This is not +coincidental because the cluster size is determined by the huge page size. +The swap table is holding an array of pointers. The pointer has the same +size as the PTE. The size of the swap table should match to the second +last level of the page table page, exactly one page. + +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/MAINTAINERS b/MAINTAINERS index ec19be6c9917..1c8292c0318d 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -16219,6 +16219,7 @@ R: Barry Song R: Chris Li L: linux-mm@kvack.org S: Maintained +F: Documentation/mm/swap-table.rst F: include/linux/swap.h F: include/linux/swapfile.h F: include/linux/swapops.h --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f180.google.com (mail-pf1-f180.google.com [209.85.210.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 884822777F9 for ; Fri, 5 Sep 2025 19:14:21 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.180 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099667; cv=none; b=aSi9V4MzVrM5/LRs+17kg1osYO7wbBi1QZxHTekwzR7Ych8hfRPiJifKwsmiASImz3qXsvCZA+lx/e0urPA/QgK2TUxmN4llJqSK773fDV1jtYIsp47w+Dai8S9yaXTKf4wWT8hIUuFsjN68lzjHZAwVgZ8S7pXayX7w8g3zC1Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099667; c=relaxed/simple; bh=1LoHdPKo2zKz70TOHdTU9nuy8mSrJQdXii+sK06/mQA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=k/crbvNm8iz4Ax1stNwXNRePD713HuZaDjprTWwczAANylQbAnhmnXgkVbtA7RklxSnmeBVz8wjNZPAc+XSPEH+3j9BmGZ6MlpUmdX1wFOr1wJy3Wq17E3xNC+XNwjs4JQvWa93uoYtqLF7l8iQPgxtqI2eIuGGdN1cMewquujw= 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=h+xn4grU; arc=none smtp.client-ip=209.85.210.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="h+xn4grU" Received: by mail-pf1-f180.google.com with SMTP id d2e1a72fcca58-772301f8a4cso3348177b3a.3 for ; Fri, 05 Sep 2025 12:14:21 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099661; x=1757704461; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=oPAOWrCpwpbR9rVPMUrX0Qp8nhk8aV7LnM+BJcLKRk0=; b=h+xn4grU2vQosInH7IQCldOaygllWGhoEFLw6i8YexJ1kVRXgh/x83GmU1YoVu96Xq qIEtRGHkKiAA7dhb9NvSr0/DyIpzmn4nrREpNIs/0jq+PGjgjcKSxddNbznmUuESAJ7P +xxFM0BuRGbCbOqHq5AT5aBt3v7WneixGPyylXHr+WMwRE/77bFPXIwyC+Bfe19/hmCf ueEwLSQOiLP9HVmjiDJ334jMQztt9FFvM2mBcWofdK0CDbsD6IX5tQGwudwUSrS9a5zN jqV8qg5X1wQhQf1jBiriYDNcIq7QPF2+7EDypa0JK/f/RwgVa4FPBhEk8BxJ4V52THnj bulg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099661; x=1757704461; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=oPAOWrCpwpbR9rVPMUrX0Qp8nhk8aV7LnM+BJcLKRk0=; b=kDpPouF1n7oC4NFGdQ7/ksRMfzfOl23Iu5IYY4WCpD3zxrIsaCXoORxy+DPyt5Ap4m DMmP5hCV043lmtCZmZSTi7TorM1VmFWPT6+oWfV85Rk9VKUl2+GI8Qorrqdq3zZTD9H+ 7XAVuOMNrFxknN241vnKq93rhllJJnA5WniFPg9sreJ4jQ9EiX8sKrYcZaKjM6IHFzZn 68zSMJLQQurLJN9vPqfM0pV8l+nH4xCrPbdKb5fyhzfHZ8jV5e33k19Q2CdFwrtw46ZS MumUwl5/tGodPMEidp8zIqSmcHE9loVbhVcOA2gxHXvjtMuA2BN0xKWef3S+6cf8azZB chbA== X-Forwarded-Encrypted: i=1; AJvYcCVHkV0Uf7YihxJMupYaUFKwgbm1rgESo1XZSexqn6z3CVsqDWE4zB2dcb+TCL86rJjvFcB7DXwfDgZQBw0=@vger.kernel.org X-Gm-Message-State: AOJu0Yw5+nXfPh3xun8g7zf/TjQaWaRaVRqB5zoQawT/yYPIpxDy5XFm HNgR9M4igWOIwotNRcwL7J39Vw9WENA+cF55QKD5E7iX8Xa5TcJg8uU7 X-Gm-Gg: ASbGncvWzmyfBN7rFB5ejhg+HVAYEFjW1MpLjIKp8Q0CWX9jEBjyAkLKOz/4PgtCsBY 8bd6NFniWMilUAPgeojOokfORRZaSgAFCPWTGLO+R4dyY1DvW2TwIxQLQ8+LKCJwSTedna1MOb3 84F5MMhb13UVwQS+gy9s2dDt41gDdc3vesyWXEeHScExD9gyTAkX1xM6HSNVFOZe9GwyXM9dob6 O+K8tRfgCga+/oaOkk1S8sjikIOceNdX/XgmgsDSPeRFeeEj1NVDJINo+aB2tCOSZLuP1+Cta5n 5U1xbwnKhaw5Da0qc4eaPXXw3g37v+NJSZTc7LljJDIeKC03Sth4sDX3z5EaHNusxz3GhN4hPwK 4jWE6GorHUkqJBSJoeVF9B8R0yMO70BNFIIybxq3aYXK/aCtUmt3G+KDThw== X-Google-Smtp-Source: AGHT+IEVx2SUdnlXnTbUzYeaXXSinO95wJgf+dR2LlFdFQaVChU5ZU3mt8Ll6c0HJcL8428E5cqOnw== X-Received: by 2002:a05:6a00:848:b0:772:5d0f:6c9b with SMTP id d2e1a72fcca58-7725d0f6f0cmr23220397b3a.1.1757099660578; Fri, 05 Sep 2025 12:14:20 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.15 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:20 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 02/15] mm, swap: use unified helper for swap cache look up Date: Sat, 6 Sep 2025 03:13:44 +0800 Message-ID: <20250905191357.78298-3-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song The swap cache lookup helper swap_cache_get_folio currently does readahead updates as well, so callers that are not doing swapin from any VMA or mapping are forced to reuse filemap helpers instead, and have to access the swap cache space directly. So decouple readahead update with swap cache lookup. Move the readahead update part into a standalone helper. Let the caller call the readahead update helper if they do readahead. And convert all swap cache lookups to use swap_cache_get_folio. After this commit, there are only three special cases for accessing swap cache space now: huge memory splitting, migration, and shmem replacing, because they need to lock the XArray. The following commits will wrap their accesses to the swap cache too, with special helpers. And worth noting, currently dropbehind is not supported for anon folio, and we will never see a dropbehind folio in swap cache. The unified helper can be updated later to handle that. While at it, add proper kernedoc for touched helpers. No functional change. Signed-off-by: Kairui Song Acked-by: Chris Li Acked-by: Nhat Pham Reviewed-by: Baolin Wang Reviewed-by: Barry Song Acked-by: David Hildenbrand Suggested-by: Chris Li --- mm/memory.c | 6 ++- mm/mincore.c | 3 +- mm/shmem.c | 4 +- mm/swap.h | 13 ++++-- mm/swap_state.c | 109 +++++++++++++++++++++++++---------------------- mm/swapfile.c | 11 +++-- mm/userfaultfd.c | 5 +-- 7 files changed, 81 insertions(+), 70 deletions(-) diff --git a/mm/memory.c b/mm/memory.c index d9de6c056179..10ef528a5f44 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4660,9 +4660,11 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) if (unlikely(!si)) goto out; =20 - folio =3D swap_cache_get_folio(entry, vma, vmf->address); - if (folio) + folio =3D swap_cache_get_folio(entry); + if (folio) { + swap_update_readahead(folio, vma, vmf->address); page =3D folio_file_page(folio, swp_offset(entry)); + } swapcache =3D folio; =20 if (!folio) { diff --git a/mm/mincore.c b/mm/mincore.c index 2f3e1816a30d..8ec4719370e1 100644 --- a/mm/mincore.c +++ b/mm/mincore.c @@ -76,8 +76,7 @@ static unsigned char mincore_swap(swp_entry_t entry, bool= shmem) if (!si) return 0; } - folio =3D filemap_get_entry(swap_address_space(entry), - swap_cache_index(entry)); + folio =3D swap_cache_get_folio(entry); if (shmem) put_swap_device(si); /* The swap cache space contains either folio, shadow or NULL */ diff --git a/mm/shmem.c b/mm/shmem.c index 2df26f4d6e60..4e27e8e5da3b 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2354,7 +2354,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, } =20 /* Look it up and read it in.. */ - folio =3D swap_cache_get_folio(swap, NULL, 0); + folio =3D swap_cache_get_folio(swap); if (!folio) { if (data_race(si->flags & SWP_SYNCHRONOUS_IO)) { /* Direct swapin skipping swap cache & readahead */ @@ -2379,6 +2379,8 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, count_vm_event(PGMAJFAULT); count_memcg_event_mm(fault_mm, PGMAJFAULT); } + } else { + swap_update_readahead(folio, NULL, 0); } =20 if (order > folio_order(folio)) { diff --git a/mm/swap.h b/mm/swap.h index 1ae44d4193b1..efb6d7ff9f30 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -62,8 +62,7 @@ void delete_from_swap_cache(struct folio *folio); void clear_shadow_from_swap_cache(int type, unsigned long begin, unsigned long end); void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int n= r); -struct folio *swap_cache_get_folio(swp_entry_t entry, - struct vm_area_struct *vma, unsigned long addr); +struct folio *swap_cache_get_folio(swp_entry_t entry); 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); @@ -74,6 +73,8 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, g= fp_t flag, struct mempolicy *mpol, pgoff_t ilx); struct folio *swapin_readahead(swp_entry_t entry, gfp_t flag, struct vm_fault *vmf); +void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma, + unsigned long addr); =20 static inline unsigned int folio_swap_flags(struct folio *folio) { @@ -159,6 +160,11 @@ static inline struct folio *swapin_readahead(swp_entry= _t swp, gfp_t gfp_mask, return NULL; } =20 +static inline void swap_update_readahead(struct folio *folio, + struct vm_area_struct *vma, unsigned long addr) +{ +} + static inline int swap_writeout(struct folio *folio, struct swap_iocb **swap_plug) { @@ -169,8 +175,7 @@ static inline void swapcache_clear(struct swap_info_str= uct *si, swp_entry_t entr { } =20 -static inline struct folio *swap_cache_get_folio(swp_entry_t entry, - struct vm_area_struct *vma, unsigned long addr) +static inline struct folio *swap_cache_get_folio(swp_entry_t entry) { return NULL; } diff --git a/mm/swap_state.c b/mm/swap_state.c index 99513b74b5d8..68ec531d0f2b 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -69,6 +69,27 @@ 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 and check if the folio still matches the swap entry before + * use. + */ +struct folio *swap_cache_get_folio(swp_entry_t entry) +{ + struct folio *folio =3D filemap_get_folio(swap_address_space(entry), + swap_cache_index(entry)); + if (IS_ERR(folio)) + return NULL; + return folio; +} + void *get_shadow_from_swap_cache(swp_entry_t entry) { struct address_space *address_space =3D swap_address_space(entry); @@ -272,55 +293,43 @@ static inline bool swap_use_vma_readahead(void) return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap); } =20 -/* - * Lookup a swap entry in the swap cache. A found folio will be returned - * unlocked and with its refcount incremented - we rely on the kernel - * lock getting page table operations atomic even if we drop the folio - * lock before returning. - * - * Caller must lock the swap device or hold a reference to keep it valid. +/** + * swap_update_readahead - Update the readahead statistics of VMA or globa= lly. + * @folio: the swap cache folio that just got hit. + * @vma: the VMA that should be updated, could be NULL for global update. + * @addr: the addr that triggered the swapin, ignored if @vma is NULL. */ -struct folio *swap_cache_get_folio(swp_entry_t entry, - struct vm_area_struct *vma, unsigned long addr) +void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma, + unsigned long addr) { - struct folio *folio; - - folio =3D filemap_get_folio(swap_address_space(entry), swap_cache_index(e= ntry)); - if (!IS_ERR(folio)) { - bool vma_ra =3D swap_use_vma_readahead(); - bool readahead; + bool readahead, vma_ra =3D swap_use_vma_readahead(); =20 - /* - * At the moment, we don't support PG_readahead for anon THP - * so let's bail out rather than confusing the readahead stat. - */ - if (unlikely(folio_test_large(folio))) - return folio; - - readahead =3D folio_test_clear_readahead(folio); - if (vma && vma_ra) { - unsigned long ra_val; - int win, hits; - - ra_val =3D GET_SWAP_RA_VAL(vma); - win =3D SWAP_RA_WIN(ra_val); - hits =3D SWAP_RA_HITS(ra_val); - if (readahead) - hits =3D min_t(int, hits + 1, SWAP_RA_HITS_MAX); - atomic_long_set(&vma->swap_readahead_info, - SWAP_RA_VAL(addr, win, hits)); - } - - if (readahead) { - count_vm_event(SWAP_RA_HIT); - if (!vma || !vma_ra) - atomic_inc(&swapin_readahead_hits); - } - } else { - folio =3D NULL; + /* + * At the moment, we don't support PG_readahead for anon THP + * so let's bail out rather than confusing the readahead stat. + */ + if (unlikely(folio_test_large(folio))) + return; + + readahead =3D folio_test_clear_readahead(folio); + if (vma && vma_ra) { + unsigned long ra_val; + int win, hits; + + ra_val =3D GET_SWAP_RA_VAL(vma); + win =3D SWAP_RA_WIN(ra_val); + hits =3D SWAP_RA_HITS(ra_val); + if (readahead) + hits =3D min_t(int, hits + 1, SWAP_RA_HITS_MAX); + atomic_long_set(&vma->swap_readahead_info, + SWAP_RA_VAL(addr, win, hits)); } =20 - return folio; + if (readahead) { + count_vm_event(SWAP_RA_HIT); + if (!vma || !vma_ra) + atomic_inc(&swapin_readahead_hits); + } } =20 struct folio *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask, @@ -336,14 +345,10 @@ struct folio *__read_swap_cache_async(swp_entry_t ent= ry, gfp_t gfp_mask, *new_page_allocated =3D false; for (;;) { int err; - /* - * First check the swap cache. Since this is normally - * called after swap_cache_get_folio() failed, re-calling - * that would confuse statistics. - */ - folio =3D filemap_get_folio(swap_address_space(entry), - swap_cache_index(entry)); - if (!IS_ERR(folio)) + + /* Check the swap cache in case the folio is already there */ + folio =3D swap_cache_get_folio(entry); + if (folio) goto got_folio; =20 /* diff --git a/mm/swapfile.c b/mm/swapfile.c index a7ffabbe65ef..4b8ab2cb49ca 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -213,15 +213,14 @@ static int __try_to_reclaim_swap(struct swap_info_str= uct *si, unsigned long offset, unsigned long flags) { swp_entry_t entry =3D swp_entry(si->type, offset); - struct address_space *address_space =3D swap_address_space(entry); struct swap_cluster_info *ci; struct folio *folio; int ret, nr_pages; bool need_reclaim; =20 again: - folio =3D filemap_get_folio(address_space, swap_cache_index(entry)); - if (IS_ERR(folio)) + folio =3D swap_cache_get_folio(entry); + if (!folio) return 0; =20 nr_pages =3D folio_nr_pages(folio); @@ -2131,7 +2130,7 @@ static int unuse_pte_range(struct vm_area_struct *vma= , pmd_t *pmd, pte_unmap(pte); pte =3D NULL; =20 - folio =3D swap_cache_get_folio(entry, vma, addr); + folio =3D swap_cache_get_folio(entry); if (!folio) { struct vm_fault vmf =3D { .vma =3D vma, @@ -2357,8 +2356,8 @@ static int try_to_unuse(unsigned int type) (i =3D find_next_to_unuse(si, i)) !=3D 0) { =20 entry =3D swp_entry(type, i); - folio =3D filemap_get_folio(swap_address_space(entry), swap_cache_index(= entry)); - if (IS_ERR(folio)) + folio =3D swap_cache_get_folio(entry); + if (!folio) continue; =20 /* diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 50aaa8dcd24c..af61b95c89e4 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -1489,9 +1489,8 @@ static long move_pages_ptes(struct mm_struct *mm, pmd= _t *dst_pmd, pmd_t *src_pmd * separately to allow proper handling. */ if (!src_folio) - folio =3D filemap_get_folio(swap_address_space(entry), - swap_cache_index(entry)); - if (!IS_ERR_OR_NULL(folio)) { + folio =3D swap_cache_get_folio(entry); + if (folio) { if (folio_test_large(folio)) { ret =3D -EBUSY; folio_put(folio); --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pj1-f51.google.com (mail-pj1-f51.google.com [209.85.216.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 D1D9F1B0437 for ; Fri, 5 Sep 2025 19:14:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.51 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099668; cv=none; b=n3iMXb+XIZ58v5GJN27Ho7wEKOsZPrwDfeGbOKojOe4u/k2KTvh+hRyZvo0UFhAM6jGU6BBpQMhHgQo+C6NVDsxZXFNZZpeOOsiwgykAXr50t4kEtHR/P1a8LsGOyIvMSciWS0bSw8mDLvDyKCmpzD3WKBqtAo7NC+VY1QnZ88k= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099668; c=relaxed/simple; bh=3GSOhd9YKGJLP3uKPaY5KWa5kFw9s1KPG8wavA4BW1A=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=EVDyOpR4RufcOejAOSgzpP2/fT95XmBe4PtGV3B/LFX8KeLO1I4IKWcyxnLpwn+IFXrdaYpYGSlrQZdmwxWLLQPh957i6ywjZlRPbvN21QMDTX/GFJmjUYfogJRbsdX+QBfJl1rKGT4l4XVn2b7DuYfc+6sQHfiauM967z3WosE= 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=Wcy2vwDS; arc=none smtp.client-ip=209.85.216.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="Wcy2vwDS" Received: by mail-pj1-f51.google.com with SMTP id 98e67ed59e1d1-323266cdf64so2035161a91.0 for ; Fri, 05 Sep 2025 12:14:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099666; x=1757704466; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=V/6xkjxZiS4WkuxSj7iGXQCi48pk2b1g9CeSbkf+6vY=; b=Wcy2vwDSVxJj2zcrw12YOTCcSHzb/LIJhJvpOG2j38PEZzsvedfJG6sB+rJ46ubgu9 05Hupv1iPTQMQHSBvaG7Lw51emQvl2IGw0ndSkvqP5eUuiiY+jFVB7eCDHQuJfbh4IQL GN156vabYMYYQqkmUje9NdNakoZHMyAxg/S+0jXRwnsGxqk+YCT/6uhm9CwrPJTd2n8y Fndloy3/GZIeXSsUcpvnmJpkAjTZ0H73v+VmHqaosh+iLRfofX6MrLnUiM6nDO8alkxX KdyvZrA1uum8baJg/TN33OFH/3HdFPFXl0jXr1NgBipQXz864Ouw0CMju57SgI1WGw4Z plrQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099666; x=1757704466; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=V/6xkjxZiS4WkuxSj7iGXQCi48pk2b1g9CeSbkf+6vY=; b=rUY2bMAoIv+8DrFGzvAK/RhxeIKseDog232D8DEMqFjBZnvjhj62zeXfaYI1w3bMCb z18qJYDLaTySHK5F5VW8Vxo0Wrb9chJDhWNkihkwdUSEFd93D1vtjb4okM1EyoAZtZ16 /MiDMo82+yK0+5UhOA30oYXB3Qyb+nATZ01QIiX2lK8lcXGluoMffepIFgve+AkQ1l22 5zzN5BQf8q/nN1zjf6N8DKfFVR52bwaX3mBHkaG9cs8naLqarfgMB8iM0fUwD5gcBQdZ XdD1Xjpp9WtlfB/AqpbZnOTHDtSnti31evYQMbxtRG5nxuIQCXoeS331NaHUl4OGLmpg 6eVg== X-Forwarded-Encrypted: i=1; AJvYcCVWHl4EOn18IgdV/zVwoq0kYyDGQE79De6nIrwrN3zrhDHqOHmx+qPtB/LBD79/mqTC3CJD9iVG7qnlDro=@vger.kernel.org X-Gm-Message-State: AOJu0YxHlzMThZ6nPjAc1gZBEuzrLyTxNLQ5Zm2L+UNpj20+kRO+KEN/ 4Kcsccoi6g3c/HpWEtQ8d4Sp+M+F9BOmP5ZJBcwwYeR8vigYZxZ8kr+3 X-Gm-Gg: ASbGnctJZez6a1X+Q9pGx/q+ZFS3iU+gRr64ChBRZIOneLB496tGqy7arCcdn/ydp0p F96fBh7Jhx48/snEDMx7cxs+OAHFmcJ7ZMCD7Zt+/F0KqRsLNiYRuOQuomVk/kxe7MaILCYo5z/ c5VfWnxZoj7qL/T0NYvBzRwcWskBS4T/Pafi/xNN/kj7VaGea/qR80GrkLr9r9FIrTrCeJZdwAX ariAW2yyPqxbBz6M8CiKocg1KvPXDJs/oV8uIBLt8ByKq1gtDnrX6X6keAtx0GaXY98ykWLxuBs XuK+3Mpt/ylQoGsuLy8vxYLLkEf2rtBl0AfZ0sfICuHIILB+GZOkmObeLK0L5AjvaaqSfKVMTmv QWV8A0SSkcvxeZv4k+Q7yuISRBc+1IZayI6dnT4nadT3mZsU= X-Google-Smtp-Source: AGHT+IGAxCtVPjTCtyLUbjnAoA/ve5psp8+Ku1jl/RRWXT1povQsWgKxWs9snjl6Uh0QMXzMKbPaaA== X-Received: by 2002:a17:90b:380e:b0:329:d50e:2f24 with SMTP id 98e67ed59e1d1-329d51d757fmr22448731a91.24.1757099665908; Fri, 05 Sep 2025 12:14:25 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.20 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:25 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 03/15] mm, swap: fix swap cahe index error when retrying reclaim Date: Sat, 6 Sep 2025 03:13:45 +0800 Message-ID: <20250905191357.78298-4-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song The allocator will reclaim cached slots while scanning. Currently, it will try again if the reclaim found a folio that is already removed from the swap cache due to a race. But the following lookup will be using the wrong index. It won't cause any OOB issue since the swap cache index is truncated upon lookup, but it may lead to reclaiming of an irrelevant folio. This should not cause a measurable issue, but we should fix it. Fixes: fae8595505313 ("mm, swap: avoid reclaiming irrelevant swap cache") Signed-off-by: Kairui Song Acked-by: Chris Li Acked-by: David Hildenbrand Acked-by: Nhat Pham Reviewed-by: Baolin Wang Suggested-by: Chris Li --- mm/swapfile.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index 4b8ab2cb49ca..4c63fc62f4cb 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -240,13 +240,13 @@ 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. */ - entry =3D folio->swap; - if (offset < swp_offset(entry) || offset >=3D swp_offset(entry) + nr_page= s) { + if (offset < swp_offset(folio->swap) || + offset >=3D swp_offset(folio->swap) + nr_pages) { folio_unlock(folio); folio_put(folio); goto again; } - offset =3D swp_offset(entry); + offset =3D swp_offset(folio->swap); =20 need_reclaim =3D ((flags & TTRS_ANYWAY) || ((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) || --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f174.google.com (mail-pf1-f174.google.com [209.85.210.174]) (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 1AB2427B32B for ; Fri, 5 Sep 2025 19:14:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099673; cv=none; b=a6M1DelTN5MSdTrWbq9w8zzhUTAPAjlxyXEV4lDQ5zH6pppJ8u+KZ3/YmEew/WdU7dZEpKguirqL4hsJcl+3jI2NjvF5/AhvWzha9XZjBXO0dkNka8oTH6lIQ4A79+z/sAwSy03fvgCEWghSEPqE5ZNlrHknOgQasPPPHP/6Fac= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099673; c=relaxed/simple; bh=cdVNCZWUbrIO+GqQrsJ3wMQ2ulxyBF4oP4toSJvz1Q4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=ni+MiATWlxjPkDk7wCQ9wdoXsnIqqdPVqw0aAfI8KOeJtmrK9iOVevRSSLj4JZ+hhU7qNYFhlrFj9WGs0UGD2UwBabuf66RWQZ3UC0JbSCMXGYjWGv5J0cWLIMPGqAaL6yZTrQEbkOw2ccqTKQj8Tjdye/MKCZxaRrhgUEupCzw= 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=T8mo2bsR; arc=none smtp.client-ip=209.85.210.174 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="T8mo2bsR" Received: by mail-pf1-f174.google.com with SMTP id d2e1a72fcca58-77287fb79d3so2219335b3a.1 for ; Fri, 05 Sep 2025 12:14:31 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099671; x=1757704471; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=1hz/rwuCJ+AfNnA/+slxKdJ9Vt8t8OYTTKbWi35Lmcc=; b=T8mo2bsRtz38GJIcxKYcTHgb0co1EWHGgJjpqiAcWHJhuPumElp6W/g9bzbzwy2YQG PNnnwCIgQ31S5RhGsgjH31v+IepJTdVy7t72ClRz8F7XhnJdhbh9x3uonD6nvKtqwcWn s1jblVJ8uhRSZ4DqenJgw1AYugwDhJGroxI90Z6lvRKYYxWO9rIw/o3Lg7s++xc8dKNE KMKLT56uGCsF+CTFk0YRMZEQQkR6iVrBiApi2TkCxAio4eGHfqzZqmaG4mKl5Yn1Nlxd hllBsPiWjf3mYr/uqIAUSN+Td7qMpkZFFXorrk/G34mmTaMNJXgsm62lNS9u4aAjSCox 6qtg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099671; x=1757704471; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=1hz/rwuCJ+AfNnA/+slxKdJ9Vt8t8OYTTKbWi35Lmcc=; b=iyQGWZFSjtGQr1OXd+8siBFUzf4vMKrsA5a3swX+dOopTRmPwrDpnVdSSiwT8cL7/G fE6NhEqOxCaohhneYAug2R79cmYCjtMY3QLWZgQdMdNbLlbl1ObVlL3ByTv0nstTYApM 9JOgcf2ionqUnGjnKiSdLmtyFaBylvFlCEq+R7a5kV1CXvrNi4FWE03QY1nM34qs93wu K7mgSnqcQyd8komQVlSdM49+M+ZQSQnfMZU1wVrrNxh0oHKmIRKs7jNAlwQ5PaDJYf32 E0gQt0nynolnq25oXqwXHKJdpYfJAR9iyVn2hz28D6Q8jNOLU1nChoJWSyKh+yQRRU1W F0oA== X-Forwarded-Encrypted: i=1; AJvYcCW9+XYpC9fCk97q8k+8LB/L1zWmrvr65ZUsSKLDQmP3AUUaE1xcwFgdA5OWyneI1TsVbBA+zPp4ZUJemiQ=@vger.kernel.org X-Gm-Message-State: AOJu0Ywtg8t2IyI4J4ntDSWTMx9+qHbktLxM0gqTF2xlsrGHMbILoGns VARu7Ai3b84jcp18hDPkNuvd70kWLdmncWdTlECclC/TvjQ+lIE1QCzf X-Gm-Gg: ASbGncsVAkLi2mihKYCMOacc5bKtP9Ubl4nykq+otH9PSlnEpu62r99Gwnf/+HZWANq RTkNnwGR+9uf1L2EJSmsfNXgxCwjHprBXUOTbUT/S4IEvoPoEAYS3+BM2yXvKPUGlUXcNz2e8kR SL1LK8gv/De6uj1p6SEeQ2X7/eCvqpa9JsnL0xhzj/MwgTFcu7sw2pKCkAOUJzLRu2BldB+LNU4 TVdQYb3nXfKzDjnctADKXpK2FMUh5RumSSY/8BJ+5V6Pft1gYlFd1mL7jZF2fIs+1IDiKmlsYvE 5irtfvqCf+n1iIG5IYGIxLgpxIsHZvoNS9l9EmOI0jwrypMJPefQ3ZVS7GPgNqZ3rj2Oc4zIlK7 bfzLZ8a/9kGyX2Z2TogtrYwvFewVg14SFwFHuhT/b4CgQse4lEPxmBQoEiQ== X-Google-Smtp-Source: AGHT+IGfH9fV1AgSl0wv8tqYCRcHQb5tSEyNj8zQqgrgjfFl5SnhdLgFSlUza4Y9ihJjnD8NLMJuyQ== X-Received: by 2002:a05:6a00:984:b0:772:5a3f:7cbb with SMTP id d2e1a72fcca58-7725a3f84f0mr27740818b3a.6.1757099671272; Fri, 05 Sep 2025 12:14:31 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.26 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:30 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 04/15] mm, swap: check page poison flag after locking it Date: Sat, 6 Sep 2025 03:13:46 +0800 Message-ID: <20250905191357.78298-5-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song Instead of checking the poison flag only in the fast swap cache lookup path, always check the poison flags after locking a swap cache folio. There are two reasons to do so. The folio is unstable and could be removed from the swap cache anytime, so it's totally possible that the folio is no longer the backing folio of a swap entry, and could be an irrelevant poisoned folio. We might mistakenly kill a faulting process. And it's totally possible or even common for the slow swap in path (swapin_readahead) to bring in a cached folio. The cache folio could be poisoned, too. Only checking the poison flag in the fast path will miss such folios. The race window is tiny, so it's very unlikely to happen, though. While at it, also add a unlikely prefix. Signed-off-by: Kairui Song Acked-by: Chris Li Suggested-by: Chris Li --- mm/memory.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/mm/memory.c b/mm/memory.c index 10ef528a5f44..94a5928e8ace 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4661,10 +4661,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) goto out; =20 folio =3D swap_cache_get_folio(entry); - if (folio) { + if (folio) swap_update_readahead(folio, vma, vmf->address); - page =3D folio_file_page(folio, swp_offset(entry)); - } swapcache =3D folio; =20 if (!folio) { @@ -4735,20 +4733,13 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) ret =3D VM_FAULT_MAJOR; count_vm_event(PGMAJFAULT); count_memcg_event_mm(vma->vm_mm, PGMAJFAULT); - page =3D folio_file_page(folio, swp_offset(entry)); - } else if (PageHWPoison(page)) { - /* - * hwpoisoned dirty swapcache pages are kept for killing - * owner processes (which may be unknown at hwpoison time) - */ - ret =3D VM_FAULT_HWPOISON; - goto out_release; } =20 ret |=3D folio_lock_or_retry(folio, vmf); if (ret & VM_FAULT_RETRY) goto out_release; =20 + page =3D folio_file_page(folio, swp_offset(entry)); if (swapcache) { /* * Make sure folio_free_swap() or swapoff did not release the @@ -4761,6 +4752,15 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) page_swap_entry(page).val !=3D entry.val)) goto out_page; =20 + if (unlikely(PageHWPoison(page))) { + /* + * hwpoisoned dirty swapcache pages are kept for killing + * owner processes (which may be unknown at hwpoison time) + */ + ret =3D VM_FAULT_HWPOISON; + goto out_page; + } + /* * KSM sometimes has to copy on read faults, for example, if * folio->index of non-ksm folios would be nonlinear inside the --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pg1-f170.google.com (mail-pg1-f170.google.com [209.85.215.170]) (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 9120327B32B for ; Fri, 5 Sep 2025 19:14:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.170 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099679; cv=none; b=tN2nPM7/N+kD/sl3aj4XadxURLY5QH4UN06bGP0e6+wxewR50GNrWuntnSSpOepnPNUaTUek0wpJkmJmHbtQrdJamKIYGMPb1vGYI73oNMCPlM0Z6CdbiRaAq3OvtMpB1HS3h+4SSnWGDh+PfA0kbjUuGaaR4qio1sIjYnxQy0o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099679; c=relaxed/simple; bh=4KpjepTCIfFn2CYzGFPHQ95P8vG1TGauuBTZWpu7bfY=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=erjSVq5hCcF2XlnYoXkCIukzrTnW5y5GVcj8Iu4cYjiZQgl5CLz+7n/3jvMUh+tNNpDB/DZZPYTqIsCgdXw0XCY7RDjEjIcTcAm94IVft42DWUg6gujncUDoW3zEWjp8NMPwwpApIOxeGL7WmA3ojj9eZFhnlD9HNERDV1db1OA= 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=nBOi0Hli; arc=none smtp.client-ip=209.85.215.170 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="nBOi0Hli" Received: by mail-pg1-f170.google.com with SMTP id 41be03b00d2f7-b52196e8464so391411a12.3 for ; Fri, 05 Sep 2025 12:14:37 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099677; x=1757704477; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=qcBRC1dfTG2s+aFL1L7sgVVmaFlNWBkL9Ua/k3R9Js8=; b=nBOi0HliRzXtnNrW22gPoEkHJeH3o6ts4kC970AI+el4sOg2kAfpDtsO68X0oObCiq pd+V4fQPQ/QDcGWzl/DWEq2c+AOd5HWCGiM6mBwqUlgm+PAmpdssOY3gQ00/zp2r6+o7 +9Os10EFW8thI2A+bsQY1oX6rpbHB+YC9tMHCRNpL43MV9vTNcsyg8MRiLbrrnHhHRmp ulMcxiNBjP6WLw4pl1K4bAJi/T29LWMRQuANFEo/k/Rzn3wm/9rYq71YDWKuz225+Bdt IaepBA5Icc/kxtMUlKUlnnh3g0sMc4ayklUGUI7DSJTCNADlUuQtUa78LaHQehmjFH5R X6tg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099677; x=1757704477; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=qcBRC1dfTG2s+aFL1L7sgVVmaFlNWBkL9Ua/k3R9Js8=; b=ZFJTBGZpqH4wSM+szCEiw4QC8lA8vqSBdoOlU5DbImI9r1wZwDa7DaFMK1rY76NCPv UUd8ZyFGe8bybCvPTJqIb09PFgLunV4Reh3zieztMY37bFsNwId4ATOH2imRRaoovVMh +9Xkomt6C+IprgWsT/WS8jqLGSxSpLt7t11yCmrBwV3U8ooIrdB8ieoATOaSW1v20azB 4BkQA92BbbeEvOj1Aejcg9rA4Ih1250M9afdk5qKr9ZZBJrRpr7JKTMaiUFDM+89ll5W kqgoiXfjljj2SYjIv5zNT8m9GCg1w7WeuyZOZXHrlpQvQw2g87xaS92Ru6rrMEclnBK2 mPfg== X-Forwarded-Encrypted: i=1; AJvYcCUB3v2F1DM76MchgYB0j6Hwp0mvjhNHZ3rz8VYm0LSpNcMWX1Ocuq1nfPiv8sc546odI0vmZX+Z0YcygRI=@vger.kernel.org X-Gm-Message-State: AOJu0Yz9/31U/G/Fq0A6fCfAWjnvfCZ9/LwmetWBoEe50ooixiouFHxh f4ED495h24IYLSEfVW4FFtLDsODpdpbX/9kNm9C8KDTovLLklMakxX84 X-Gm-Gg: ASbGnculTJ65gJwTDMFo4Zy011gZYs+qU3UcCxfsnqH8GOaEito6LkuPEQ8zUYC6y9P LSHTPsfzQG890qzM+q0UhL+UcKVegZeKvL94GseaUG9akBKwe4LZPNd7xFBU6eEXaWJoHkGW7lW Fft2crYsy2H4nl/P3GRV4m5ZyJzxObuH4jUR0uETNEz8F6AuBNtAg2p0lAOMWgnYVfVUbzHDg4m gYMVhDI51EBcVaeCmV6gcNIl5zZPTbj2lUsnv+89z0eG9wfNcMbiuYEjgFuRad4nvP7mZlGVeQm jobpkh61WwRJPOWUS9ZSC31+rzi6RGbqvXNqYtOcJq/5qpct5uF5UM4JZO0g5kxCwCcSmyZBk0N rs/smyOetj481JsM68iCov6QQtkC1WDlcXmaP5WsTElDZEPI= X-Google-Smtp-Source: AGHT+IH0gGzdjlZMueDj/hSEJuQyIDnEEPfDmDuK23QnXLBRkJurBKBb+WQfJlSWK4T1Xzn33MtTuA== X-Received: by 2002:a17:90b:51c4:b0:32b:98a3:7409 with SMTP id 98e67ed59e1d1-32b98a37612mr8823618a91.34.1757099676730; Fri, 05 Sep 2025 12:14:36 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.31 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:36 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 05/15] mm, swap: always lock and check the swap cache folio before use Date: Sat, 6 Sep 2025 03:13:47 +0800 Message-ID: <20250905191357.78298-6-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song Swap cache lookup only increases the reference count of the returned folio. That's not enough to ensure a folio is stable in the swap cache, so the folio could be removed from the swap cache at any time. The caller should always lock and check the folio before using it. We have just documented this in kerneldoc, now introduce a helper for swap cache folio verification with proper sanity checks. Also, sanitize a few current users to use this convention and the new helper for easier debugging. They were not having observable problems yet, only trivial issues like wasted CPU cycles on swapoff or reclaiming. They would fail in some other way, but it is still better to always follow this convention to make things robust and make later commits easier to do. Signed-off-by: Kairui Song Acked-by: Chris Li Suggested-by: Chris Li --- mm/memory.c | 3 +-- mm/swap.h | 24 ++++++++++++++++++++++++ mm/swap_state.c | 7 +++++-- mm/swapfile.c | 10 +++++++--- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/mm/memory.c b/mm/memory.c index 94a5928e8ace..5808c4ef21b3 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4748,8 +4748,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) * swapcache, we need to check that the page's swap has not * changed. */ - if (unlikely(!folio_test_swapcache(folio) || - page_swap_entry(page).val !=3D entry.val)) + if (unlikely(!folio_matches_swap_entry(folio, entry))) goto out_page; =20 if (unlikely(PageHWPoison(page))) { diff --git a/mm/swap.h b/mm/swap.h index efb6d7ff9f30..a69e18b12b45 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -52,6 +52,25 @@ static inline pgoff_t swap_cache_index(swp_entry_t entry) return swp_offset(entry) & SWAP_ADDRESS_SPACE_MASK; } =20 +/** + * folio_matches_swap_entry - Check if a folio matches a given swap entry. + * @folio: The folio. + * @entry: The swap entry 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 or false. + */ +static inline bool folio_matches_swap_entry(const struct folio *folio, + swp_entry_t entry) +{ + VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); + if (!folio_test_swapcache(folio)) + return false; + VM_WARN_ON_ONCE_FOLIO(!IS_ALIGNED(folio->swap.val, folio_nr_pages(folio))= , folio); + return folio->swap.val =3D=3D round_down(entry.val, folio_nr_pages(folio)= ); +} + void show_swap_cache_info(void); void *get_shadow_from_swap_cache(swp_entry_t entry); int add_to_swap_cache(struct folio *folio, swp_entry_t entry, @@ -144,6 +163,11 @@ static inline pgoff_t swap_cache_index(swp_entry_t ent= ry) return 0; } =20 +static inline bool folio_matches_swap_entry(const struct folio *folio, swp= _entry_t entry) +{ + return false; +} + static inline void show_swap_cache_info(void) { } diff --git a/mm/swap_state.c b/mm/swap_state.c index 68ec531d0f2b..9225d6b695ad 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -79,7 +79,7 @@ void show_swap_cache_info(void) * 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. + * use (e.g. with folio_matches_swap_entry). */ struct folio *swap_cache_get_folio(swp_entry_t entry) { @@ -346,7 +346,10 @@ struct folio *__read_swap_cache_async(swp_entry_t entr= y, gfp_t gfp_mask, for (;;) { int err; =20 - /* Check the swap cache in case the folio is already there */ + /* + * Check the swap cache first, if a cached folio is found, + * return it unlocked. The caller will lock and check it. + */ folio =3D swap_cache_get_folio(entry); if (folio) goto got_folio; diff --git a/mm/swapfile.c b/mm/swapfile.c index 4c63fc62f4cb..1bd90f17440f 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -240,14 +240,12 @@ 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. */ - if (offset < swp_offset(folio->swap) || - offset >=3D swp_offset(folio->swap) + nr_pages) { + if (!folio_matches_swap_entry(folio, entry)) { folio_unlock(folio); folio_put(folio); goto again; } offset =3D swp_offset(folio->swap); - need_reclaim =3D ((flags & TTRS_ANYWAY) || ((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) || ((flags & TTRS_FULL) && mem_cgroup_swap_full(folio))); @@ -2150,6 +2148,12 @@ static int unuse_pte_range(struct vm_area_struct *vm= a, pmd_t *pmd, } =20 folio_lock(folio); + if (!folio_matches_swap_entry(folio, entry)) { + folio_unlock(folio); + folio_put(folio); + continue; + } + folio_wait_writeback(folio); ret =3D unuse_pte(vma, pmd, addr, entry, folio); if (ret < 0) { --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f176.google.com (mail-pf1-f176.google.com [209.85.210.176]) (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 368E5280339 for ; Fri, 5 Sep 2025 19:14:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.176 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099685; cv=none; b=dNgPkmaIFyZTUSrRthHrm9ffOss7Kmp/OeCbx5YW1kZ4VV80yifw7cB04u8daZ2MpqFeCtoFi0czkYr+/vSU30zBtoLHWuosKZRwAPX7Y5LPuX/VpYpIbNBBvUpEfyIPKdvBCDBocIxmXUadrMeTKDkGay4b9Kzw9xjs5Q8gEE8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099685; c=relaxed/simple; bh=HjAkCiKreUoJyDEivAofk+EGvLIortYa6b1SPhd5BSc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=DCUPejG8a33RDLzhl6ZtLesljdrep9QeQ6fk7lDmzuXwBuyYucjtj8/b4SlND9Z2wfUcWHF30qUiIEZK4fF4suEBVmlIt1LsN9F3TQoEjpIGdJlo4YM5Atul9xul/RZHgAXvPpj+GCEdIbpLG6UlWzrqv0NIshL9fgwiaQWFvic= 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=Eh0CTWXy; arc=none smtp.client-ip=209.85.210.176 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="Eh0CTWXy" Received: by mail-pf1-f176.google.com with SMTP id d2e1a72fcca58-772488c78bcso2456523b3a.1 for ; Fri, 05 Sep 2025 12:14:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099682; x=1757704482; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=ZXCjnErSqW7lrOTzOAfqkITRvdAoHNXzorUyab5yxLY=; b=Eh0CTWXysjaHdiBR69ens2c8h3wfQ5hebFNRklR9sCwmZfGnc3z+C7QQvd3LnLS3SP PrIv3l9iFRLJrsfAcmem0NKwQqFFPTR96GpLZErRrTLPtxK2qCCGUCl74PQo+XbiyB+y N85u96e3rg6b1opPeF9eiV3dIij6KC48x9mUx5aDt+ynoUrAsdQqmR+U0QH3YftRKCaS Vwkim0BaURTrTphkjg9WUpjYG09GN5L+TuBO0KqDDXKvUW7qJs/+1tvHeKsThoy//Pcy 7usHmWOo4WLJCh2jYqEjLmTdwIs9yY2IlEIk/qOsEp0WqAGta5N1fegrBl8k7TI2h9sj 4UWQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099682; x=1757704482; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=ZXCjnErSqW7lrOTzOAfqkITRvdAoHNXzorUyab5yxLY=; b=cBN2ZhiwiB8geewbwJhDjbqLTvpWYfGgT8cbbo1Zgg92KyKMbDxKvnXjhWHJrDUCM2 LYHEjf4fT5DhSVmntvhUnv92G9/RQKK5iIFAYS8SA4Yce26CAPdCC7H1thbKvCFREq5t 3QxCWYp02chcuwY1Mzj87hSRe3PpXBKC9uCBvxLrJDY4hDEoszulgQvI6Jd5rYQicDBU OF6/QhE8V3PScvKQWurt/WFrWcUKSnJdEKTjSV8r+uT8G14TkxP9CFQFrtp6eDZ1Lmma xixQzaEnv8lBdxEQQLksfpJp39PjPugo0JAfcB2MW6GLrVEmj/E2HNXaNn4A257YTOlv f+7g== X-Forwarded-Encrypted: i=1; AJvYcCUNqRzeJK4Rm0E4DU+EYrpFwS5/SqkPFrUTvnXIiGIZXnLm/3Y0knThoDy/ox7su3dfPL/5JygOEMZJEe0=@vger.kernel.org X-Gm-Message-State: AOJu0YyLDvsSLx/J520bldh08AM+5yDT5U5efS8XIHVhjZUbxZ/mIMaS S6y7chy5+jo90xg4y/xB9lqiLBTvMgsjqnswUXsLsHYNBo/KgaE0Tzzm X-Gm-Gg: ASbGncsSzAUvu6Pejb5UA7YF1jrEbvbtjPerwfCCjXq+bmjeNqmowiDNTw2v5jNEXGs 2qB1Kl8jEd0l/D+3TUiWAAS/E5HTNc0yipw1BBioHiosEy0rOLcxo3ZH3gUqIWr6w4vsYIQDKns rMFT8mT27TlEvPJLyUh94jmfHKod/HHyePGPEMUXdcyJknRB6mLvZJh4jWeaAy3knjSQID1DnHb bnQitMnljx40arJwLPIjCVWy1QVxnY4L2B9fN9n8z1zfLpphKZC9e0QPDg5X83k1+D7pFKFOXYI t2+tExPz2djS45GdMoL73Fekf8LI1zaCyyRA51mekNyCHuT0LPQoekadu2VrBAgBJY7Eb2vv7jh gIo9Zcp2D5wlN6GqULV3dfxHv2G4DaINVZh3Z5/nIi1u3hyIjMY+rybm+Sg== X-Google-Smtp-Source: AGHT+IEBYA0uesip3wIKaccDeR63V4mHmwyoEjZ2FLF3Pja8XPH7B2M+y/xcl5swlQp/VY6U0RNV9A== X-Received: by 2002:a05:6a00:2e2a:b0:772:5fad:e6d7 with SMTP id d2e1a72fcca58-7725fadf0a9mr29719836b3a.32.1757099682203; Fri, 05 Sep 2025 12:14:42 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.37 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:41 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 06/15] mm, swap: rename and move some swap cluster definition and helpers Date: Sat, 6 Sep 2025 03:13:48 +0800 Message-ID: <20250905191357.78298-7-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song No feature change, move cluster related definitions and helpers to mm/swap.h, also tidy up and add a "swap_" prefix for cluster lock/unlock helpers, so they can be used outside of swap files. And while at it, add kerneldoc. Signed-off-by: Kairui Song Acked-by: Chris Li Reviewed-by: Barry Song Acked-by: David Hildenbrand Reviewed-by: Baolin Wang Suggested-by: Chris Li --- include/linux/swap.h | 34 ---------------- mm/swap.h | 70 ++++++++++++++++++++++++++++++++ mm/swapfile.c | 97 +++++++++++++------------------------------- 3 files changed, 99 insertions(+), 102 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 23452f014ca1..7e1fe4ff3d30 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -235,40 +235,6 @@ enum { /* Special value in each swap_map continuation */ #define SWAP_CONT_MAX 0x7f /* Max count */ =20 -/* - * We use this to track usage of a cluster. A cluster is a block of swap d= isk - * space with SWAPFILE_CLUSTER pages long and naturally aligns in disk. All - * free clusters are organized into a list. We fetch an entry from the lis= t to - * get a free cluster. - * - * The flags field determines if a cluster is free. This is - * protected by cluster lock. - */ -struct swap_cluster_info { - spinlock_t lock; /* - * Protect swap_cluster_info fields - * other than list, and swap_info_struct->swap_map - * elements corresponding to the swap cluster. - */ - u16 count; - u8 flags; - u8 order; - struct list_head list; -}; - -/* All on-list cluster must have a non-zero flag. */ -enum swap_cluster_flags { - CLUSTER_FLAG_NONE =3D 0, /* For temporary off-list cluster */ - CLUSTER_FLAG_FREE, - CLUSTER_FLAG_NONFULL, - CLUSTER_FLAG_FRAG, - /* Clusters with flags above are allocatable */ - CLUSTER_FLAG_USABLE =3D CLUSTER_FLAG_FRAG, - CLUSTER_FLAG_FULL, - CLUSTER_FLAG_DISCARD, - CLUSTER_FLAG_MAX, -}; - /* * The first page in the swap file is the swap header, which is always mar= ked * bad to prevent it from being allocated as an entry. This also prevents = the diff --git a/mm/swap.h b/mm/swap.h index a69e18b12b45..39b27337bc0a 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -7,10 +7,80 @@ struct swap_iocb; =20 extern int page_cluster; =20 +#ifdef CONFIG_THP_SWAP +#define SWAPFILE_CLUSTER HPAGE_PMD_NR +#define swap_entry_order(order) (order) +#else +#define SWAPFILE_CLUSTER 256 +#define swap_entry_order(order) 0 +#endif + +/* + * We use this to track usage of a cluster. A cluster is a block of swap d= isk + * space with SWAPFILE_CLUSTER pages long and naturally aligns in disk. All + * free clusters are organized into a list. We fetch an entry from the lis= t to + * get a free cluster. + * + * The flags field determines if a cluster is free. This is + * protected by cluster lock. + */ +struct swap_cluster_info { + spinlock_t lock; /* + * Protect swap_cluster_info fields + * other than list, and swap_info_struct->swap_map + * elements corresponding to the swap cluster. + */ + u16 count; + u8 flags; + u8 order; + struct list_head list; +}; + +/* All on-list cluster must have a non-zero flag. */ +enum swap_cluster_flags { + CLUSTER_FLAG_NONE =3D 0, /* For temporary off-list cluster */ + CLUSTER_FLAG_FREE, + CLUSTER_FLAG_NONFULL, + CLUSTER_FLAG_FRAG, + /* Clusters with flags above are allocatable */ + CLUSTER_FLAG_USABLE =3D CLUSTER_FLAG_FRAG, + CLUSTER_FLAG_FULL, + CLUSTER_FLAG_DISCARD, + CLUSTER_FLAG_MAX, +}; + #ifdef CONFIG_SWAP #include /* for swp_offset */ #include /* for bio_end_io_t */ =20 +static inline struct swap_cluster_info *swp_offset_cluster( + struct swap_info_struct *si, pgoff_t offset) +{ + return &si->cluster_info[offset / SWAPFILE_CLUSTER]; +} + +/** + * 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. + * + * Context: The caller must ensure the offset is in the valid range and + * protect the swap device with reference count or locks. + */ +static inline struct swap_cluster_info *swap_cluster_lock( + struct swap_info_struct *si, unsigned long offset) +{ + struct swap_cluster_info *ci =3D swp_offset_cluster(si, offset); + + spin_lock(&ci->lock); + return ci; +} + +static inline void swap_cluster_unlock(struct swap_cluster_info *ci) +{ + spin_unlock(&ci->lock); +} + /* linux/mm/page_io.c */ int sio_pool_init(void); struct swap_iocb; diff --git a/mm/swapfile.c b/mm/swapfile.c index 1bd90f17440f..547ad4bfe1d8 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -58,9 +58,6 @@ static void swap_entries_free(struct swap_info_struct *si, static void swap_range_alloc(struct swap_info_struct *si, unsigned int nr_entries); static bool folio_swapcache_freeable(struct folio *folio); -static struct swap_cluster_info *lock_cluster(struct swap_info_struct *si, - unsigned long offset); -static inline void unlock_cluster(struct swap_cluster_info *ci); =20 static DEFINE_SPINLOCK(swap_lock); static unsigned int nr_swapfiles; @@ -257,9 +254,9 @@ static int __try_to_reclaim_swap(struct swap_info_struc= t *si, * 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. */ - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); need_reclaim =3D swap_only_has_cache(si, offset, nr_pages); - unlock_cluster(ci); + swap_cluster_unlock(ci); if (!need_reclaim) goto out_unlock; =20 @@ -384,19 +381,6 @@ static void discard_swap_cluster(struct swap_info_stru= ct *si, } } =20 -#ifdef CONFIG_THP_SWAP -#define SWAPFILE_CLUSTER HPAGE_PMD_NR - -#define swap_entry_order(order) (order) -#else -#define SWAPFILE_CLUSTER 256 - -/* - * Define swap_entry_order() as constant to let compiler to optimize - * out some code if !CONFIG_THP_SWAP - */ -#define swap_entry_order(order) 0 -#endif #define LATENCY_LIMIT 256 =20 static inline bool cluster_is_empty(struct swap_cluster_info *info) @@ -424,34 +408,12 @@ static inline unsigned int cluster_index(struct swap_= info_struct *si, return ci - si->cluster_info; } =20 -static inline struct swap_cluster_info *offset_to_cluster(struct swap_info= _struct *si, - unsigned long offset) -{ - return &si->cluster_info[offset / SWAPFILE_CLUSTER]; -} - static inline unsigned int cluster_offset(struct swap_info_struct *si, struct swap_cluster_info *ci) { return cluster_index(si, ci) * SWAPFILE_CLUSTER; } =20 -static inline struct swap_cluster_info *lock_cluster(struct swap_info_stru= ct *si, - unsigned long offset) -{ - struct swap_cluster_info *ci; - - ci =3D offset_to_cluster(si, offset); - spin_lock(&ci->lock); - - return ci; -} - -static inline void unlock_cluster(struct swap_cluster_info *ci) -{ - spin_unlock(&ci->lock); -} - static void move_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci, struct list_head *list, enum swap_cluster_flags new_flags) @@ -807,7 +769,7 @@ static unsigned int alloc_swap_scan_cluster(struct swap= _info_struct *si, } out: relocate_cluster(si, ci); - unlock_cluster(ci); + swap_cluster_unlock(ci); if (si->flags & SWP_SOLIDSTATE) { this_cpu_write(percpu_swap_cluster.offset[order], next); this_cpu_write(percpu_swap_cluster.si[order], si); @@ -874,7 +836,7 @@ static void swap_reclaim_full_clusters(struct swap_info= _struct *si, bool force) if (ci->flags =3D=3D CLUSTER_FLAG_NONE) relocate_cluster(si, ci); =20 - unlock_cluster(ci); + swap_cluster_unlock(ci); if (to_scan <=3D 0) break; } @@ -913,7 +875,7 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o if (offset =3D=3D SWAP_ENTRY_INVALID) goto new_cluster; =20 - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); /* Cluster could have been used by another order */ if (cluster_is_usable(ci, order)) { if (cluster_is_empty(ci)) @@ -921,7 +883,7 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o found =3D alloc_swap_scan_cluster(si, ci, offset, order, usage); } else { - unlock_cluster(ci); + swap_cluster_unlock(ci); } if (found) goto done; @@ -1202,7 +1164,7 @@ static bool swap_alloc_fast(swp_entry_t *entry, if (!si || !offset || !get_swap_device_info(si)) return false; =20 - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); if (cluster_is_usable(ci, order)) { if (cluster_is_empty(ci)) offset =3D cluster_offset(si, ci); @@ -1210,7 +1172,7 @@ static bool swap_alloc_fast(swp_entry_t *entry, if (found) *entry =3D swp_entry(si->type, found); } else { - unlock_cluster(ci); + swap_cluster_unlock(ci); } =20 put_swap_device(si); @@ -1478,14 +1440,14 @@ static void swap_entries_put_cache(struct swap_info= _struct *si, unsigned long offset =3D swp_offset(entry); struct swap_cluster_info *ci; =20 - ci =3D lock_cluster(si, offset); - if (swap_only_has_cache(si, offset, nr)) + ci =3D swap_cluster_lock(si, offset); + if (swap_only_has_cache(si, offset, nr)) { swap_entries_free(si, ci, entry, nr); - else { + } else { for (int i =3D 0; i < nr; i++, entry.val++) swap_entry_put_locked(si, ci, entry, SWAP_HAS_CACHE); } - unlock_cluster(ci); + swap_cluster_unlock(ci); } =20 static bool swap_entries_put_map(struct swap_info_struct *si, @@ -1503,7 +1465,7 @@ static bool swap_entries_put_map(struct swap_info_str= uct *si, if (count !=3D 1 && count !=3D SWAP_MAP_SHMEM) goto fallback; =20 - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); if (!swap_is_last_map(si, offset, nr, &has_cache)) { goto locked_fallback; } @@ -1512,21 +1474,20 @@ static bool swap_entries_put_map(struct swap_info_s= truct *si, else for (i =3D 0; i < nr; i++) WRITE_ONCE(si->swap_map[offset + i], SWAP_HAS_CACHE); - unlock_cluster(ci); + swap_cluster_unlock(ci); =20 return has_cache; =20 fallback: - ci =3D lock_cluster(si, offset); + 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); if (count =3D=3D SWAP_HAS_CACHE) has_cache =3D true; } - unlock_cluster(ci); + swap_cluster_unlock(ci); return has_cache; - } =20 /* @@ -1576,7 +1537,7 @@ static void swap_entries_free(struct swap_info_struct= *si, unsigned char *map_end =3D map + nr_pages; =20 /* It should never free entries across different clusters */ - VM_BUG_ON(ci !=3D offset_to_cluster(si, offset + nr_pages - 1)); + VM_BUG_ON(ci !=3D swp_offset_cluster(si, offset + nr_pages - 1)); VM_BUG_ON(cluster_is_empty(ci)); VM_BUG_ON(ci->count < nr_pages); =20 @@ -1651,9 +1612,9 @@ bool swap_entry_swapped(struct swap_info_struct *si, = swp_entry_t entry) struct swap_cluster_info *ci; int count; =20 - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); count =3D swap_count(si->swap_map[offset]); - unlock_cluster(ci); + swap_cluster_unlock(ci); return !!count; } =20 @@ -1676,7 +1637,7 @@ int swp_swapcount(swp_entry_t entry) =20 offset =3D swp_offset(entry); =20 - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); =20 count =3D swap_count(si->swap_map[offset]); if (!(count & COUNT_CONTINUED)) @@ -1699,7 +1660,7 @@ int swp_swapcount(swp_entry_t entry) n *=3D (SWAP_CONT_MAX + 1); } while (tmp_count & COUNT_CONTINUED); out: - unlock_cluster(ci); + swap_cluster_unlock(ci); return count; } =20 @@ -1714,7 +1675,7 @@ static bool swap_page_trans_huge_swapped(struct swap_= info_struct *si, int i; bool ret =3D false; =20 - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); if (nr_pages =3D=3D 1) { if (swap_count(map[roffset])) ret =3D true; @@ -1727,7 +1688,7 @@ static bool swap_page_trans_huge_swapped(struct swap_= info_struct *si, } } unlock_out: - unlock_cluster(ci); + swap_cluster_unlock(ci); return ret; } =20 @@ -2660,8 +2621,8 @@ static void wait_for_allocation(struct swap_info_stru= ct *si) BUG_ON(si->flags & SWP_WRITEOK); =20 for (offset =3D 0; offset < end; offset +=3D SWAPFILE_CLUSTER) { - ci =3D lock_cluster(si, offset); - unlock_cluster(ci); + ci =3D swap_cluster_lock(si, offset); + swap_cluster_unlock(ci); } } =20 @@ -3577,7 +3538,7 @@ static int __swap_duplicate(swp_entry_t entry, unsign= ed char usage, int nr) offset =3D swp_offset(entry); VM_WARN_ON(nr > SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER); VM_WARN_ON(usage =3D=3D 1 && nr > 1); - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); =20 err =3D 0; for (i =3D 0; i < nr; i++) { @@ -3632,7 +3593,7 @@ static int __swap_duplicate(swp_entry_t entry, unsign= ed char usage, int nr) } =20 unlock_out: - unlock_cluster(ci); + swap_cluster_unlock(ci); return err; } =20 @@ -3731,7 +3692,7 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) =20 offset =3D swp_offset(entry); =20 - ci =3D lock_cluster(si, offset); + ci =3D swap_cluster_lock(si, offset); =20 count =3D swap_count(si->swap_map[offset]); =20 @@ -3791,7 +3752,7 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) out_unlock_cont: spin_unlock(&si->cont_lock); out: - unlock_cluster(ci); + swap_cluster_unlock(ci); put_swap_device(si); outer: if (page) --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f171.google.com (mail-pf1-f171.google.com [209.85.210.171]) (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 9963727990E for ; Fri, 5 Sep 2025 19:14:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099690; cv=none; b=AF+EOTqjSugRtfGSXajtKX51pIQhlPIUCbtYnbQAQ4B3i4tioaL8gEHgrAK2NIxIzTGbHwUSMZpheV/nrWWWaR0EIOxxP3u3BTBeLxggmGoFDzcPDT4t0q8RVya1jSoLv5PnE/v2gsjDAZQtLumyLTbuFZc2PkV5xPlsxzssXn4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099690; c=relaxed/simple; bh=nd4rjLFRz1sRUijBdMt39nXgon0d+hnJIbLFi25Npy4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=QPBHEfXHOj8uAvWgqTK7HboWwbnBfVe5tJHnrw8t7BUvc3sZwkHoHXppJKsD4YcG+zutOK+LhwzHf0KCEhVMqbXGSvLbxJxHMhmNIOE1UKxOmo0QCLn3YB2Ryja7vn+eZhkz8fVmN+2V3/iI7G5/is4kdvtyMUTBTa4hxKrZrB4= 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=K/1DceW1; arc=none smtp.client-ip=209.85.210.171 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="K/1DceW1" Received: by mail-pf1-f171.google.com with SMTP id d2e1a72fcca58-77238cb3cbbso2678935b3a.0 for ; Fri, 05 Sep 2025 12:14:48 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099688; x=1757704488; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=7wNWJIsRurMOO+0rzGE8dlFv4uZu2nZpfcpjb5d40uU=; b=K/1DceW1RlZpsalL5f8FE9FUVZSiHQjI3MB4Y63t+CU7hvOYFpVoLDt38Qe7KKfgfj LIWBEuT0k7zqUl/jJPOYDCYC558tkYu7ULbScZeyulZ1/Qf3tTsSgqg4CPXON+BrCRvi AkepreKxFkd7NHPvpyXwBVuri8ena+Izi1gXSOy/iwRE4w6tOSYpCOHJzA9w3HXCeBsU xIgSroJhMfZ6PCPUm+b4GXAtAe2aqX9PrC47dpKl5LWA7ECTK7rtXbjmIEV6jY83tXJF 344z7FR9pzhRB6wCBRP0mJVv0KW9tr4BpKmRw6TVoXlSblNmO9UD98poyV1u6dTSLqIZ Lg3w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099688; x=1757704488; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=7wNWJIsRurMOO+0rzGE8dlFv4uZu2nZpfcpjb5d40uU=; b=fvkOK/C6j1I3eMJLxcgv3VhvOD6amQFysZ+pUE5fwU8ATSeSXjBXAxLrDpS5EaDbxC dC7JDm8MO2cO8eR0aL0BEjyPnhKjySZ86D2E6GdYHKViDCNjZLsyLd7tAXcnP0NZExjm hVJoGEfL1CUFGxyE/Eyxgpd3UL8k1cu7iVrdXoU8UizKD+RIl7fgakHETAnhR8V5NRfR POkkm76jRtfzCgmjRw5DRL7bOZ/P7Jwaxf6Km9xcwufTJkv/CmIBwbBhKmak5TRVQdX6 +rYPBmaEylML6h0Vt6BJrKM4JyVPJtar7gX5c2i73vQhnXeZg5/TJSgbFN1o1arlPduu Z21w== X-Forwarded-Encrypted: i=1; AJvYcCXHajWyIHR9JLqXbxl0mPa08ULc7x5iIx8zEda9rZHlksO+SbUeujd4KRQbxnwMLkjINTaof//I3K36w9s=@vger.kernel.org X-Gm-Message-State: AOJu0YzhTPrQ8xlHQBM/pqeXXo4jeR9+l2epICh/u7Ov415KmOAu3hSx QhjjdIXORkJPAnyyFXFL7hfyT2h1WwuOUWcurramGFS1/Vb3eU3GzgjP X-Gm-Gg: ASbGnctqiU2XF2/xDLL+lSYB3KHpcOVTpcWaltqkMBTZffFUwJDPRR8Rm9kbJvaTYAX eBe/1RBDI/MA3GRKHPS8+t4VmvTu5uz9Zwoc366pa07rYJeJPkVxJElPPPXuvD4lS8PqJVUoGfu 7D6OYat9CDWZbJ9uQlHz9Q993/X4Gph0Lph+Be3s/av/K53H1FoGAAtwYKoLaaXtpIeoXM414xS H8dLHpQckNh8/oldITIUSRK3vQDuAGDcG5nZ/KWYNsNRNIT1OBxN6qwTzFPU0Lg4T4vtTIlsCqy UF4jxLeksF3P8hmng++VOQVgCT6BSr9wkrXg48xcOSToF5gFD5zX+aUILKaP3c+Reh5NMPZA0RJ Uo0AqpgRw5si3Ip5x+E6z5I+eWgqsU0nNA0OlTn9RBTWvS2k= X-Google-Smtp-Source: AGHT+IGdgRlly4oOAAksandcKOQYiB7a6oz9DT+B8AQxv8TwGzWAE0KmCN/5UsjAGpOC4XEKyoieOg== X-Received: by 2002:a05:6a00:300d:b0:772:48c5:c758 with SMTP id d2e1a72fcca58-77248c5e13cmr25141547b3a.8.1757099687728; Fri, 05 Sep 2025 12:14:47 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.42 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:47 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 07/15] mm, swap: tidy up swap device and cluster info helpers Date: Sat, 6 Sep 2025 03:13:49 +0800 Message-ID: <20250905191357.78298-8-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song swp_swap_info is the most commonly used helper for retrieving swap info. It has an internal check that may lead to a NULL return value, but almost none of its caller checks the return value, making the internal check pointless. In fact, most of these callers already ensured the entry is valid and never expect a NULL value. Tidy this up and shorten the name. If the caller can make sure the swap entry/type is valid and the device is pinned, use the new introduced __swap_entry_to_info/__swap_type_to_info instead. They have more debug sanity checks and lower overhead as they are inlined. Callers that may expect a NULL value should use swap_entry_to_info/swap_type_to_info instead. No feature change. The rearranged codes should have had no effect, or they should have been hitting NULL de-ref bugs already. Only some new sanity checks are added so potential issues may show up in debug build. The new helpers will be frequently used with swap table later when working with swap cache folios. A locked swap cache folio ensures the entries are valid and stable so these helpers are very helpful. Signed-off-by: Kairui Song Acked-by: Chris Li Reviewed-by: Barry Song Acked-by: David Hildenbrand Suggested-by: Chris Li --- include/linux/swap.h | 6 ------ mm/page_io.c | 12 ++++++------ mm/swap.h | 38 +++++++++++++++++++++++++++++++++----- mm/swap_state.c | 4 ++-- mm/swapfile.c | 37 +++++++++++++++++++------------------ 5 files changed, 60 insertions(+), 37 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 7e1fe4ff3d30..6db105383782 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -479,7 +479,6 @@ 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); -struct swap_info_struct *swp_swap_info(swp_entry_t entry); struct backing_dev_info; extern int init_swap_address_space(unsigned int type, unsigned long nr_pag= es); extern void exit_swap_address_space(unsigned int type); @@ -492,11 +491,6 @@ static inline void put_swap_device(struct swap_info_st= ruct *si) } =20 #else /* CONFIG_SWAP */ -static inline struct swap_info_struct *swp_swap_info(swp_entry_t entry) -{ - return NULL; -} - static inline struct swap_info_struct *get_swap_device(swp_entry_t entry) { return NULL; diff --git a/mm/page_io.c b/mm/page_io.c index a2056a5ecb13..3c342db77ce3 100644 --- a/mm/page_io.c +++ b/mm/page_io.c @@ -204,7 +204,7 @@ 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 swp_swap_info(folio->swap); + struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); int nr_pages =3D folio_nr_pages(folio); swp_entry_t entry; unsigned int i; @@ -223,7 +223,7 @@ static void swap_zeromap_folio_set(struct folio *folio) =20 static void swap_zeromap_folio_clear(struct folio *folio) { - struct swap_info_struct *sis =3D swp_swap_info(folio->swap); + struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); swp_entry_t entry; unsigned int i; =20 @@ -374,7 +374,7 @@ static void sio_write_complete(struct kiocb *iocb, long= 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 swp_swap_info(folio->swap); + struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); struct file *swap_file =3D sis->swap_file; loff_t pos =3D swap_dev_pos(folio->swap); =20 @@ -446,7 +446,7 @@ 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 swp_swap_info(folio->swap); + struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); =20 VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio); /* @@ -537,7 +537,7 @@ static bool swap_read_folio_zeromap(struct folio *folio) =20 static void swap_read_folio_fs(struct folio *folio, struct swap_iocb **plu= g) { - struct swap_info_struct *sis =3D swp_swap_info(folio->swap); + struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); struct swap_iocb *sio =3D NULL; loff_t pos =3D swap_dev_pos(folio->swap); =20 @@ -608,7 +608,7 @@ 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 swp_swap_info(folio->swap); + struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); bool synchronous =3D sis->flags & SWP_SYNCHRONOUS_IO; bool workingset =3D folio_test_workingset(folio); unsigned long pflags; diff --git a/mm/swap.h b/mm/swap.h index 39b27337bc0a..a65e72edb087 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -15,6 +15,8 @@ extern int page_cluster; #define swap_entry_order(order) 0 #endif =20 +extern struct swap_info_struct *swap_info[]; + /* * We use this to track usage of a cluster. A cluster is a block of swap d= isk * space with SWAPFILE_CLUSTER pages long and naturally aligns in disk. All @@ -53,9 +55,29 @@ enum swap_cluster_flags { #include /* for swp_offset */ #include /* for bio_end_io_t */ =20 -static inline struct swap_cluster_info *swp_offset_cluster( +/* + * Callers of all helpers below must ensure the entry, type, or offset is + * valid, and protect the swap device with reference count or locks. + */ +static inline struct swap_info_struct *__swap_type_to_info(int type) +{ + struct swap_info_struct *si; + + si =3D READ_ONCE(swap_info[type]); /* rcu_dereference() */ + VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ + return si; +} + +static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t en= try) +{ + return __swap_type_to_info(swp_type(entry)); +} + +static inline struct swap_cluster_info *__swap_offset_to_cluster( struct swap_info_struct *si, pgoff_t offset) { + VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ + VM_WARN_ON_ONCE(offset >=3D si->max); return &si->cluster_info[offset / SWAPFILE_CLUSTER]; } =20 @@ -70,8 +92,9 @@ static inline struct swap_cluster_info *swp_offset_cluste= r( static inline struct swap_cluster_info *swap_cluster_lock( struct swap_info_struct *si, unsigned long offset) { - struct swap_cluster_info *ci =3D swp_offset_cluster(si, offset); + struct swap_cluster_info *ci =3D __swap_offset_to_cluster(si, offset); =20 + VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ spin_lock(&ci->lock); return ci; } @@ -167,7 +190,7 @@ void swap_update_readahead(struct folio *folio, struct = vm_area_struct *vma, =20 static inline unsigned int folio_swap_flags(struct folio *folio) { - return swp_swap_info(folio->swap)->flags; + return __swap_entry_to_info(folio->swap)->flags; } =20 /* @@ -178,7 +201,7 @@ 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 swp_swap_info(entry); + struct swap_info_struct *sis =3D __swap_entry_to_info(entry); unsigned long start =3D swp_offset(entry); unsigned long end =3D start + max_nr; bool first_bit; @@ -197,7 +220,7 @@ 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 swp_swap_info(entry); + struct swap_info_struct *si =3D __swap_entry_to_info(entry); pgoff_t offset =3D swp_offset(entry); int i; =20 @@ -216,6 +239,11 @@ static inline int non_swapcache_batch(swp_entry_t entr= y, int max_nr) =20 #else /* CONFIG_SWAP */ struct swap_iocb; +static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t en= try) +{ + return NULL; +} + static inline void swap_read_folio(struct folio *folio, struct swap_iocb *= *plug) { } diff --git a/mm/swap_state.c b/mm/swap_state.c index 9225d6b695ad..0ad4f3b41f1b 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -336,7 +336,7 @@ 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 swp_swap_info(entry); + struct swap_info_struct *si =3D __swap_entry_to_info(entry); struct folio *folio; struct folio *new_folio =3D NULL; struct folio *result =3D NULL; @@ -560,7 +560,7 @@ struct folio *swap_cluster_readahead(swp_entry_t entry,= gfp_t gfp_mask, unsigned long offset =3D entry_offset; unsigned long start_offset, end_offset; unsigned long mask; - struct swap_info_struct *si =3D swp_swap_info(entry); + struct swap_info_struct *si =3D __swap_entry_to_info(entry); struct blk_plug plug; struct swap_iocb *splug =3D NULL; bool page_allocated; diff --git a/mm/swapfile.c b/mm/swapfile.c index 547ad4bfe1d8..367481d319cd 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -102,7 +102,7 @@ static PLIST_HEAD(swap_active_head); static struct plist_head *swap_avail_heads; static DEFINE_SPINLOCK(swap_avail_lock); =20 -static struct swap_info_struct *swap_info[MAX_SWAPFILES]; +struct swap_info_struct *swap_info[MAX_SWAPFILES]; =20 static DEFINE_MUTEX(swapon_mutex); =20 @@ -124,14 +124,20 @@ static DEFINE_PER_CPU(struct percpu_swap_cluster, per= cpu_swap_cluster) =3D { .lock =3D INIT_LOCAL_LOCK(), }; =20 -static struct swap_info_struct *swap_type_to_swap_info(int type) +/* May return NULL on invalid type, caller must check for NULL return */ +static struct swap_info_struct *swap_type_to_info(int type) { if (type >=3D MAX_SWAPFILES) return NULL; - return READ_ONCE(swap_info[type]); /* rcu_dereference() */ } =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) +{ + return swap_type_to_info(swp_type(entry)); +} + static inline unsigned char swap_count(unsigned char ent) { return ent & ~SWAP_HAS_CACHE; /* may include COUNT_CONTINUED flag */ @@ -341,7 +347,7 @@ offset_to_swap_extent(struct swap_info_struct *sis, uns= igned long offset) =20 sector_t swap_folio_sector(struct folio *folio) { - struct swap_info_struct *sis =3D swp_swap_info(folio->swap); + struct swap_info_struct *sis =3D __swap_entry_to_info(folio->swap); struct swap_extent *se; sector_t sector; pgoff_t offset; @@ -1299,7 +1305,7 @@ static struct swap_info_struct *_swap_info_get(swp_en= try_t entry) =20 if (!entry.val) goto out; - si =3D swp_swap_info(entry); + si =3D swap_entry_to_info(entry); if (!si) goto bad_nofile; if (data_race(!(si->flags & SWP_USED))) @@ -1414,7 +1420,7 @@ struct swap_info_struct *get_swap_device(swp_entry_t = entry) =20 if (!entry.val) goto out; - si =3D swp_swap_info(entry); + si =3D swap_entry_to_info(entry); if (!si) goto bad_nofile; if (!get_swap_device_info(si)) @@ -1537,7 +1543,7 @@ static void swap_entries_free(struct swap_info_struct= *si, unsigned char *map_end =3D map + nr_pages; =20 /* It should never free entries across different clusters */ - VM_BUG_ON(ci !=3D swp_offset_cluster(si, offset + nr_pages - 1)); + VM_BUG_ON(ci !=3D __swap_offset_to_cluster(si, offset + nr_pages - 1)); VM_BUG_ON(cluster_is_empty(ci)); VM_BUG_ON(ci->count < nr_pages); =20 @@ -1595,7 +1601,7 @@ void put_swap_folio(struct folio *folio, swp_entry_t = entry) =20 int __swap_count(swp_entry_t entry) { - struct swap_info_struct *si =3D swp_swap_info(entry); + struct swap_info_struct *si =3D __swap_entry_to_info(entry); pgoff_t offset =3D swp_offset(entry); =20 return swap_count(si->swap_map[offset]); @@ -1826,7 +1832,7 @@ void free_swap_and_cache_nr(swp_entry_t entry, int nr) =20 swp_entry_t get_swap_page_of_type(int type) { - struct swap_info_struct *si =3D swap_type_to_swap_info(type); + struct swap_info_struct *si =3D swap_type_to_info(type); unsigned long offset; swp_entry_t entry =3D {0}; =20 @@ -1907,7 +1913,7 @@ int find_first_swap(dev_t *device) */ sector_t swapdev_block(int type, pgoff_t offset) { - struct swap_info_struct *si =3D swap_type_to_swap_info(type); + struct swap_info_struct *si =3D swap_type_to_info(type); struct swap_extent *se; =20 if (!si || !(si->flags & SWP_WRITEOK)) @@ -2835,7 +2841,7 @@ static void *swap_start(struct seq_file *swap, loff_t= *pos) if (!l) return SEQ_START_TOKEN; =20 - for (type =3D 0; (si =3D swap_type_to_swap_info(type)); type++) { + for (type =3D 0; (si =3D swap_type_to_info(type)); type++) { if (!(si->flags & SWP_USED) || !si->swap_map) continue; if (!--l) @@ -2856,7 +2862,7 @@ static void *swap_next(struct seq_file *swap, void *v= , loff_t *pos) type =3D si->type + 1; =20 ++(*pos); - for (; (si =3D swap_type_to_swap_info(type)); type++) { + for (; (si =3D swap_type_to_info(type)); type++) { if (!(si->flags & SWP_USED) || !si->swap_map) continue; return si; @@ -3529,7 +3535,7 @@ static int __swap_duplicate(swp_entry_t entry, unsign= ed char usage, int nr) unsigned char has_cache; int err, i; =20 - si =3D swp_swap_info(entry); + si =3D swap_entry_to_info(entry); if (WARN_ON_ONCE(!si)) { pr_err("%s%08lx\n", Bad_file, entry.val); return -EINVAL; @@ -3644,11 +3650,6 @@ void swapcache_clear(struct swap_info_struct *si, sw= p_entry_t entry, int nr) swap_entries_put_cache(si, entry, nr); } =20 -struct swap_info_struct *swp_swap_info(swp_entry_t entry) -{ - return swap_type_to_swap_info(swp_type(entry)); -} - /* * 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 --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f170.google.com (mail-pf1-f170.google.com [209.85.210.170]) (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 0F5F9283FDF for ; Fri, 5 Sep 2025 19:14:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.170 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099695; cv=none; b=ZX4ZH6DjM2+qJzWnszg3GSLT+PaApk+vz6TMdn2Wjjxucnq/DQm7Wr5/MsCdM0UB27nhGK97yJUP3s1UnoKB/75oK1Lmy8DbEsDGRwmn9MqqjIcRVLVUlRr1/1TbJwLIl0+l3ZDDZ7ahuSlObglVn+T/adJKEd7vV5+y9E+vvvU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099695; c=relaxed/simple; bh=H1N9v0PSjC5bjNISerZDYJC4cOIRGv8nLszk4ayzCB4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=HlShVXLo0tI14NUlHurOr1oP6ShPqeaSY16WIQ4PtnkVZ+3LKN38nvvGCSROL4TzWZb4/s+Niq8ml+MDOkXNshtXCKoapyIqFnpStRroDJ7k8ttubfOvT4MPlGsPcOx7z7iG0aDHf4g7GcK/kIo5db9HZXh95ASPl0TUTaz4juY= 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=Gt7/0cj8; arc=none smtp.client-ip=209.85.210.170 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="Gt7/0cj8" Received: by mail-pf1-f170.google.com with SMTP id d2e1a72fcca58-772481b2329so2640553b3a.2 for ; Fri, 05 Sep 2025 12:14:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099693; x=1757704493; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=Ox30d6DM6rDiHJuPv69STkw16eZZKgiB3gZs68VZQi4=; b=Gt7/0cj8JOOU2Kb1c/zGqevLJq0nyppKPi9Q23Lz4LAvbs3LZBa3/KDEpkZEV00xsH h5Gt2B8qkRWvkk7xfrIA/2aOlXVQy/exHGbxodULmzDynCof6CEDHGRq8YfO2827Ovv+ kOTnfxerf+CQVZbhkLJzrEKNsVD4k5RhaYVtaMbLwBQI3IQgsO0petoIwJKaioK6wVJz pjV55x9xaHfcybupyoATOhukfqun+moUubiPy6SkaYOpuRy76h6PlC1nAd7gvHWAUIsD kIrQeodOEfiYcSlaINmKdsBn3cxcvSnmGQbqKTOqTV2gWzBig/WxWtm5R72NXchVAR49 2aOA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099693; x=1757704493; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=Ox30d6DM6rDiHJuPv69STkw16eZZKgiB3gZs68VZQi4=; b=lBqkW7GajgCLkpCF6Fo0ggHLnomO9pvuesovo8xoVkYEAtgnDxrbuuoigXUxADasW3 VpwsKSLwCX/eTXGPYCjWPiL34j8QtUlV5nu8JLfT1czPuuFRpQbT+I0jQ7CQ8WYBhaWH L5eQJa4xMIk07V++qhPNstid0a7rEM8wgqSXYiPOA4ZS4X6dT+bsj+4dpMDsXfCG19Vw LADingwzkcMv0bA8I+2RCtB0az6zSjVCoR8t/FajPQurdJ84SX0tvP2QfCjNtoB0c9wI r00LX5pgxFVPAdqmZzkUTawQeq2/yOhkLGx6grRhylbmT3nsaK06q1yaVaVckt8WFGtD MpZA== X-Forwarded-Encrypted: i=1; AJvYcCW+hY0fRC3ARPnDZ+ubY0zRDFzHFyNhPYWUY2MxZq2WzkbUCcZqzWv8VPiTcLY5zHQWMbaolxAcLReHHMQ=@vger.kernel.org X-Gm-Message-State: AOJu0YyPhMxPupZbOGkG0NPVd+MQyQaDSYvQhFe8hummeSr/JUO/JSfG dzmvBKBlhzePc06JWFG4cZSVL3yJGnP6/3tHiGBZ4yGATx+/RAHyuL+v X-Gm-Gg: ASbGncvfCIIC7UDVnIAZBcP0tjUkVdP2hI3YU/OJrM6vGLg2Q37xmBnH7FL52ZBmNfz MK6493Z1Z30SmuQK+Ww869v7ed/wJKdfEQDr3tRRCrXa2ITKxL4hfztTBqjNzGIRpeVzCmaP+Ln 5+AI+2mEIcA0mMrNAwuUJfNvoQxDaT47hFQT4F2P30DpFZwO9vq6xvFZmnq0RvXXE2anEOTcRSO YinBi7aU7T6jcaPLWxH4M6pEEXH7iuLOwEYaiygDU2zNPo/EVLn/AttyBXYZt4IxpKOLLwg/Cow sjkq/lS8sq5YLRhPXu9MbVw5Dw/cSiXJuVZzZe4grkO55i3pnKRMIRD0Nxr0REvx/MhY/JWRexZ onRWppdKpGH5iaLPV6EPP6YplTxMQR0CnUXsU783zAiUA+xk= X-Google-Smtp-Source: AGHT+IHkfM1wQBbs4k5VXAzI/0q78S/BXsy7LEozPN1l6mv9TC/7dXb738MOmgCmXvDJRIWgub+l9A== X-Received: by 2002:a05:6a00:10cd:b0:772:398a:7655 with SMTP id d2e1a72fcca58-7723e38ae13mr26648003b3a.23.1757099693154; Fri, 05 Sep 2025 12:14:53 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.48 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:52 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 08/15] mm/shmem, swap: remove redundant error handling for replacing folio Date: Sat, 6 Sep 2025 03:13:50 +0800 Message-ID: <20250905191357.78298-9-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song Shmem may replace a folio in the swap cache if the cached one doesn't fit the swapin's GFP zone. When doing so, shmem has already double checked that the swap cache folio is locked, still has the swap cache flag set, and contains the wanted swap entry. So it is impossible to fail due to an Xarray mismatch. There is even a comment for that. Delete the defensive error handling path, and add a WARN_ON instead: if that happened, something has broken the basic principle of how the swap cache works, we should catch and fix that. Signed-off-by: Kairui Song Reviewed-by: David Hildenbrand Suggested-by: Chris Li --- mm/shmem.c | 42 ++++++++++++------------------------------ 1 file changed, 12 insertions(+), 30 deletions(-) diff --git a/mm/shmem.c b/mm/shmem.c index 4e27e8e5da3b..cc6a0007c7a6 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -1698,13 +1698,13 @@ int shmem_writeout(struct folio *folio, struct swap= _iocb **plug, } =20 /* - * The delete_from_swap_cache() below could be left for + * The swap_cache_del_folio() below could be left for * shrink_folio_list()'s folio_free_swap() to dispose of; * but I'm a little nervous about letting this folio out of * shmem_writeout() in a hybrid half-tmpfs-half-swap state * e.g. folio_mapping(folio) might give an unexpected answer. */ - delete_from_swap_cache(folio); + swap_cache_del_folio(folio); goto redirty; } if (nr_pages > 1) @@ -2082,7 +2082,7 @@ static struct folio *shmem_swap_alloc_folio(struct in= ode *inode, new->swap =3D entry; =20 memcg1_swapin(entry, nr_pages); - shadow =3D get_shadow_from_swap_cache(entry); + shadow =3D swap_cache_get_shadow(entry); if (shadow) workingset_refault(new, shadow); folio_add_lru(new); @@ -2158,35 +2158,17 @@ static int shmem_replace_folio(struct folio **folio= p, gfp_t gfp, /* Swap cache still stores N entries instead of a high-order entry */ xa_lock_irq(&swap_mapping->i_pages); for (i =3D 0; i < nr_pages; i++) { - void *item =3D xas_load(&xas); - - if (item !=3D old) { - error =3D -ENOENT; - break; - } - - xas_store(&xas, new); + WARN_ON_ONCE(xas_store(&xas, new)); xas_next(&xas); } - if (!error) { - mem_cgroup_replace_folio(old, new); - shmem_update_stats(new, nr_pages); - shmem_update_stats(old, -nr_pages); - } xa_unlock_irq(&swap_mapping->i_pages); =20 - if (unlikely(error)) { - /* - * Is this possible? I think not, now that our callers - * check both the swapcache flag and folio->private - * after getting the folio lock; but be defensive. - * Reverse old to newpage for clear and free. - */ - old =3D new; - } else { - folio_add_lru(new); - *foliop =3D new; - } + mem_cgroup_replace_folio(old, new); + shmem_update_stats(new, nr_pages); + shmem_update_stats(old, -nr_pages); + + folio_add_lru(new); + *foliop =3D new; =20 folio_clear_swapcache(old); old->private =3D NULL; @@ -2220,7 +2202,7 @@ static void shmem_set_folio_swapin_error(struct inode= *inode, pgoff_t index, nr_pages =3D folio_nr_pages(folio); folio_wait_writeback(folio); if (!skip_swapcache) - delete_from_swap_cache(folio); + swap_cache_del_folio(folio); /* * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks * won't be 0 when inode is released and thus trigger WARN_ON(i_blocks) @@ -2459,7 +2441,7 @@ static int shmem_swapin_folio(struct inode *inode, pg= off_t index, folio->swap.val =3D 0; swapcache_clear(si, swap, nr_pages); } else { - delete_from_swap_cache(folio); + swap_cache_del_folio(folio); } folio_mark_dirty(folio); swap_free_nr(swap, nr_pages); --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f179.google.com (mail-pf1-f179.google.com [209.85.210.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 8986C28B7DB for ; Fri, 5 Sep 2025 19:14:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099701; cv=none; b=CM5ppsxlEFAnRQqDTlFvUz3D5uUCJlELZiAy8eCjkbHEnfqxosNT1Af8JWuPNaFkapoZC5o/M+fiRvtJWyYDzRy/veyoKf+iU4xVJ/qPjvEKSEmq+dkWPWdjuDPD4qzNsh+3DcnluU7S8NryBrXjVfKTVN/em3UaVHMBemE1jEc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099701; c=relaxed/simple; bh=su9xnhRSPMiQBdNnNB2mYr3cxQkTWMIJ4vLB7YAq34M=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=RljIf/9L36lMlVm1JuNLJTOljsI0V8trMTrH74g2Ibx8zRV37nJim4iixo7m0XZXrCbfETjGwYSMwZtY4P3CEN53htt2HY2uipcTYv3s8U0p4ehMTjfwLUqWDISdh0lKimEFdyRAr3O56g6sEC3RboBl4tNFN/dHxgvYUENqhR0= 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=Thnd7pZ7; arc=none smtp.client-ip=209.85.210.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="Thnd7pZ7" Received: by mail-pf1-f179.google.com with SMTP id d2e1a72fcca58-772301f8ae2so2190155b3a.0 for ; Fri, 05 Sep 2025 12:14:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099699; x=1757704499; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=E3aNJoCVROccJngmuYyj6rXHVyByugeVfWJigOc5CDQ=; b=Thnd7pZ7bI8TpvO9jqnmlctj1soCONPyQqrbjHyPf5J8umY9JEBd1n1I4Crdgr09Ag i+KTggZ4tCogvgbp/Vsu3Nt+zAnboFVL922zCnyYO6P4/WFeK6Bwr4SqtoFmVMYxD91S SVWQM5+fmsE8/YQ6eJRwDjIdz3ZAVrWpTxMUSzNnRHv3gFjhT4QiZGBcxkcE3zjLkWxI /rmuyrNekthy74UNTqOmFlH2USIcKHLOA4NU6OEgntCbr5SnWqGFnz0S0eru4iP3LkJ3 hBap3SCYuDJ929sh4YfS1rPVstjsUyFYFBPjIcRt9VsdtG9lCtpk2YWkVe0dM45rpP3E xwQg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099699; x=1757704499; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=E3aNJoCVROccJngmuYyj6rXHVyByugeVfWJigOc5CDQ=; b=IXYCXPQbdqDpiq/j0DatsbJYZePrsTc10eRRIK++CedhBERrk0dmcD4jdXE3n1OMzL EBOiNcKvgeQEUu4NDnANrpsXHZrTnzlcrZsmouiSUgAqFoFciHknBTudlcIQSXO2r/jl fTmCL/iF1j1G2wChIfP4DWCXuuBeTvQbh15Bw8vpYPUt8No49p48yShGQ/zAqvm1a4SN c7Vwc7He5jtL0Iv1UKRLcM6QKTliKp6eXlnQ8KJWsFLYYkM2FP0SmOLKeQ683Ym2NL/I +vH8tnI1NzE0NwKn26BmwCSuogq1PCNAvSxr6EqjbapITA0IhL1tDORYRkbUT5Uz6cOT hvUQ== X-Forwarded-Encrypted: i=1; AJvYcCUhzytYE8WHnbCAMTX1uOGkwa5+qncgtr64rgv5V3Lqczg4/NjlINeWOowRbQBpz5kMD89A8v7yODoGP2g=@vger.kernel.org X-Gm-Message-State: AOJu0YyfitaFz7e2J6vSW83h8ObBE66Ktv7mdX1GZ+wJ1OvRynvGveWt OybQWntDXofRJj3Fohy0DMxW2L1xgqicyGtotsY0vko+GvjKvZffs16N X-Gm-Gg: ASbGncubxWI7gx19/snYXrYqRpPfnj3v/WlJwgl5hlEhu5dgRSvv2sY0XEMlvrpBi68 6Ie8v9Ul06Ro0aZ8Ti8craUWiCid60BX6LViR1jizdftEkZqpwlKdCaO2GDez9qurl1i+3P5In4 I/nbdAl3v9/Ta8sGaZUJopxrgWHRAJC7AW168wcGlZt7mV/poaI7Oev4LBS1nGcf4XTq0NRC3yt 7sRERbgZfDqn2otX8dDpJI2iJSFe0oL1I+ppFwoMeNPCG8XVL97vP1ygUnGRh3wcNHcidaCTWYR iluLfRZQK4rO6Uk7aJwhGSXzVpO+YDzW1bZqxbqA2SL7cYurJe0m3zaup+k+yBUuMXBfTk1R+NX HoEico6gVQgxM3rgB2Glig4naSon+U/Ss9Tkvi38zRKhChJXuvgjLjMIgsA== X-Google-Smtp-Source: AGHT+IFkFSys4IRUs0tnQpRxvyD0XxRc9V7ETW+LXR3DXREnaZW5aW0gNaD7ew1XW/XButtm1AKAsw== X-Received: by 2002:a05:6a00:3e29:b0:736:8c0f:7758 with SMTP id d2e1a72fcca58-7723e224181mr25962922b3a.10.1757099698697; Fri, 05 Sep 2025 12:14:58 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.53 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:14:58 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 09/15] mm, swap: cleanup swap cache API and add kerneldoc Date: Sat, 6 Sep 2025 03:13:51 +0800 Message-ID: <20250905191357.78298-10-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song In preparation for replacing the swap cache backend with the swap table, clean up and add proper kernel doc for all swap cache APIs. Now all swap cache APIs are well-defined with consistent names. No feature change, only renaming and documenting. Signed-off-by: Kairui Song Acked-by: Chris Li Acked-by: David Hildenbrand Reviewed-by: Baolin Wang Reviewed-by: Barry Song Suggested-by: Chris Li --- mm/filemap.c | 2 +- mm/memory-failure.c | 2 +- mm/memory.c | 2 +- mm/swap.h | 48 ++++++++++++++----------- mm/swap_state.c | 86 ++++++++++++++++++++++++++++++++------------- mm/swapfile.c | 8 ++--- mm/vmscan.c | 2 +- mm/zswap.c | 2 +- 8 files changed, 98 insertions(+), 54 deletions(-) diff --git a/mm/filemap.c b/mm/filemap.c index 344ab106c21c..29ea56999a16 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -4517,7 +4517,7 @@ static void filemap_cachestat(struct address_space *m= apping, * invalidation, so there might not be * a shadow in the swapcache (yet). */ - shadow =3D get_shadow_from_swap_cache(swp); + shadow =3D swap_cache_get_shadow(swp); if (!shadow) goto resched; } diff --git a/mm/memory-failure.c b/mm/memory-failure.c index b93ab99ad3ef..922526533cd9 100644 --- a/mm/memory-failure.c +++ b/mm/memory-failure.c @@ -1199,7 +1199,7 @@ static int me_swapcache_clean(struct page_state *ps, = struct page *p) struct folio *folio =3D page_folio(p); int ret; =20 - delete_from_swap_cache(folio); + swap_cache_del_folio(folio); =20 ret =3D delete_from_lru_cache(folio) ? MF_FAILED : MF_RECOVERED; folio_unlock(folio); diff --git a/mm/memory.c b/mm/memory.c index 5808c4ef21b3..41e641823558 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4699,7 +4699,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) =20 memcg1_swapin(entry, nr_pages); =20 - shadow =3D get_shadow_from_swap_cache(entry); + shadow =3D swap_cache_get_shadow(entry); if (shadow) workingset_refault(folio, shadow); =20 diff --git a/mm/swap.h b/mm/swap.h index a65e72edb087..8b38577a4e04 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -164,17 +164,29 @@ static inline bool folio_matches_swap_entry(const str= uct folio *folio, return folio->swap.val =3D=3D round_down(entry.val, folio_nr_pages(folio)= ); } =20 +/* + * 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: + * - Hold a reference by get_swap_device(): this ensures a single entry is + * valid and increases the swap device's refcount. + * - Locking a folio in the swap cache: this ensures the folio's swap entr= ies + * are valid and pinned, also implies reference to the device. + * - Locking anything referencing the swap entry: e.g. PTL that protects + * swap entries in the page table, similar to locking swap cache folio. + * - See the comment of get_swap_device() for more complex usage. + */ +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_del_folio(struct folio *folio); +void __swap_cache_del_folio(struct folio *folio, + swp_entry_t entry, void *shadow); +void swap_cache_clear_shadow(int type, unsigned long begin, + unsigned long end); + void show_swap_cache_info(void); -void *get_shadow_from_swap_cache(swp_entry_t entry); -int add_to_swap_cache(struct folio *folio, swp_entry_t entry, - gfp_t gfp, void **shadowp); -void __delete_from_swap_cache(struct folio *folio, - swp_entry_t entry, void *shadow); -void delete_from_swap_cache(struct folio *folio); -void clear_shadow_from_swap_cache(int type, unsigned long begin, - unsigned long end); void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int n= r); -struct folio *swap_cache_get_folio(swp_entry_t entry); 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); @@ -302,28 +314,22 @@ static inline struct folio *swap_cache_get_folio(swp_= entry_t entry) return NULL; } =20 -static inline void *get_shadow_from_swap_cache(swp_entry_t entry) +static inline void *swap_cache_get_shadow(swp_entry_t entry) { return NULL; } =20 -static inline int add_to_swap_cache(struct folio *folio, swp_entry_t entry, - gfp_t gfp_mask, void **shadowp) -{ - return -1; -} - -static inline void __delete_from_swap_cache(struct folio *folio, - swp_entry_t entry, void *shadow) +static inline int swap_cache_add_folio(swp_entry_t entry, struct folio *fo= lio, + gfp_t gfp, void **shadow) { + return -EINVAL; } =20 -static inline void delete_from_swap_cache(struct folio *folio) +static inline void swap_cache_del_folio(struct folio *folio) { } =20 -static inline void clear_shadow_from_swap_cache(int type, unsigned long be= gin, - unsigned long end) +static inline void __swap_cache_del_folio(swp_entry_t entry, struct folio = *folio, void *shadow) { } =20 diff --git a/mm/swap_state.c b/mm/swap_state.c index 0ad4f3b41f1b..f3a32a06a950 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -78,8 +78,8 @@ void show_swap_cache_info(void) * 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 and check if the folio still matches the swap entry before - * use (e.g. with folio_matches_swap_entry). + * 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) { @@ -90,7 +90,15 @@ struct folio *swap_cache_get_folio(swp_entry_t entry) return folio; } =20 -void *get_shadow_from_swap_cache(swp_entry_t entry) +/** + * 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) { struct address_space *address_space =3D swap_address_space(entry); pgoff_t idx =3D swap_cache_index(entry); @@ -102,12 +110,21 @@ void *get_shadow_from_swap_cache(swp_entry_t entry) return NULL; } =20 -/* - * add_to_swap_cache resembles filemap_add_folio on swapper_space, - * but sets SwapCache flag and 'swap' instead of mapping and index. +/** + * 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 mark the corresponding swap_map slots with + * SWAP_HAS_CACHE to avoid race or conflict. + * Return: Returns 0 on success, error code otherwise. */ -int add_to_swap_cache(struct folio *folio, swp_entry_t entry, - gfp_t gfp, void **shadowp) +int swap_cache_add_folio(struct folio *folio, swp_entry_t entry, + gfp_t gfp, void **shadowp) { struct address_space *address_space =3D swap_address_space(entry); pgoff_t idx =3D swap_cache_index(entry); @@ -155,12 +172,20 @@ int add_to_swap_cache(struct folio *folio, swp_entry_= t entry, return xas_error(&xas); } =20 -/* - * This must be called only on folios that have - * been verified to be in the swap cache. +/** + * __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 hold the xa_lock, ensure the folio is + * locked and in the swap cache, using the index of @entry. */ -void __delete_from_swap_cache(struct folio *folio, - swp_entry_t entry, void *shadow) +void __swap_cache_del_folio(struct folio *folio, + swp_entry_t entry, void *shadow) { struct address_space *address_space =3D swap_address_space(entry); int i; @@ -186,27 +211,40 @@ void __delete_from_swap_cache(struct folio *folio, __lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr); } =20 -/* - * This must be called only on folios that have - * been verified to be in the swap cache and locked. - * It will never put the folio into the free list, - * the caller has a reference on the folio. +/** + * 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 delete_from_swap_cache(struct folio *folio) +void swap_cache_del_folio(struct folio *folio) { swp_entry_t entry =3D folio->swap; struct address_space *address_space =3D swap_address_space(entry); =20 xa_lock_irq(&address_space->i_pages); - __delete_from_swap_cache(folio, entry, NULL); + __swap_cache_del_folio(folio, entry, NULL); xa_unlock_irq(&address_space->i_pages); =20 put_swap_folio(folio, entry); folio_ref_sub(folio, folio_nr_pages(folio)); } =20 -void clear_shadow_from_swap_cache(int type, unsigned long begin, - unsigned long end) +/** + * swap_cache_clear_shadow - Clears a set of shadows in the swap cache. + * @type: Indicates the swap device. + * @begin: Beginning offset of the range. + * @end: Ending offset of the range. + * + * Context: Caller must ensure the range is valid and hold a reference to + * the swap device. + */ +void swap_cache_clear_shadow(int type, unsigned long begin, + unsigned long end) { unsigned long curr =3D begin; void *old; @@ -393,7 +431,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry= , gfp_t gfp_mask, goto put_and_return; =20 /* - * We might race against __delete_from_swap_cache(), and + * We might race against __swap_cache_del_folio(), and * stumble across a swap_map entry whose SWAP_HAS_CACHE * has not yet been cleared. Or race against another * __read_swap_cache_async(), which has set SWAP_HAS_CACHE @@ -412,7 +450,7 @@ struct folio *__read_swap_cache_async(swp_entry_t entry= , gfp_t gfp_mask, goto fail_unlock; =20 /* May fail (-ENOMEM) if XArray node allocation failed. */ - if (add_to_swap_cache(new_folio, entry, gfp_mask & GFP_RECLAIM_MASK, &sha= dow)) + if (swap_cache_add_folio(new_folio, entry, gfp_mask & GFP_RECLAIM_MASK, &= shadow)) goto fail_unlock; =20 memcg1_swapin(entry, 1); diff --git a/mm/swapfile.c b/mm/swapfile.c index 367481d319cd..731b541b1d33 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -266,7 +266,7 @@ static int __try_to_reclaim_swap(struct swap_info_struc= t *si, if (!need_reclaim) goto out_unlock; =20 - delete_from_swap_cache(folio); + swap_cache_del_folio(folio); folio_set_dirty(folio); ret =3D nr_pages; out_unlock: @@ -1123,7 +1123,7 @@ static void swap_range_free(struct swap_info_struct *= si, unsigned long offset, swap_slot_free_notify(si->bdev, offset); offset++; } - clear_shadow_from_swap_cache(si->type, begin, end); + swap_cache_clear_shadow(si->type, begin, end); =20 /* * Make sure that try_to_unuse() observes si->inuse_pages reaching 0 @@ -1288,7 +1288,7 @@ int folio_alloc_swap(struct folio *folio, gfp_t gfp) * TODO: this could cause a theoretical memory reclaim * deadlock in the swap out path. */ - if (add_to_swap_cache(folio, entry, gfp | __GFP_NOMEMALLOC, NULL)) + if (swap_cache_add_folio(folio, entry, gfp | __GFP_NOMEMALLOC, NULL)) goto out_free; =20 return 0; @@ -1758,7 +1758,7 @@ bool folio_free_swap(struct folio *folio) if (folio_swapped(folio)) return false; =20 - delete_from_swap_cache(folio); + swap_cache_del_folio(folio); folio_set_dirty(folio); return true; } diff --git a/mm/vmscan.c b/mm/vmscan.c index ca9e1cd3cd68..c79c6806560b 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -776,7 +776,7 @@ 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); - __delete_from_swap_cache(folio, swap, shadow); + __swap_cache_del_folio(folio, swap, shadow); memcg1_swapout(folio, swap); xa_unlock_irq(&mapping->i_pages); put_swap_folio(folio, swap); diff --git a/mm/zswap.c b/mm/zswap.c index c88ad61b232c..3dda4310099e 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -1069,7 +1069,7 @@ static int zswap_writeback_entry(struct zswap_entry *= entry, =20 out: if (ret && ret !=3D -EEXIST) { - delete_from_swap_cache(folio); + swap_cache_del_folio(folio); folio_unlock(folio); } folio_put(folio); --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f180.google.com (mail-pf1-f180.google.com [209.85.210.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 E6B3427E04F for ; Fri, 5 Sep 2025 19:15:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.180 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099706; cv=none; b=pNc3pIiZHbeXBkhVfXRsVGwg1MYBH7ZVchWP9+/d4RoShtMkFySqDJ+ATxStSNZ9C+vMFGH3U5t8Zoy5FbQKQ2Ar+aVgeI1JD16Y+vXeCiWONc4a+epJkOWhZMviCS1gB1TFKT7sMZQekBGc+aKbsoFtnQ4RysMEbsn2kLMovGY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099706; c=relaxed/simple; bh=PZ9CZUY+9q7aVuxipydq1ZkprFWX7sdmxkMlB6wqez0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=tUQdUlObFNWeXBlG9K4gYdYsum6Kt1d4u6iE/FV+xvZD8ZAmWiwUMnKUBkkuL19sQgAhFncnI/Z6ltYAItsDmLTIpYFCWa7cM+EccVm9dBxavrQeZpSeZz28y7v3yaNUkqXbCRswhlGInzcJk4forYocrBI9ecAfFVHT8qQyGpo= 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=T+b5lstp; arc=none smtp.client-ip=209.85.210.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="T+b5lstp" Received: by mail-pf1-f180.google.com with SMTP id d2e1a72fcca58-77269d19280so2232901b3a.3 for ; Fri, 05 Sep 2025 12:15:04 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099704; x=1757704504; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=qeydI8/HJylw/79KhdbsUGz3ARLAznWN2FgVE73ocLM=; b=T+b5lstprwX+yvtQYRgCh58VXp6A8AEP/2+oyvn8mPqBPkFyQN4tix5fWtwXhiBiUr 1fnmEBPDLdZbXCfKIHYYGLJ5eA5Xi9r4FI/1t542eXQ1RptotYDe+CLy7wz0XvfUM+gx W3jJA7qN/sDFeZzH672aKg4XWIAPg4KjKP9g/bWZdkgLXWdz2GApxfpUaR94BG6HH0r9 8Kt0qyVhqpHAo4qXE9Dn4lK0yFOE6ClaAdtAzPLCVnVN1MaCANZHl0QbkZj9jikBZNpK bADv3rCZ4aoQkY7TrNKaKUZHzXTGZZg62tcfUIzm2d3T9xgdt9gO82+ti2LIIOSJtS0S kfhw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099704; x=1757704504; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=qeydI8/HJylw/79KhdbsUGz3ARLAznWN2FgVE73ocLM=; b=LT7K0aTL7ACzIvWu8WqY2knJEjwbhe7m/J0OP5l26CBe7aRGlaOF0hWWLL7mxTQKvw weDJkyVipF1EZMDoqq5mlnaiV21dn9o6rXXTWtIrrZ1h0ZB6FrfQcJf5y4vsjoWZga9T 7jAAMXTLVhf43PIERRs9kEXbfR4PdjRtFTU2gadiLEXVoHuUjI6jUmSXGzc3UFAoI1Im /xkPvysKIgMCzjt3wkX0dEjxz673wfDx40cTG0lFvMm5epw9xvubkJ5tL+Z6xFIDG1of lFlfnx9V2KGRs605qVj4UQ+Bux2WpLk6v5MSWRE+8dpervHDxcvW+a8aaLCSPTWFH+cr +sSA== X-Forwarded-Encrypted: i=1; AJvYcCUds+MuNEkTwQ6HOONIWgXpc4WtghB0v4BdJEPQVmEFMhjOkSj8QOqfTukEYsUwPrybL3dWwFUWV+kNSN0=@vger.kernel.org X-Gm-Message-State: AOJu0Yya4uYBydGpt3v+3z/L1WNG+WiZfGwMJJwi8APUGPRngOYQ8Y7N M4FQtY+5CXq5BtCxajTmGwC1Z1Ut6OTooLsfvL1YLrrN2pXZLzR7yTdj X-Gm-Gg: ASbGncuAw1XWmu1ZDT2CPh7G6ubV9LZABIrAzZxptwptlYkDcFK2qJ7FvNjsX/xqS+9 z5R5DcHUCH2ZoCmS7gLTG9VIRRDPL0geAbOUOKFUw0BGVx7HYVF74Pr3Kf86lGwqqR9hMGZu5p3 QSqcmOyAymkNe0R7kq6d949DJlDKx/1huafUKnwk4aOneITgUy+IAOEgoYHzFbdIeD9J4Xj9DQB 9PXcSW/FgSo2kbrNZ5D6kJjxmKq++3LEK8S2uUMfPlSUvVZT/CcREGFyVMPTurxBQgV6DUB0epA 7H5F3hO5whmz3hs9ZkYcAmRNBzMDe1ZMlHjQbp5HxPxHayqoGGwLsnUCnX1CQ5U9s9bV+gOTcRS 3kyEB1av8ssGxfaOHj9y/edeBcIQP6aGEy9ywDSaAJnYCLuB2135k2J2lFA== X-Google-Smtp-Source: AGHT+IHWPtwM9o9BiVGBGT6c2v5RdaBjzKiZLU1Y6x4jyh1hpXCSNboWEG37cyccl+n7P+1hlaOKmA== X-Received: by 2002:a05:6a00:2e24:b0:771:ec42:1c1e with SMTP id d2e1a72fcca58-7723e342f91mr28182850b3a.16.1757099704147; Fri, 05 Sep 2025 12:15:04 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.14.59 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:15:03 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 10/15] mm, swap: wrap swap cache replacement with a helper Date: Sat, 6 Sep 2025 03:13:52 +0800 Message-ID: <20250905191357.78298-11-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song There are currently three swap cache users that are trying to replace an existing folio with a new one: huge memory splitting, migration, and shmem replacement. What they are doing is quite similar. Introduce a common helper for this. In later commits, they can be easily switched to use the swap table by updating this helper. The newly added helper also makes the swap cache API better defined, and debugging is easier. Signed-off-by: Kairui Song Acked-by: Chris Li Reviewed-by: Baolin Wang Suggested-by: Chris Li --- mm/huge_memory.c | 5 ++--- mm/migrate.c | 11 +++-------- mm/shmem.c | 10 ++-------- mm/swap.h | 3 +++ mm/swap_state.c | 32 ++++++++++++++++++++++++++++++++ 5 files changed, 42 insertions(+), 19 deletions(-) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index 26cedfcd7418..a4d192c8d794 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -3798,9 +3798,8 @@ static int __folio_split(struct folio *folio, unsigne= d int new_order, * NOTE: shmem in swap cache is not supported yet. */ if (swap_cache) { - __xa_store(&swap_cache->i_pages, - swap_cache_index(new_folio->swap), - new_folio, 0); + __swap_cache_replace_folio(swap_cache, new_folio->swap, + folio, new_folio); continue; } =20 diff --git a/mm/migrate.c b/mm/migrate.c index 8e435a078fc3..7e1d01aa8c85 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -566,7 +566,6 @@ static int __folio_migrate_mapping(struct address_space= *mapping, struct zone *oldzone, *newzone; int dirty; long nr =3D folio_nr_pages(folio); - long entries, i; =20 if (!mapping) { /* Take off deferred split queue while frozen and memcg set */ @@ -615,9 +614,6 @@ static int __folio_migrate_mapping(struct address_space= *mapping, if (folio_test_swapcache(folio)) { folio_set_swapcache(newfolio); newfolio->private =3D folio_get_private(folio); - entries =3D nr; - } else { - entries =3D 1; } =20 /* Move dirty while folio refs frozen and newfolio not yet exposed */ @@ -627,11 +623,10 @@ static int __folio_migrate_mapping(struct address_spa= ce *mapping, folio_set_dirty(newfolio); } =20 - /* Swap cache still stores N entries instead of a high-order entry */ - for (i =3D 0; i < entries; i++) { + if (folio_test_swapcache(folio)) + __swap_cache_replace_folio(mapping, folio->swap, folio, newfolio); + else xas_store(&xas, newfolio); - xas_next(&xas); - } =20 /* * Drop cache reference from old folio by unfreezing diff --git a/mm/shmem.c b/mm/shmem.c index cc6a0007c7a6..823ceae9dff8 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2123,10 +2123,8 @@ static int shmem_replace_folio(struct folio **foliop= , gfp_t gfp, struct folio *new, *old =3D *foliop; swp_entry_t entry =3D old->swap; struct address_space *swap_mapping =3D swap_address_space(entry); - pgoff_t swap_index =3D swap_cache_index(entry); - XA_STATE(xas, &swap_mapping->i_pages, swap_index); int nr_pages =3D folio_nr_pages(old); - int error =3D 0, i; + int error =3D 0; =20 /* * We have arrived here because our zones are constrained, so don't @@ -2155,12 +2153,8 @@ static int shmem_replace_folio(struct folio **foliop= , gfp_t gfp, new->swap =3D entry; folio_set_swapcache(new); =20 - /* Swap cache still stores N entries instead of a high-order entry */ xa_lock_irq(&swap_mapping->i_pages); - for (i =3D 0; i < nr_pages; i++) { - WARN_ON_ONCE(xas_store(&xas, new)); - xas_next(&xas); - } + __swap_cache_replace_folio(swap_mapping, entry, old, new); xa_unlock_irq(&swap_mapping->i_pages); =20 mem_cgroup_replace_folio(old, new); diff --git a/mm/swap.h b/mm/swap.h index 8b38577a4e04..a139c9131244 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -182,6 +182,9 @@ int swap_cache_add_folio(struct folio *folio, swp_entry= _t entry, void swap_cache_del_folio(struct folio *folio); void __swap_cache_del_folio(struct folio *folio, swp_entry_t entry, void *shadow); +void __swap_cache_replace_folio(struct address_space *address_space, + swp_entry_t entry, + struct folio *old, struct folio *new); void swap_cache_clear_shadow(int type, unsigned long begin, unsigned long end); =20 diff --git a/mm/swap_state.c b/mm/swap_state.c index f3a32a06a950..38f5f4cf565d 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -234,6 +234,38 @@ void swap_cache_del_folio(struct folio *folio) folio_ref_sub(folio, folio_nr_pages(folio)); } =20 +/** + * __swap_cache_replace_folio - Replace a folio in the swap cache. + * @mapping: Swap mapping address space. + * @entry: The first swap entry that the new folio corresponds to. + * @old: The old folio to be replaced. + * @new: The new folio. + * + * Replace a existing folio in the swap cache with a new folio. + * + * Context: Caller must ensure both folios are locked, and lock the + * swap address_space that holds the entries to be replaced. + */ +void __swap_cache_replace_folio(struct address_space *mapping, + swp_entry_t entry, + struct folio *old, struct folio *new) +{ + unsigned long nr_pages =3D folio_nr_pages(new); + unsigned long offset =3D swap_cache_index(entry); + unsigned long end =3D offset + nr_pages; + XA_STATE(xas, &mapping->i_pages, offset); + + VM_WARN_ON_ONCE(entry.val !=3D new->swap.val); + VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new)); + VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new)); + + /* Swap cache still stores N entries instead of a high-order entry */ + do { + WARN_ON_ONCE(xas_store(&xas, new) !=3D old); + xas_next(&xas); + } while (++offset < end); +} + /** * swap_cache_clear_shadow - Clears a set of shadows in the swap cache. * @type: Indicates the swap device. --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f171.google.com (mail-pf1-f171.google.com [209.85.210.171]) (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 EFAA436B for ; Fri, 5 Sep 2025 19:15:10 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099713; cv=none; b=tjRRZRI1tGI/rQdrF5n+awuUX9C/jOIbKQzC3rhFOpZWU1jHMzA5v0xvlGVIgalKAar2bZShmgPVlV+zKG1leFKJlqwTS8RCjoLFuhu7T9FDPvTIczn5PC72UsQ/oSyP9iTftvmClmHktoSBxulwps58TqhZb9zu96QKGOoaEzo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099713; c=relaxed/simple; bh=SHihKBs+1uL7zMMKLnU4yybgJikbE1Y/7EyJpm2uzRE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=pnwM28YlsUbETNxrqOeFcr1ozYYOMohdZKHw81fbZW0qdMYqCvHTtR6QwtNFMUqMeFzE7pyyCiC07sGXGpX1g4zisTv58T/1tqaEvdkoknwJMHBvlAIDFJAMuxyQcmH8QGrtPAtwRUF4t9TMRStW2+XgpBu6lJgCFuVLdc6onTI= 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=AQpyxl2P; arc=none smtp.client-ip=209.85.210.171 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="AQpyxl2P" Received: by mail-pf1-f171.google.com with SMTP id d2e1a72fcca58-7725147ec88so1132385b3a.0 for ; Fri, 05 Sep 2025 12:15:10 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099710; x=1757704510; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=mUroiBc6AXqcFq5CUo5edWLJp1k73jl4G+DYgeRyCP4=; b=AQpyxl2PPJciUNzbcecMmfBGTCVCFRiclstmNynFjbzY8N7ckIVC42mNb7ivT8OMV/ 31Vme5S6dxn/dafEIr3/ztUdAnSKQQKJaKe6VYKZs7G5VSrZEoqp9qvy6vfx02mPpkBi h852ScUV7hzUu6xwhP1QgaiLbm7mVWTCG6+o4071eJPPSWaGAgqnuDDYyrNCeiJx5Lyo NFpEqDy8Bx3NJdt1+w67muCWgf5+vgZ71+sQEIYBwwCt+psD4APBbNcOFJHO8Cd4KN9o pNWK5Gh7TmoIf2f1Syi93si6krPhGpHr7UfcwDgO5xUD4N3ns03e3oxO8ts0iGkPPxQv zkoQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099710; x=1757704510; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=mUroiBc6AXqcFq5CUo5edWLJp1k73jl4G+DYgeRyCP4=; b=g0X9G70m0tJ2/4hc0VIf0K2hmcYfr21otLnU2Uub4Jiktn+Ykpe0svijz0MdZj/x3u 14rBMV6ok1V6B4birDVXhoVHZUr6nAHQLNKYp/f8kqZ9nqLXHrFMOD5P65SmqC7YoQ02 b4VPICQF19xXaU7TGz5hYsx7HzDg89P0Ebm/q6WJD4ZivW45g4VzNdtHWeKcLRjeBP8A dq2QULKcf780e6/2G2IXH4InA874+Dm4Tg3DKHRrR1m4upQPbUXG7MfWKWFuHPGMSrhw e0tzgPNvahyoWpMrWpBc+Zy1QsugbHfINxfNecInEzxcxW746uRX1fxR9fQrf+Q1I3j8 qVkA== X-Forwarded-Encrypted: i=1; AJvYcCVV/XKUCcWL3LymI6aDApYmDo2My1RmdiGXiUx+lMkqmicoiIcOk+ZgCwdek/nmmTt8R/Npmh18KkG0NAk=@vger.kernel.org X-Gm-Message-State: AOJu0Yz/C4IcxhVb9zSfbNkZTzvFSxNbjDAFPUv03+maeQlEOMzVNvZt AAZMfwZCAVmy033XCF+6Nn+XhL7FXlL3XrVg6O47NnHAHQ3QOeRu8VU+ X-Gm-Gg: ASbGncvuhg2X6J6UokKqWt6FB8+aBczpbpE5C91lGa/FsQBgfyUlcMmZ2NMaInBroLR hrjC2XuW+y964HjpRK7GF1sxL6HSvvJmr3Jg3SfzEwDD+FDH6ckTcayYgKPM4WZREQrfRnfkXOX A9ib3BtMcQZZ+C7ao/05d1xkjCTz6VbBTzL5B3awmFQ9yWAwsNW7zzYc38FfijEOQQRNgurlkOC Sn2kDXGiY1uAS+TySKuAUSMTPikGToiSOoWrWFDE202oW7ME88NfaCjCwm4XS9JCkzIIhD4YAkj ZfQkXcYiHoelXooDfsMoOg171Ff+s2guZhLL3PlX2uD/aE8eund11x1BQgeCJaxCHJL5HVKHRat sv66LbcOMG6iExriwoyCspG0QiSWC3c/UqfZ4eo6aiLSeIZg= X-Google-Smtp-Source: AGHT+IEQG4xHRhrV5M4T/jaUcuMfZcwJ4zOzM9Ghh9wGZUXiJYzLJRWMICkyNlXpAReTH8qkBRZoNw== X-Received: by 2002:a05:6a00:4b0b:b0:76b:ecf2:7ece with SMTP id d2e1a72fcca58-7741bf4b456mr5306017b3a.12.1757099709646; Fri, 05 Sep 2025 12:15:09 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.15.04 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:15:09 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 11/15] mm, swap: use the swap table for the swap cache and switch API Date: Sat, 6 Sep 2025 03:13:53 +0800 Message-ID: <20250905191357.78298-12-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song Introduce basic swap table infrastructures, which are now just a fixed-sized flat array inside each swap cluster, with access wrappers. Each cluster contains a swap table of 512 entries. Each table entry is an opaque atomic long. It could be in 3 types: a shadow type (XA_VALUE), a folio type (pointer), or NULL. In this first step, it only supports storing a folio or shadow, and it is a drop-in replacement for the current swap cache. Convert all swap cache users to use the new sets of APIs. Chris Li has been suggesting using a new infrastructure for swap cache for better performance, and that idea combined well with the swap table as the new backing structure. Now the lock contention range is reduced to 2M clusters, which is much smaller than the 64M address_space. And we can also drop the multiple address_space design. All the internal works are done with swap_cache_get_* helpers. Swap cache lookup is still lock-less like before, and the helper's contexts are same with original swap cache helpers. They still require a pin on the swap device to prevent the backing data from being freed. Swap cache updates are now protected by the swap cluster lock instead of the Xarray lock. This is mostly handled internally, but new __swap_cache_* helpers require the caller to lock the cluster. So, a few new cluster access and locking helpers are also introduced. A fully cluster-based unified swap table can be implemented on top of this to take care of all count tracking and synchronization work, with dynamic allocation. It should reduce the memory usage while making the performance even better. Co-developed-by: Chris Li Signed-off-by: Chris Li Signed-off-by: Kairui Song Acked-by: Chris Li Suggested-by: Chris Li --- MAINTAINERS | 1 + include/linux/swap.h | 2 - mm/huge_memory.c | 13 +- mm/migrate.c | 19 ++- mm/shmem.c | 8 +- mm/swap.h | 157 +++++++++++++++++------ mm/swap_state.c | 289 +++++++++++++++++++------------------------ mm/swap_table.h | 97 +++++++++++++++ mm/swapfile.c | 100 +++++++++++---- mm/vmscan.c | 20 ++- 10 files changed, 458 insertions(+), 248 deletions(-) create mode 100644 mm/swap_table.h diff --git a/MAINTAINERS b/MAINTAINERS index 1c8292c0318d..de402ca91a80 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -16226,6 +16226,7 @@ F: include/linux/swapops.h F: mm/page_io.c F: mm/swap.c F: mm/swap.h +F: mm/swap_table.h F: mm/swap_state.c F: mm/swapfile.c =20 diff --git a/include/linux/swap.h b/include/linux/swap.h index 6db105383782..2cb0458561ef 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -480,8 +480,6 @@ 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); struct backing_dev_info; -extern int init_swap_address_space(unsigned int type, unsigned long nr_pag= es); -extern void exit_swap_address_space(unsigned int type); extern struct swap_info_struct *get_swap_device(swp_entry_t entry); sector_t swap_folio_sector(struct folio *folio); =20 diff --git a/mm/huge_memory.c b/mm/huge_memory.c index a4d192c8d794..052e8fc7ee0c 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -3720,7 +3720,7 @@ static int __folio_split(struct folio *folio, unsigne= d int new_order, /* Prevent deferred_split_scan() touching ->_refcount */ spin_lock(&ds_queue->split_queue_lock); if (folio_ref_freeze(folio, 1 + extra_pins)) { - struct address_space *swap_cache =3D NULL; + struct swap_cluster_info *ci =3D NULL; struct lruvec *lruvec; int expected_refs; =20 @@ -3764,8 +3764,7 @@ static int __folio_split(struct folio *folio, unsigne= d int new_order, goto fail; } =20 - swap_cache =3D swap_address_space(folio->swap); - xa_lock(&swap_cache->i_pages); + ci =3D swap_cluster_lock_by_folio(folio); } =20 /* lock lru list/PageCompound, ref frozen by page_ref_freeze */ @@ -3797,8 +3796,8 @@ static int __folio_split(struct folio *folio, unsigne= d int new_order, * Anonymous folio with swap cache. * NOTE: shmem in swap cache is not supported yet. */ - if (swap_cache) { - __swap_cache_replace_folio(swap_cache, new_folio->swap, + if (ci) { + __swap_cache_replace_folio(ci, new_folio->swap, folio, new_folio); continue; } @@ -3834,8 +3833,8 @@ static int __folio_split(struct folio *folio, unsigne= d int new_order, =20 unlock_page_lruvec(lruvec); =20 - if (swap_cache) - xa_unlock(&swap_cache->i_pages); + if (ci) + swap_cluster_unlock(ci); } else { spin_unlock(&ds_queue->split_queue_lock); ret =3D -EAGAIN; diff --git a/mm/migrate.c b/mm/migrate.c index 7e1d01aa8c85..ea177ef1fea9 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -563,6 +563,7 @@ 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(folio)); + struct swap_cluster_info *ci =3D NULL; struct zone *oldzone, *newzone; int dirty; long nr =3D folio_nr_pages(folio); @@ -591,9 +592,16 @@ static int __folio_migrate_mapping(struct address_spac= e *mapping, oldzone =3D folio_zone(folio); newzone =3D folio_zone(newfolio); =20 - xas_lock_irq(&xas); + if (folio_test_swapcache(folio)) + ci =3D swap_cluster_lock_by_folio_irq(folio); + else + xas_lock_irq(&xas); + if (!folio_ref_freeze(folio, expected_count)) { - xas_unlock_irq(&xas); + if (ci) + swap_cluster_unlock(ci); + else + xas_unlock_irq(&xas); return -EAGAIN; } =20 @@ -624,7 +632,7 @@ static int __folio_migrate_mapping(struct address_space= *mapping, } =20 if (folio_test_swapcache(folio)) - __swap_cache_replace_folio(mapping, folio->swap, folio, newfolio); + __swap_cache_replace_folio(ci, folio->swap, folio, newfolio); else xas_store(&xas, newfolio); =20 @@ -635,8 +643,11 @@ static int __folio_migrate_mapping(struct address_spac= e *mapping, */ folio_ref_unfreeze(folio, expected_count - nr); =20 - xas_unlock(&xas); /* Leave irq disabled to prevent preemption while updating stats */ + if (ci) + swap_cluster_unlock(ci); + else + xas_unlock(&xas); =20 /* * If moved to a different zone then also account diff --git a/mm/shmem.c b/mm/shmem.c index 823ceae9dff8..21e795f18e78 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -2120,9 +2120,9 @@ 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; - struct address_space *swap_mapping =3D swap_address_space(entry); int nr_pages =3D folio_nr_pages(old); int error =3D 0; =20 @@ -2153,9 +2153,9 @@ static int shmem_replace_folio(struct folio **foliop,= gfp_t gfp, new->swap =3D entry; folio_set_swapcache(new); =20 - xa_lock_irq(&swap_mapping->i_pages); - __swap_cache_replace_folio(swap_mapping, entry, old, new); - xa_unlock_irq(&swap_mapping->i_pages); + ci =3D swap_cluster_lock_by_folio_irq(old); + __swap_cache_replace_folio(ci, entry, old, new); + swap_cluster_unlock(ci); =20 mem_cgroup_replace_folio(old, new); shmem_update_stats(new, nr_pages); diff --git a/mm/swap.h b/mm/swap.h index a139c9131244..bf4e54f1f6b6 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -2,6 +2,7 @@ #ifndef _MM_SWAP_H #define _MM_SWAP_H =20 +#include /* for atomic_long_t */ struct mempolicy; struct swap_iocb; =20 @@ -35,6 +36,7 @@ struct swap_cluster_info { u16 count; u8 flags; u8 order; + atomic_long_t *table; /* Swap table entries, see mm/swap_table.h */ struct list_head list; }; =20 @@ -55,6 +57,11 @@ 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) +{ + return swp_offset(entry) % SWAPFILE_CLUSTER; +} + /* * Callers of all helpers below must ensure the entry, type, or offset is * valid, and protect the swap device with reference count or locks. @@ -81,6 +88,25 @@ static inline struct swap_cluster_info *__swap_offset_to= _cluster( return &si->cluster_info[offset / SWAPFILE_CLUSTER]; } =20 +static inline struct swap_cluster_info *__swap_entry_to_cluster(swp_entry_= t entry) +{ + return __swap_offset_to_cluster(__swap_entry_to_info(entry), + swp_offset(entry)); +} + +static __always_inline struct swap_cluster_info *__swap_cluster_lock( + struct swap_info_struct *si, unsigned long offset, bool irq) +{ + struct swap_cluster_info *ci =3D __swap_offset_to_cluster(si, offset); + + VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ + if (irq) + spin_lock_irq(&ci->lock); + else + spin_lock(&ci->lock); + return ci; +} + /** * swap_cluster_lock - Lock and return the swap cluster of given offset. * @si: swap device the cluster belongs to. @@ -92,11 +118,48 @@ static inline struct swap_cluster_info *__swap_offset_= to_cluster( static inline struct swap_cluster_info *swap_cluster_lock( struct swap_info_struct *si, unsigned long offset) { - struct swap_cluster_info *ci =3D __swap_offset_to_cluster(si, offset); + return __swap_cluster_lock(si, offset, false); +} =20 - VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ - spin_lock(&ci->lock); - return ci; +static inline struct swap_cluster_info *__swap_cluster_lock_by_folio( + const struct folio *folio, bool irq) +{ + 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); +} + +/* + * swap_cluster_lock_by_folio - Locks the cluster that holds a folio's ent= ries. + * @folio: The folio. + * + * This locks the swap cluster that contains a folio's swap entries. The + * swap entries of a folio are always in one single cluster, and a locked + * swap cache folio is enough to stabilize the entries and the swap device. + * + * Context: Caller must ensure the folio is locked and in the swap cache. + * Return: Pointer to the swap cluster. + */ +static inline struct swap_cluster_info *swap_cluster_lock_by_folio( + const struct folio *folio) +{ + return __swap_cluster_lock_by_folio(folio, false); +} + +/* + * swap_cluster_lock_by_folio_irq - Locks the cluster that holds a folio's= entries. + * @folio: The folio. + * + * Same as swap_cluster_lock_by_folio but also disable IRQ. + * + * Context: Caller must ensure the folio is locked and in the swap cache. + * Return: Pointer to the swap cluster. + */ +static inline struct swap_cluster_info *swap_cluster_lock_by_folio_irq( + const struct folio *folio) +{ + return __swap_cluster_lock_by_folio(folio, true); } =20 static inline void swap_cluster_unlock(struct swap_cluster_info *ci) @@ -104,6 +167,11 @@ static inline void swap_cluster_unlock(struct swap_clu= ster_info *ci) spin_unlock(&ci->lock); } =20 +static inline void swap_cluster_unlock_irq(struct swap_cluster_info *ci) +{ + spin_unlock_irq(&ci->lock); +} + /* linux/mm/page_io.c */ int sio_pool_init(void); struct swap_iocb; @@ -123,10 +191,11 @@ void __swap_writepage(struct folio *folio, struct swa= p_iocb **swap_plug); #define SWAP_ADDRESS_SPACE_SHIFT 14 #define SWAP_ADDRESS_SPACE_PAGES (1 << SWAP_ADDRESS_SPACE_SHIFT) #define SWAP_ADDRESS_SPACE_MASK (SWAP_ADDRESS_SPACE_PAGES - 1) -extern struct address_space *swapper_spaces[]; -#define swap_address_space(entry) \ - (&swapper_spaces[swp_type(entry)][swp_offset(entry) \ - >> SWAP_ADDRESS_SPACE_SHIFT]) +extern struct address_space swap_space; +static inline struct address_space *swap_address_space(swp_entry_t entry) +{ + return &swap_space; +} =20 /* * Return the swap device position of the swap entry. @@ -136,15 +205,6 @@ static inline loff_t swap_dev_pos(swp_entry_t entry) return ((loff_t)swp_offset(entry)) << PAGE_SHIFT; } =20 -/* - * Return the swap cache index of the swap entry. - */ -static inline pgoff_t swap_cache_index(swp_entry_t entry) -{ - BUILD_BUG_ON((SWP_OFFSET_MASK | SWAP_ADDRESS_SPACE_MASK) !=3D SWP_OFFSET_= MASK); - return swp_offset(entry) & SWAP_ADDRESS_SPACE_MASK; -} - /** * folio_matches_swap_entry - Check if a folio matches a given swap entry. * @folio: The folio. @@ -177,16 +237,15 @@ 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); -void __swap_cache_del_folio(struct folio *folio, - swp_entry_t entry, void *shadow); -void __swap_cache_replace_folio(struct address_space *address_space, - swp_entry_t entry, - struct folio *old, struct folio *new); -void swap_cache_clear_shadow(int type, unsigned long begin, - unsigned long end); +/* 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, + swp_entry_t entry, 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); @@ -254,6 +313,32 @@ static inline int non_swapcache_batch(swp_entry_t entr= y, int max_nr) =20 #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) +{ + return NULL; +} + +static inline struct swap_cluster_info *swap_cluster_lock_by_folio( + struct folio *folio) +{ + return NULL; +} + +static inline struct swap_cluster_info *swap_cluster_lock_by_folio_irq( + struct folio *folio) +{ + return NULL; +} + +static inline void swap_cluster_unlock(struct swap_cluster_info *ci) +{ +} + +static inline void swap_cluster_unlock_irq(struct swap_cluster_info *ci) +{ +} + static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t en= try) { return NULL; @@ -271,11 +356,6 @@ static inline struct address_space *swap_address_space= (swp_entry_t entry) return NULL; } =20 -static inline pgoff_t swap_cache_index(swp_entry_t entry) -{ - return 0; -} - static inline bool folio_matches_swap_entry(const struct folio *folio, swp= _entry_t entry) { return false; @@ -322,17 +402,22 @@ static inline void *swap_cache_get_shadow(swp_entry_t= entry) return NULL; } =20 -static inline int swap_cache_add_folio(swp_entry_t entry, struct folio *fo= lio, - gfp_t gfp, void **shadow) +static inline void swap_cache_add_folio(struct folio *folio, swp_entry_t e= ntry, void **shadow) { - return -EINVAL; } =20 static inline void swap_cache_del_folio(struct folio *folio) { } =20 -static inline void __swap_cache_del_folio(swp_entry_t entry, struct folio = *folio, void *shadow) +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_replace_folio( + struct swap_cluster_info *ci, swp_entry_t entry, + struct folio *old, struct folio *new) { } =20 @@ -367,7 +452,7 @@ static inline int non_swapcache_batch(swp_entry_t entry= , int max_nr) static inline pgoff_t folio_index(struct folio *folio) { if (unlikely(folio_test_swapcache(folio))) - return swap_cache_index(folio->swap); + return swp_offset(folio->swap); return folio->index; } =20 diff --git a/mm/swap_state.c b/mm/swap_state.c index 38f5f4cf565d..7147b390745f 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -23,6 +23,7 @@ #include #include #include "internal.h" +#include "swap_table.h" #include "swap.h" =20 /* @@ -36,8 +37,10 @@ static const struct address_space_operations swap_aops = =3D { #endif }; =20 -struct address_space *swapper_spaces[MAX_SWAPFILES] __read_mostly; -static unsigned int nr_swapper_spaces[MAX_SWAPFILES] __read_mostly; +struct address_space swap_space __read_mostly =3D { + .a_ops =3D &swap_aops, +}; + static bool enable_vma_readahead __read_mostly =3D true; =20 #define SWAP_RA_ORDER_CEILING 5 @@ -83,11 +86,21 @@ void show_swap_cache_info(void) */ struct folio *swap_cache_get_folio(swp_entry_t entry) { - struct folio *folio =3D filemap_get_folio(swap_address_space(entry), - swap_cache_index(entry)); - if (IS_ERR(folio)) - return NULL; - return folio; + + unsigned long swp_tb; + struct folio *folio; + + for (;;) { + swp_tb =3D __swap_table_get(__swap_entry_to_cluster(entry), + swp_cluster_offset(entry)); + if (!swp_tb_is_folio(swp_tb)) + return NULL; + folio =3D swp_tb_to_folio(swp_tb); + if (likely(folio_try_get(folio))) + return folio; + } + + return NULL; } =20 /** @@ -100,13 +113,13 @@ struct folio *swap_cache_get_folio(swp_entry_t entry) */ void *swap_cache_get_shadow(swp_entry_t entry) { - struct address_space *address_space =3D swap_address_space(entry); - pgoff_t idx =3D swap_cache_index(entry); - void *shadow; + unsigned long swp_tb; + + 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); =20 - shadow =3D xa_load(&address_space->i_pages, idx); - if (xa_is_value(shadow)) - return shadow; return NULL; } =20 @@ -123,57 +136,45 @@ void *swap_cache_get_shadow(swp_entry_t entry) * SWAP_HAS_CACHE to avoid race or conflict. * Return: Returns 0 on success, error code otherwise. */ -int swap_cache_add_folio(struct folio *folio, swp_entry_t entry, - gfp_t gfp, void **shadowp) +void swap_cache_add_folio(struct folio *folio, swp_entry_t entry, void **s= hadowp) { - struct address_space *address_space =3D swap_address_space(entry); - pgoff_t idx =3D swap_cache_index(entry); - XA_STATE_ORDER(xas, &address_space->i_pages, idx, folio_order(folio)); - unsigned long i, nr =3D folio_nr_pages(folio); - void *old; - - xas_set_update(&xas, workingset_update_node); - - VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); - VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio); - VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio); + void *shadow =3D NULL; + unsigned long swp_tb, exist; + struct swap_cluster_info *ci; + unsigned int ci_start, ci_off, ci_end; + unsigned long nr_pages =3D folio_nr_pages(folio); + + 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); + + swp_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 { + exist =3D __swap_table_xchg(ci, ci_off, swp_tb); + WARN_ON_ONCE(swp_tb_is_folio(exist)); + if (swp_tb_is_shadow(exist)) + shadow =3D swp_tb_to_shadow(exist); + } while (++ci_off < ci_end); =20 - folio_ref_add(folio, nr); + folio_ref_add(folio, nr_pages); folio_set_swapcache(folio); folio->swap =3D entry; + swap_cluster_unlock(ci); =20 - do { - xas_lock_irq(&xas); - xas_create_range(&xas); - if (xas_error(&xas)) - goto unlock; - for (i =3D 0; i < nr; i++) { - VM_BUG_ON_FOLIO(xas.xa_index !=3D idx + i, folio); - if (shadowp) { - old =3D xas_load(&xas); - if (xa_is_value(old)) - *shadowp =3D old; - } - xas_store(&xas, folio); - xas_next(&xas); - } - address_space->nrpages +=3D nr; - __node_stat_mod_folio(folio, NR_FILE_PAGES, nr); - __lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr); -unlock: - xas_unlock_irq(&xas); - } while (xas_nomem(&xas, gfp)); - - if (!xas_error(&xas)) - return 0; + node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages); + lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages); =20 - folio_clear_swapcache(folio); - folio_ref_sub(folio, nr); - return xas_error(&xas); + if (shadowp) + *shadowp =3D shadow; } =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. @@ -181,34 +182,36 @@ int swap_cache_add_folio(struct folio *folio, swp_ent= ry_t entry, * 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 hold the xa_lock, ensure the folio is - * locked and in the swap cache, using the index of @entry. + * 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. */ -void __swap_cache_del_folio(struct folio *folio, +void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *fo= lio, swp_entry_t entry, void *shadow) { - struct address_space *address_space =3D swap_address_space(entry); - int i; - long nr =3D folio_nr_pages(folio); - pgoff_t idx =3D swap_cache_index(entry); - XA_STATE(xas, &address_space->i_pages, idx); - - xas_set_update(&xas, workingset_update_node); - - VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); - VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio); - VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio); - - for (i =3D 0; i < nr; i++) { - void *entry =3D xas_store(&xas, shadow); - VM_BUG_ON_PAGE(entry !=3D folio, entry); - xas_next(&xas); - } + unsigned long exist, swp_tb; + unsigned int ci_start, ci_off, ci_end; + unsigned long nr_pages =3D folio_nr_pages(folio); + + 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); + + swp_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 */ + exist =3D __swap_table_xchg(ci, ci_off, swp_tb); + WARN_ON_ONCE(!swp_tb_is_folio(exist) || + swp_tb_to_folio(exist) !=3D folio); + } while (++ci_off < ci_end); + folio->swap.val =3D 0; folio_clear_swapcache(folio); - address_space->nrpages -=3D nr; - __node_stat_mod_folio(folio, NR_FILE_PAGES, -nr); - __lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr); + node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages); + lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages); } =20 /** @@ -223,12 +226,12 @@ void __swap_cache_del_folio(struct folio *folio, */ void swap_cache_del_folio(struct folio *folio) { + struct swap_cluster_info *ci; swp_entry_t entry =3D folio->swap; - struct address_space *address_space =3D swap_address_space(entry); =20 - xa_lock_irq(&address_space->i_pages); - __swap_cache_del_folio(folio, entry, NULL); - xa_unlock_irq(&address_space->i_pages); + 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); =20 put_swap_folio(folio, entry); folio_ref_sub(folio, folio_nr_pages(folio)); @@ -236,7 +239,7 @@ void swap_cache_del_folio(struct folio *folio) =20 /** * __swap_cache_replace_folio - Replace a folio in the swap cache. - * @mapping: Swap mapping address space. + * @ci: The locked swap cluster. * @entry: The first swap entry that the new folio corresponds to. * @old: The old folio to be replaced. * @new: The new folio. @@ -244,64 +247,58 @@ void swap_cache_del_folio(struct folio *folio) * Replace a existing folio in the swap cache with a new folio. * * Context: Caller must ensure both folios are locked, and lock the - * swap address_space that holds the entries to be replaced. + * cluster that holds the entries to be replaced. */ -void __swap_cache_replace_folio(struct address_space *mapping, - swp_entry_t entry, +void __swap_cache_replace_folio(struct swap_cluster_info *ci, swp_entry_t = entry, struct folio *old, struct folio *new) { + unsigned int ci_off =3D swp_cluster_offset(entry); unsigned long nr_pages =3D folio_nr_pages(new); - unsigned long offset =3D swap_cache_index(entry); - unsigned long end =3D offset + nr_pages; - XA_STATE(xas, &mapping->i_pages, offset); + unsigned int ci_end =3D ci_off + nr_pages; + unsigned long exist, swp_tb; =20 VM_WARN_ON_ONCE(entry.val !=3D new->swap.val); VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new)); VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new)); - - /* Swap cache still stores N entries instead of a high-order entry */ + swp_tb =3D folio_to_swp_tb(new); do { - WARN_ON_ONCE(xas_store(&xas, new) !=3D old); - xas_next(&xas); - } while (++offset < end); + exist =3D __swap_table_xchg(ci, ci_off, swp_tb); + WARN_ON_ONCE(!swp_tb_is_folio(exist) || swp_tb_to_folio(exist) !=3D old); + } 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); + } } =20 /** * swap_cache_clear_shadow - Clears a set of shadows in the swap cache. - * @type: Indicates the swap device. - * @begin: Beginning offset of the range. - * @end: Ending offset of the range. + * @entry: The starting index entry. + * @nr_ents: How many slots need to be cleared. * - * Context: Caller must ensure the range is valid and hold a reference to - * the swap device. + * Context: Caller must ensure the range is valid, not occupied by, + * any folio and protect the swap device with reference count or locks. */ -void swap_cache_clear_shadow(int type, unsigned long begin, - unsigned long end) +void __swap_cache_clear_shadow(swp_entry_t entry, int nr_ents) { - unsigned long curr =3D begin; - void *old; - - for (;;) { - swp_entry_t entry =3D swp_entry(type, curr); - unsigned long index =3D curr & SWAP_ADDRESS_SPACE_MASK; - struct address_space *address_space =3D swap_address_space(entry); - XA_STATE(xas, &address_space->i_pages, index); - - xas_set_update(&xas, workingset_update_node); - - xa_lock_irq(&address_space->i_pages); - xas_for_each(&xas, old, min(index + (end - curr), SWAP_ADDRESS_SPACE_PAG= ES)) { - if (!xa_is_value(old)) - continue; - xas_store(&xas, NULL); - } - xa_unlock_irq(&address_space->i_pages); + 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; =20 - /* search the next swapcache until we meet end */ - curr =3D ALIGN((curr + 1), SWAP_ADDRESS_SPACE_PAGES); - if (curr > end) - break; - } + 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); } =20 /* @@ -481,10 +478,7 @@ 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 - /* 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); memcg1_swapin(entry, 1); =20 if (shadow) @@ -676,41 +670,6 @@ struct folio *swap_cluster_readahead(swp_entry_t entry= , gfp_t gfp_mask, return folio; } =20 -int init_swap_address_space(unsigned int type, unsigned long nr_pages) -{ - struct address_space *spaces, *space; - unsigned int i, nr; - - nr =3D DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES); - spaces =3D kvcalloc(nr, sizeof(struct address_space), GFP_KERNEL); - if (!spaces) - return -ENOMEM; - for (i =3D 0; i < nr; i++) { - space =3D spaces + i; - xa_init_flags(&space->i_pages, XA_FLAGS_LOCK_IRQ); - atomic_set(&space->i_mmap_writable, 0); - space->a_ops =3D &swap_aops; - /* swap cache doesn't use writeback related tags */ - mapping_set_no_writeback_tags(space); - } - nr_swapper_spaces[type] =3D nr; - swapper_spaces[type] =3D spaces; - - return 0; -} - -void exit_swap_address_space(unsigned int type) -{ - int i; - struct address_space *spaces =3D swapper_spaces[type]; - - for (i =3D 0; i < nr_swapper_spaces[type]; i++) - VM_WARN_ON_ONCE(!mapping_empty(&spaces[i])); - kvfree(spaces); - nr_swapper_spaces[type] =3D 0; - swapper_spaces[type] =3D NULL; -} - static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start, unsigned long *end) { @@ -883,7 +842,7 @@ static const struct attribute_group swap_attr_group =3D= { .attrs =3D swap_attrs, }; =20 -static int __init swap_init_sysfs(void) +static int __init swap_init(void) { int err; struct kobject *swap_kobj; @@ -898,11 +857,13 @@ static int __init swap_init_sysfs(void) pr_err("failed to register swap group\n"); goto delete_obj; } + /* Swap cache writeback is LRU based, no tags for it */ + mapping_set_no_writeback_tags(&swap_space); return 0; =20 delete_obj: kobject_put(swap_kobj); return err; } -subsys_initcall(swap_init_sysfs); +subsys_initcall(swap_init); #endif diff --git a/mm/swap_table.h b/mm/swap_table.h new file mode 100644 index 000000000000..e1f7cc009701 --- /dev/null +++ b/mm/swap_table.h @@ -0,0 +1,97 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _MM_SWAP_TABLE_H +#define _MM_SWAP_TABLE_H + +#include "swap.h" + +/* + * 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. + */ +static inline void __swap_table_set(struct swap_cluster_info *ci, + unsigned int off, unsigned long swp_tb) +{ + VM_WARN_ON_ONCE(off >=3D SWAPFILE_CLUSTER); + atomic_long_set(&ci->table[off], swp_tb); +} + +static inline unsigned long __swap_table_xchg(struct swap_cluster_info *ci, + unsigned int off, unsigned long swp_tb) +{ + VM_WARN_ON_ONCE(off >=3D SWAPFILE_CLUSTER); + /* Ordering is guaranteed by cluster lock, relax */ + return atomic_long_xchg_relaxed(&ci->table[off], swp_tb); +} + +static inline unsigned long __swap_table_get(struct swap_cluster_info *ci, + unsigned int off) +{ + VM_WARN_ON_ONCE(off >=3D SWAPFILE_CLUSTER); + return atomic_long_read(&ci->table[off]); +} +#endif diff --git a/mm/swapfile.c b/mm/swapfile.c index 731b541b1d33..cbb7d4c0773d 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -46,6 +46,7 @@ #include #include #include +#include "swap_table.h" #include "internal.h" #include "swap.h" =20 @@ -420,6 +421,34 @@ static inline unsigned int cluster_offset(struct swap_= info_struct *si, return cluster_index(si, ci) * SWAPFILE_CLUSTER; } =20 +static int swap_table_alloc_table(struct swap_cluster_info *ci) +{ + WARN_ON(ci->table); + ci->table =3D kzalloc(sizeof(unsigned long) * SWAPFILE_CLUSTER, GFP_KERNE= L); + if (!ci->table) + return -ENOMEM; + return 0; +} + +static void swap_cluster_free_table(struct swap_cluster_info *ci) +{ + unsigned int ci_off; + unsigned long swp_tb; + + if (!ci->table) + return; + + for (ci_off =3D 0; ci_off < SWAPFILE_CLUSTER; ci_off++) { + swp_tb =3D __swap_table_get(ci, ci_off); + if (!swp_tb_is_null(swp_tb)) + pr_err_once("swap: unclean swap space on swapoff: 0x%lx", + swp_tb); + } + + kfree(ci->table); + ci->table =3D NULL; +} + static void move_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci, struct list_head *list, enum swap_cluster_flags new_flags) @@ -702,6 +731,26 @@ 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 cluster_table_check(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) @@ -721,6 +770,7 @@ 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); + cluster_table_check(ci, start, nr_pages); swap_range_alloc(si, nr_pages); ci->count +=3D nr_pages; =20 @@ -1123,7 +1173,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(si->type, begin, end); + __swap_cache_clear_shadow(swp_entry(si->type, begin), nr_entries); =20 /* * Make sure that try_to_unuse() observes si->inuse_pages reaching 0 @@ -1280,16 +1330,7 @@ int folio_alloc_swap(struct folio *folio, gfp_t gfp) if (!entry.val) return -ENOMEM; =20 - /* - * XArray node allocations from PF_MEMALLOC contexts could - * completely exhaust the page allocator. __GFP_NOMEMALLOC - * stops emergency reserves from being allocated. - * - * TODO: this could cause a theoretical memory reclaim - * deadlock in the swap out path. - */ - if (swap_cache_add_folio(folio, entry, gfp | __GFP_NOMEMALLOC, NULL)) - goto out_free; + swap_cache_add_folio(folio, entry, NULL); =20 return 0; =20 @@ -1555,6 +1596,7 @@ 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); + cluster_table_check(ci, offset, nr_pages); =20 if (!ci->count) free_cluster(si, ci); @@ -2632,6 +2674,18 @@ static void wait_for_allocation(struct swap_info_str= uct *si) } } =20 +static void free_cluster_info(struct swap_cluster_info *cluster_info, + unsigned long maxpages) +{ + int i, nr_clusters =3D DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); + + if (!cluster_info) + return; + for (i =3D 0; i < nr_clusters; i++) + swap_cluster_free_table(&cluster_info[i]); + kvfree(cluster_info); +} + /* * Called after swap device's reference count is dead, so * neither scan nor allocation will use it. @@ -2766,12 +2820,13 @@ SYSCALL_DEFINE1(swapoff, const char __user *, speci= alfile) =20 swap_file =3D p->swap_file; p->swap_file =3D NULL; - p->max =3D 0; swap_map =3D p->swap_map; p->swap_map =3D NULL; zeromap =3D p->zeromap; p->zeromap =3D NULL; cluster_info =3D p->cluster_info; + free_cluster_info(cluster_info, p->max); + p->max =3D 0; p->cluster_info =3D NULL; spin_unlock(&p->lock); spin_unlock(&swap_lock); @@ -2782,10 +2837,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specia= lfile) p->global_cluster =3D NULL; vfree(swap_map); kvfree(zeromap); - kvfree(cluster_info); /* Destroy swap account information */ swap_cgroup_swapoff(p->type); - exit_swap_address_space(p->type); =20 inode =3D mapping->host; =20 @@ -3169,8 +3222,11 @@ static struct swap_cluster_info *setup_clusters(stru= ct swap_info_struct *si, if (!cluster_info) goto err; =20 - for (i =3D 0; i < nr_clusters; i++) + for (i =3D 0; i < nr_clusters; i++) { spin_lock_init(&cluster_info[i].lock); + if (swap_table_alloc_table(&cluster_info[i])) + goto err_free; + } =20 if (!(si->flags & SWP_SOLIDSTATE)) { si->global_cluster =3D kmalloc(sizeof(*si->global_cluster), @@ -3231,9 +3287,8 @@ static struct swap_cluster_info *setup_clusters(struc= t swap_info_struct *si, } =20 return cluster_info; - err_free: - kvfree(cluster_info); + free_cluster_info(cluster_info, maxpages); err: return ERR_PTR(err); } @@ -3427,13 +3482,9 @@ SYSCALL_DEFINE2(swapon, const char __user *, special= file, int, swap_flags) } } =20 - error =3D init_swap_address_space(si->type, maxpages); - if (error) - goto bad_swap_unlock_inode; - error =3D zswap_swapon(si->type, maxpages); if (error) - goto free_swap_address_space; + goto bad_swap_unlock_inode; =20 /* * Flush any pending IO and dirty mappings before we start using this @@ -3468,8 +3519,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) goto out; free_swap_zswap: zswap_swapoff(si->type); -free_swap_address_space: - exit_swap_address_space(si->type); bad_swap_unlock_inode: inode_unlock(inode); bad_swap: @@ -3484,7 +3533,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) spin_unlock(&swap_lock); vfree(swap_map); kvfree(zeromap); - kvfree(cluster_info); + if (cluster_info) + free_cluster_info(cluster_info, maxpages); if (inced_nr_rotate_swap) atomic_dec(&nr_rotate_swap); if (swap_file) diff --git a/mm/vmscan.c b/mm/vmscan.c index c79c6806560b..1d5335993313 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -730,13 +730,18 @@ 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)) + if (folio_test_swapcache(folio)) { + ci =3D swap_cluster_lock_by_folio_irq(folio); + } else { spin_lock(&mapping->host->i_lock); - xa_lock_irq(&mapping->i_pages); + xa_lock_irq(&mapping->i_pages); + } + /* * The non racy check for a busy folio. * @@ -776,9 +781,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(folio, swap, shadow); + __swap_cache_del_folio(ci, folio, swap, shadow); memcg1_swapout(folio, swap); - xa_unlock_irq(&mapping->i_pages); + swap_cluster_unlock_irq(ci); put_swap_folio(folio, swap); } else { void (*free_folio)(struct folio *); @@ -816,9 +821,12 @@ static int __remove_mapping(struct address_space *mapp= ing, struct folio *folio, return 1; =20 cannot_free: - xa_unlock_irq(&mapping->i_pages); - if (!folio_test_swapcache(folio)) + if (folio_test_swapcache(folio)) { + swap_cluster_unlock_irq(ci); + } else { + xa_unlock_irq(&mapping->i_pages); spin_unlock(&mapping->host->i_lock); + } return 0; } =20 --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pj1-f43.google.com (mail-pj1-f43.google.com [209.85.216.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 AB76827EFE7 for ; Fri, 5 Sep 2025 19:15:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.43 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099719; cv=none; b=gIvmqaKkLyNEgf0scxbrZsxRDGe945oKgV7eCBHPs65w/tlFmOb/MTXRfND8mhcgXNFOzYarVdo9h5HFTwr3hokWmbETy6Qfbs6ZQMF4iFdBsh5vcC4Yj4XzP1GLcUw22SiZyw4uYtVcqQ1yrcssFXoEEYZvDdBhltB8M5SsTlw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099719; c=relaxed/simple; bh=ZZVE6780Tc4CYdtj3mmdcqTBtUymc3eqy1ZEbeptUMg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=RCzEEF/A7Sfr+76S3GzTZikT0eoZ4kY3e8C491Tcmy1VSidXjiS2HEE6l3t5CxuHjg4uEarVMP7tif6L6W4SMKOnTr66/tkUEx7LQg6J00bxhvTtp9SNGtXZq2Lobozeq3t/C6arbYc4bjT74vM/1tdIeT5BeYEtfVo9fBQyeHo= 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=KyO8Prh3; arc=none smtp.client-ip=209.85.216.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="KyO8Prh3" Received: by mail-pj1-f43.google.com with SMTP id 98e67ed59e1d1-32d3e17d925so161705a91.2 for ; Fri, 05 Sep 2025 12:15:17 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099717; x=1757704517; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=9s8hZ7R4zViy+wFgr3fw3L0ssVquOrWHeMQPoSASmCw=; b=KyO8Prh3STUipE/NuOEJak1rp/qZ+wbICdj/C8gVs260ZJ0LqNSa4CWYQcZUYNmbMr 7hWsGE4XGZ2NYfCbf4692rvDZhNwA4t536lQygODh1ErUXBHS38o+mTlcIaat6ZnjQJ5 xHtUfp08wG3or0Xebqm6FSxbZCEqrYm3OUVHV40tJdsCzYeOg+ga41N3Kj7/OsKkdFcx dtJvxU7ScbZqHfd9KKvm66GlGkBzIJHzVsmJINVJO2SqUMEieNyG2Ijs4Qy9LkeGmV3o hAWUFwUcGWkbrew3rtCD6aQpfQSukpEPIT/t6GhkwSn7c8ZJn+rpXhJZiZ2BHN2kAwWb xz7Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099717; x=1757704517; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=9s8hZ7R4zViy+wFgr3fw3L0ssVquOrWHeMQPoSASmCw=; b=AKCwZscEdYakwnxHi9nir84XJHDwojSnogJ59mBfosGbOt3UQqPU3H2PciMUAj5IiX HzxfsduJaMMk/vQpFQxF1lX4HSYRrN6WgEMYkL5F4ph2SSvF3rKiLnznbKXCQgPNyXzL huFYXuJzO8bfnapPCBJ69L6dU0ynvDNPgSRoJFRNXqGU4E7zUg/9D+0sjoJCpSj5ug7X RPPFr3SDtHvo5+zkGUWsYMcAubHksqiTcWCp/f2IJ/oMFPZDYZB7ublNDXG5htq/SYRP 83Baf3KZ6CVWUme27WC8k7Oc8VGQZ9x7nwk98+CFoCxVjmEcHB1yp0cRqbiPDPwaPtl8 u+bw== X-Forwarded-Encrypted: i=1; AJvYcCVuHYJfpvrDenPKKX/b2vfL5vPo3FBB8rFKaefra9m6WChqmMNo/dyVtPJejgcBB/kjRhqvojj0HfY+1HI=@vger.kernel.org X-Gm-Message-State: AOJu0Yy/j2mixG14iSl+4axFqmniHtDy52m5YR3gLidsdLQ7PRPklo3V AWS73ZlG2032+409ttDdWT0yrczoOorgLucFJyZrNzvVe7+I7hhtUW+1 X-Gm-Gg: ASbGncumJ2rgp6B3/Gda4Sc+0YrgOlqKlM4EUDq0BDMrnt/t40BBne9Ic+/Whc8iar1 wUR5lCz0FXA/UgWXHsZawj0+efSiRdM/EkMNkU1GoHnk+obfj+08lB8PAReIdgYve69ZN1iNgm7 RqtxO7Y/99pvIM2d0O4vDsgJIIIdlyp2Cn6M99Ab/4rQTPfp1X0UNpF9oa/SdI0PMdgsNaUQDOD RPxDpojNSlcK8c5rB85P/oBpShHSR+4kuurbUnLi/pj7PXsA7Z+qA1bXDP9vMZKNlpsX2SGFWn2 nMZtW5v/xZx0vVcjKqZI0D8csuSV7UhXlfwxQg/A7l98WwRC3rFy6lTSv9QAUgIK9zhIwwcZjGa KAQApZc6+ftAfxMAJ/8+GAScwbVzTO61HagITTT7l+FcG4LfOzhCnQSSiHHW5/jQmRfGd X-Google-Smtp-Source: AGHT+IEd9Oqt6BI578NyTBpy1CqRprvjkInlPYYiEsPmHlAXqsCDTLDSG3bcASc0W4CS/dAa/N/jHw== X-Received: by 2002:a17:90b:1802:b0:32b:ca6f:1231 with SMTP id 98e67ed59e1d1-32d43f05005mr15140a91.1.1757099714590; Fri, 05 Sep 2025 12:15:14 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.15.09 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:15:14 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 12/15] mm, swap: mark swap address space ro and add context debug check Date: Sat, 6 Sep 2025 03:13:54 +0800 Message-ID: <20250905191357.78298-13-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song Swap cache is now backed by swap table, and the address space is not holding any mutable data anymore. And swap cache is now protected by the swap cluster lock, instead of the XArray lock. All access to swap cache are wrapped by swap cache helpers. Locking is mostly handled internally by swap cache helpers, only a few __swap_cache_* helpers require the caller to lock the cluster by themselves. Worth noting that, unlike XArray, the cluster lock is not IRQ safe. The swap cache was very different compared to filemap, and now it's completely separated from filemap. Nothing wants to mark or change anything or do a writeback callback in IRQ. So explicitly document this and add a debug check to avoid further potential misuse. And mark the swap cache space as read-only to avoid any user wrongly mixing unexpected filemap helpers with swap cache. Signed-off-by: Kairui Song Acked-by: Chris Li Acked-by: David Hildenbrand Suggested-by: Chris Li --- mm/swap.h | 12 +++++++++++- mm/swap_state.c | 3 ++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/mm/swap.h b/mm/swap.h index bf4e54f1f6b6..e48431a26f89 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -99,6 +99,16 @@ static __always_inline struct swap_cluster_info *__swap_= cluster_lock( { struct swap_cluster_info *ci =3D __swap_offset_to_cluster(si, offset); =20 + /* + * Nothing modifies swap cache in an IRQ context. All access to + * swap cache is wrapped by swap_cache_* helpers, and swap cache + * writeback is handled outside of IRQs. Swapin or swapout never + * occurs in IRQ, and neither does in-place split or replace. + * + * Besides, modifying swap cache requires synchronization with + * swap_map, which was never IRQ safe. + */ + VM_WARN_ON_ONCE(!in_task()); VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */ if (irq) spin_lock_irq(&ci->lock); @@ -191,7 +201,7 @@ void __swap_writepage(struct folio *folio, struct swap_= iocb **swap_plug); #define SWAP_ADDRESS_SPACE_SHIFT 14 #define SWAP_ADDRESS_SPACE_PAGES (1 << SWAP_ADDRESS_SPACE_SHIFT) #define SWAP_ADDRESS_SPACE_MASK (SWAP_ADDRESS_SPACE_PAGES - 1) -extern struct address_space swap_space; +extern struct address_space swap_space __ro_after_init; static inline struct address_space *swap_address_space(swp_entry_t entry) { return &swap_space; diff --git a/mm/swap_state.c b/mm/swap_state.c index 7147b390745f..209d5e9e8d90 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -37,7 +37,8 @@ static const struct address_space_operations swap_aops = =3D { #endif }; =20 -struct address_space swap_space __read_mostly =3D { +/* Set swap_space as read only as swap cache is handled by swap table */ +struct address_space swap_space __ro_after_init =3D { .a_ops =3D &swap_aops, }; =20 --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f170.google.com (mail-pf1-f170.google.com [209.85.210.170]) (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 770AC2BE7B5 for ; Fri, 5 Sep 2025 19:15:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.170 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099725; cv=none; b=HZHZYRu1tjePFsMfDj8wDngINHq/a1lK2+PSgXEuZbnq6Zksq0c1QMRoBrQAmgbqP+SwFeHlH5V6rXPv04h6n7NaIlPMTeisNYCgRNczhjX+Blnhvq0T3mYr0VYt9fv5RfMyz/de7IQTNryifuJ1cK0pF2xXUbGJGm9JmZuLm6s= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099725; c=relaxed/simple; bh=JMGQF9ss8ceQsMt/AnYp4G62XcoIhrBz/bqWmU3BMDo=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=dTGHQ2nG7TFHZLvQyfhzkQIMllgz7INU9nSU/tTRR8O8R5JMPS2W8+YBqbvc9/rOik5of8hpuaioAXP0GkKcyP5tgXfVbh2DNV634uoOkvM6tl+PoAPFqgx+O3xEScKDUYDBZhkm0zyF44MrMghMDHP7d58sTigtqWjfFhrt1FI= 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=LOPXy72b; arc=none smtp.client-ip=209.85.210.170 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="LOPXy72b" Received: by mail-pf1-f170.google.com with SMTP id d2e1a72fcca58-77251d7cca6so2091920b3a.3 for ; Fri, 05 Sep 2025 12:15:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099722; x=1757704522; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=NTNtn8bp73dj8smpZWVlmgVZUs77+apTLTbhCM2474w=; b=LOPXy72bXfi7KecAdQHaG7wLQw2qPi2h/HSI/giNbq8WlgyJd3MaZXK5ju3Iy44KYQ 0hZ/qJvuUcxTpX5naQGpp7TANnJksdZ492lhUWchVKSVHmwWvtmesz9pM+F6IYBfaTl8 4xCKE7mnsAxZw8uaJyEMP/Cbws/8sLyqrjzALNYSsC5oMdFzqYhb5kZfy/czn/vdH8HC n8j575zpsou++fuoRle/l6btAtPM0x9Vyx/zYFBCzlGjJXCll3EVPz0MRjwYhIFnipwW oaRRgiRKoVMOQ5fGzRhEn+pLQMY6AmLRL6RZr+UI2/Zi8uQgO6p10kwSnPi6+RCWgu+C WG1w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099722; x=1757704522; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=NTNtn8bp73dj8smpZWVlmgVZUs77+apTLTbhCM2474w=; b=o49TxnDs5sjkKBNVeOSB5mErTh5EUpWXtXqff9+jnMBzQHqg1wdikIOjiqJ8602eip 5RPWlSblBnnK60tV2UctPtUNBqcMJjOQXG4iLPqrZc9tkvGp81RejhbgX7ekZ26/TkZ6 cngJFWCukno2aDfhGyYeILp/QLyi6d0yQjC0PY//3tdIf4oxnH29KNm/sEVaz2kuCnkY Rlj9bi29BN5bRAK39ISwhI2keRxCuKZqr4b9zbiBL100koPMnekSpliZaEorv++J6Czu j5uOw9q7ylWu+KCvWPDQwazyWfddIDB/7Kw9mvwe11GMB8w280JbtV1SNd4OB9tfcqSZ 2jsg== X-Forwarded-Encrypted: i=1; AJvYcCWmF4MEMUkBRf09ogx7Ih/6a8BxQrXNVwiyV5lAUhdbYV5Vqv6bAKuO4Vs1fgLyutUYN/y4KKXhna3GV5c=@vger.kernel.org X-Gm-Message-State: AOJu0YxqK+19a2G0G130uJ5PLpELAtUA9D3CDQMPN6a6zNLcZJTt+i1u SMw6kCU4tOYiMdiY+J49Rai5+wi+1cdUjok1I0cEH+4MMxvJSSgrt+8f X-Gm-Gg: ASbGncuZ9aunUNeG+nOJvCbraOOupHFUcKTuj1PrIbzKxPQHMVAsORNiwiq9giAt6Xg 17UQ+yCrVB6ya7fSSgbrNOs8Yt/PlJ09DUMRwdvdBd07Eqb1NIJ12g0aPByhZ0aewcIWf+PAT0M omGddWaRzk7rA9sa89u6Dc0m4xRrs1LPd21P0I0uQMJuY89U/ONrnNz05fTEFTS61EsPDRYTwxw atkN6sauFqJK96/JPRzpatFXmSO7CGsAmFD/LkczhFC0gNjbUFTua575ROoEUJWHYcYcdQijYTE q1LqFYgnPr9ixzDlrEmeulxFz7bRyA9+6xaUiTpnvqsGWJeS8OfHQhDnu+l3EPMjLqT/UZOgK5S rVWRuObx5Fxr+/f7mtibtjHFMNuc04FvikCl1athvEOxnNW/2LlvaeVZethIZspNXRFCX X-Google-Smtp-Source: AGHT+IH96qTgWSibnaaMdWjrVapYmHypSxAQB9nXdv+S9Q7X6ROZXhBXtRtbecK0Xwab4dhhHrwjCg== X-Received: by 2002:a05:6300:218a:b0:243:9587:a743 with SMTP id adf61e73a8af0-243d6e06239mr30146256637.23.1757099721686; Fri, 05 Sep 2025 12:15:21 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.15.16 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:15:21 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song , kernel test robot Subject: [PATCH v2 13/15] mm, swap: remove contention workaround for swap cache Date: Sat, 6 Sep 2025 03:13:55 +0800 Message-ID: <20250905191357.78298-14-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song Swap cluster setup will try to shuffle the clusters on initialization. It was helpful to avoid contention for the swap cache space. The cluster size (2M) was much smaller than each swap cache space (64M), so shuffling the cluster means the allocator will try to allocate swap slots that are in different swap cache spaces for each CPU, reducing the chance of two CPUs using the same swap cache space, and hence reducing the contention. Now, swap cache is managed by swap clusters, this shuffle is pointless. Just remove it, and clean up related macros. This also improves the HDD swap performance as shuffling IO is a bad idea for HDD, and now the shuffling is gone. Test have shown a ~40% performance gain for HDD [1]: Doing sequential swap in of 8G data using 8 processes with usemem, average of 3 test runs: Before: 1270.91 KB/s per process After: 1849.54 KB/s per process Link: https://lore.kernel.org/linux-mm/CAMgjq7AdauQ8=3DX0zeih2r21QoV=3D-WWj= 1hyBxLWRzq74n-C=3D-Ng@mail.gmail.com/ [1] Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-lkp/202504241621.f27743ec-lkp@intel.com Signed-off-by: Kairui Song Acked-by: Chris Li Reviewed-by: Barry Song Acked-by: David Hildenbrand Suggested-by: Chris Li --- mm/swap.h | 4 ---- mm/swapfile.c | 32 ++++++++------------------------ mm/zswap.c | 7 +++++-- 3 files changed, 13 insertions(+), 30 deletions(-) diff --git a/mm/swap.h b/mm/swap.h index e48431a26f89..c4fb28845d77 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -197,10 +197,6 @@ int swap_writeout(struct folio *folio, struct swap_ioc= b **swap_plug); void __swap_writepage(struct folio *folio, struct swap_iocb **swap_plug); =20 /* linux/mm/swap_state.c */ -/* One swap address space for each 64M swap space */ -#define SWAP_ADDRESS_SPACE_SHIFT 14 -#define SWAP_ADDRESS_SPACE_PAGES (1 << SWAP_ADDRESS_SPACE_SHIFT) -#define SWAP_ADDRESS_SPACE_MASK (SWAP_ADDRESS_SPACE_PAGES - 1) extern struct address_space swap_space __ro_after_init; static inline struct address_space *swap_address_space(swp_entry_t entry) { diff --git a/mm/swapfile.c b/mm/swapfile.c index cbb7d4c0773d..6b3b35a7ddd9 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -3202,21 +3202,14 @@ static int setup_swap_map(struct swap_info_struct *= si, return 0; } =20 -#define SWAP_CLUSTER_INFO_COLS \ - DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info)) -#define SWAP_CLUSTER_SPACE_COLS \ - DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER) -#define SWAP_CLUSTER_COLS \ - max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS) - static struct swap_cluster_info *setup_clusters(struct swap_info_struct *s= i, union swap_header *swap_header, unsigned long maxpages) { unsigned long nr_clusters =3D DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); struct swap_cluster_info *cluster_info; - unsigned long i, j, idx; int err =3D -ENOMEM; + unsigned long i; =20 cluster_info =3D kvcalloc(nr_clusters, sizeof(*cluster_info), GFP_KERNEL); if (!cluster_info) @@ -3265,22 +3258,13 @@ static struct swap_cluster_info *setup_clusters(str= uct swap_info_struct *si, INIT_LIST_HEAD(&si->frag_clusters[i]); } =20 - /* - * Reduce false cache line sharing between cluster_info and - * sharing same address space. - */ - for (j =3D 0; j < SWAP_CLUSTER_COLS; j++) { - for (i =3D 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) { - struct swap_cluster_info *ci; - idx =3D i * SWAP_CLUSTER_COLS + j; - ci =3D cluster_info + idx; - if (idx >=3D nr_clusters) - continue; - if (ci->count) { - ci->flags =3D CLUSTER_FLAG_NONFULL; - list_add_tail(&ci->list, &si->nonfull_clusters[0]); - continue; - } + for (i =3D 0; i < nr_clusters; i++) { + struct swap_cluster_info *ci =3D &cluster_info[i]; + + if (ci->count) { + ci->flags =3D CLUSTER_FLAG_NONFULL; + list_add_tail(&ci->list, &si->nonfull_clusters[0]); + } else { ci->flags =3D CLUSTER_FLAG_FREE; list_add_tail(&ci->list, &si->free_clusters); } diff --git a/mm/zswap.c b/mm/zswap.c index 3dda4310099e..cba7077fda40 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -225,10 +225,13 @@ 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) - >> SWAP_ADDRESS_SPACE_SHIFT]; + >> ZSWAP_ADDRESS_SPACE_SHIFT]; } =20 #define zswap_pool_debug(msg, p) \ @@ -1674,7 +1677,7 @@ int zswap_swapon(int type, unsigned long nr_pages) struct xarray *trees, *tree; unsigned int nr, i; =20 - nr =3D DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES); + 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); --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f171.google.com (mail-pf1-f171.google.com [209.85.210.171]) (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 B3CF12C032E for ; Fri, 5 Sep 2025 19:15:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099729; cv=none; b=hcepvBTQFLe3qhYNdeGFlcKvm8vvrvYhSvI5UXIjqXp8yeM5GplK9xuYUm/EHfJoV5K7oDWLtwjzoxM0Toy5nOWNiDli6NI7dy3g6bwAkD0lmbG6OmshHXPELH1QyW52TOzpFIvsBgYfpT3wrVxAea7NKOCjSr6u6PO1SX1iUFI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099729; c=relaxed/simple; bh=9LB4pNawNDvYtH2LCllJebbjSodpn/+8Udl9dXMQuFE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=QdRlkS3TM0GuLas1wU0IGGk0TbxPjBrs99ZwnuP7sVroDPxIv7il5xPt52RN6uO3zs8yEzpRLwa4eXxXTz74lLfj9MU+d6vcAXnKDTjI5IK1d0ou6phjQc/zBPYcnAmyyltjccE0VLo7UbnQp/N0f42dN5egLfNGRu8oLFzKMrk= 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=KHSSkgs/; arc=none smtp.client-ip=209.85.210.171 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="KHSSkgs/" Received: by mail-pf1-f171.google.com with SMTP id d2e1a72fcca58-77238cb3cbbso2679528b3a.0 for ; Fri, 05 Sep 2025 12:15:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099727; x=1757704527; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=+lEkM5bIq6/Z03Z2MzIXOrrBa0ZEPgMosVL9NAQvMio=; b=KHSSkgs/HJFFSqcSrplnqURtRqeF9KwQqnYS7HtzrYAhHW5ouLKGyZZUvBVSJr7vTL juZYDb/HEU84T1dllyXFuUsBL+5sJKs0XrO48VdrhkIoxaRET06CVbhuHKWo8Km3ysc0 MCrsCdH1PSngXbfqA9h7XK8j87M1gOrmGyZPib42RWy2TP5QpLn0no4Otagg1GwsN9/t /FsqTVsa67JOIv28xSKTDd6ENPpUsVCGAaS+esZVH0S0hXYrcwQwS63Unhx5B5zRDOCi uf6DQByCFxDSn3RkWdOa99EoZv+m6rcAXDyPTbKg1XT7DnlKXs6Hjc2ksDK88JLgUk3w kXUw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099727; x=1757704527; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=+lEkM5bIq6/Z03Z2MzIXOrrBa0ZEPgMosVL9NAQvMio=; b=OSx314Xza30i49VbQlH1TmqYULUWPlqWpeacVLxxzgzwBXCdHiJzr3JvmfZxaTa6my stneHYGobOWhWZAuMdlCZmNc8i1EJO31po+Sz9qscWXbsEqXTRLj5r9h2mDIa9mTqdqr 1rVJubx/MRVmTGfVUq5LgXI/TqW+cbS/HVfJVQPZ7B54jhdgYHBUd3032ar39EGxt3xu lOYHbxca1pAXUOte8X907blfsBjAeP8OrBDG+gNeFNzC4Sic5VICZpIGGqSaDGy2z/69 EwfndZKyP0qeJT1MJIpqxTL9YSlnVNfaMDZmV5Jn75SbpDBfyD9dRSW/U+Pz4rQsY+Np kz4w== X-Forwarded-Encrypted: i=1; AJvYcCUWUbF1Xr7yWZl4HJ+wqW9DkbnyZXs1NG1zo4DChSSvXsvDcWDGt9jVSxsotDV3/RrcouGV+W5XFmufSfg=@vger.kernel.org X-Gm-Message-State: AOJu0YxdGGM4rGu2/L2s8rduniu30mDZD3LUhdp2yxOZR1zChTB05Tdb T+kqU0MF7O1US1X4ee0XyZZmfLA4fdYBrNyYwkVq0qWAvUFGwUJaARZ5 X-Gm-Gg: ASbGncuJ+yo+zVYkYLiqNgPmujygpkglFqeGELDIJMPaW98HGMa7XilkhflJpyRNEI3 t/shxcYspXiVEYJ2pZcvB9IWbSph0eoJZf2kQ1vQcU5j5bwgiBYBxC/nKonbG7aP5IXh4qHR0CY 00jMZXsQ9HLBjxq3RUBhyWcnS48O0MnOzpw9O3v/XfBMFtk9IFzQBB2WwWFZKVOFBlzs0PzwakY 5oU2DZopFGfZgEtkWtVKP2Gj4JS+XaOrpKq1u13QjM5UKGo1uRMLJPPGHJK2SYRjPnToEtDnf7w JsT5/7+w/g31J/L+0kGpI6fk1j/lyBQ/j3B5MmdMSIiLGR740jSXEZheWh4kWmTTfElup+WprMa n2eGtlVoskDh4Wu8JcvN6T+2qw6G1LkiPEwhgcJmcOFOANtwsj+22MpbGKw== X-Google-Smtp-Source: AGHT+IFX1AsNYufNSGbWrppi99g9MPF4m602yXU0boYUFaYnzpDBnO4BP28Q0xPFgPU4tjs3kQ4Hwg== X-Received: by 2002:a05:6a00:3c89:b0:772:5a3f:7cb3 with SMTP id d2e1a72fcca58-7725a3f8497mr23849253b3a.1.1757099726844; Fri, 05 Sep 2025 12:15:26 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.15.22 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:15:26 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 14/15] mm, swap: implement dynamic allocation of swap table Date: Sat, 6 Sep 2025 03:13:56 +0800 Message-ID: <20250905191357.78298-15-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song Now swap table is cluster based, which means free clusters can free its table since no one should modify it. There could be speculative readers, like swap cache look up, protect them by making them RCU protected. All swap table should be filled with null entries before free, so such readers will either see a NULL pointer or a null filled table being lazy freed. On allocation, allocate the table when a cluster is used by any order. This way, we can reduce the memory usage of large swap device significantly. This idea to dynamically release unused swap cluster data was initially suggested by Chris Li while proposing the cluster swap allocator and it suits the swap table idea very well. Co-developed-by: Chris Li Signed-off-by: Chris Li Signed-off-by: Kairui Song Acked-by: Chris Li Suggested-by: Chris Li --- mm/swap.h | 2 +- mm/swap_state.c | 9 +-- mm/swap_table.h | 37 ++++++++- mm/swapfile.c | 202 ++++++++++++++++++++++++++++++++++++++---------- 4 files changed, 199 insertions(+), 51 deletions(-) diff --git a/mm/swap.h b/mm/swap.h index c4fb28845d77..caff4fe30fc5 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -36,7 +36,7 @@ struct swap_cluster_info { u16 count; u8 flags; u8 order; - atomic_long_t *table; /* Swap table entries, see mm/swap_table.h */ + atomic_long_t __rcu *table; /* Swap table entries, see mm/swap_table.h */ struct list_head list; }; =20 diff --git a/mm/swap_state.c b/mm/swap_state.c index 209d5e9e8d90..dfe8f42fc309 100644 --- a/mm/swap_state.c +++ b/mm/swap_state.c @@ -92,8 +92,8 @@ struct folio *swap_cache_get_folio(swp_entry_t entry) struct folio *folio; =20 for (;;) { - swp_tb =3D __swap_table_get(__swap_entry_to_cluster(entry), - swp_cluster_offset(entry)); + swp_tb =3D swap_table_get(__swap_entry_to_cluster(entry), + swp_cluster_offset(entry)); if (!swp_tb_is_folio(swp_tb)) return NULL; folio =3D swp_tb_to_folio(swp_tb); @@ -116,11 +116,10 @@ void *swap_cache_get_shadow(swp_entry_t entry) { unsigned long swp_tb; =20 - swp_tb =3D __swap_table_get(__swap_entry_to_cluster(entry), - swp_cluster_offset(entry)); + 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); - return NULL; } =20 diff --git a/mm/swap_table.h b/mm/swap_table.h index e1f7cc009701..52254e455304 100644 --- a/mm/swap_table.h +++ b/mm/swap_table.h @@ -2,8 +2,15 @@ #ifndef _MM_SWAP_TABLE_H #define _MM_SWAP_TABLE_H =20 +#include +#include #include "swap.h" =20 +/* A typical flat array in each cluster as swap table */ +struct swap_table { + atomic_long_t entries[SWAPFILE_CLUSTER]; +}; + /* * 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 @@ -76,22 +83,46 @@ static inline void *swp_tb_to_shadow(unsigned long swp_= tb) static inline void __swap_table_set(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); - atomic_long_set(&ci->table[off], swp_tb); + 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(&ci->table[off], swp_tb); + return atomic_long_xchg_relaxed(&table[off], swp_tb); } =20 static inline unsigned long __swap_table_get(struct swap_cluster_info *ci, unsigned int off) { + atomic_long_t *table; + VM_WARN_ON_ONCE(off >=3D SWAPFILE_CLUSTER); - return atomic_long_read(&ci->table[off]); + table =3D rcu_dereference_check(ci->table, lockdep_is_held(&ci->lock)); + + return atomic_long_read(&table[off]); +} + +static inline unsigned long swap_table_get(struct swap_cluster_info *ci, + unsigned int off) +{ + atomic_long_t *table; + unsigned long swp_tb; + + rcu_read_lock(); + table =3D rcu_dereference(ci->table); + swp_tb =3D table ? atomic_long_read(&table[off]) : null_to_swp_tb(); + rcu_read_unlock(); + + return swp_tb; } #endif diff --git a/mm/swapfile.c b/mm/swapfile.c index 6b3b35a7ddd9..49f93069faef 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -105,6 +105,8 @@ static DEFINE_SPINLOCK(swap_avail_lock); =20 struct swap_info_struct *swap_info[MAX_SWAPFILES]; =20 +static struct kmem_cache *swap_table_cachep; + static DEFINE_MUTEX(swapon_mutex); =20 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait); @@ -400,10 +402,17 @@ static inline bool cluster_is_discard(struct swap_clu= ster_info *info) return info->flags =3D=3D CLUSTER_FLAG_DISCARD; } =20 +static inline bool cluster_table_is_alloced(struct swap_cluster_info *ci) +{ + return rcu_dereference_protected(ci->table, lockdep_is_held(&ci->lock)); +} + static inline bool cluster_is_usable(struct swap_cluster_info *ci, int ord= er) { if (unlikely(ci->flags > CLUSTER_FLAG_USABLE)) return false; + if (!cluster_table_is_alloced(ci)) + return false; if (!order) return true; return cluster_is_empty(ci) || order =3D=3D ci->order; @@ -421,32 +430,98 @@ static inline unsigned int cluster_offset(struct swap= _info_struct *si, return cluster_index(si, ci) * SWAPFILE_CLUSTER; } =20 -static int swap_table_alloc_table(struct swap_cluster_info *ci) +static void swap_cluster_free_table(struct swap_cluster_info *ci) { - WARN_ON(ci->table); - ci->table =3D kzalloc(sizeof(unsigned long) * SWAPFILE_CLUSTER, GFP_KERNE= L); - if (!ci->table) - return -ENOMEM; - return 0; + unsigned int ci_off; + struct swap_table *table; + + /* Only empty cluster's table is allow to be freed */ + 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))); + table =3D (void *)rcu_dereference_protected(ci->table, true); + rcu_assign_pointer(ci->table, NULL); + + kmem_cache_free(swap_table_cachep, table); } =20 -static void swap_cluster_free_table(struct swap_cluster_info *ci) +/* + * Allocate a swap table may need to sleep, which leads to migration, + * so attempt an atomic allocation first then fallback and handle + * potential race. + */ +static struct swap_cluster_info * +swap_cluster_alloc_table(struct swap_info_struct *si, + struct swap_cluster_info *ci, + int order) { - unsigned int ci_off; - unsigned long swp_tb; + struct swap_cluster_info *pcp_ci; + struct swap_table *table; + unsigned long offset; =20 - if (!ci->table) - return; + /* + * Only cluster isolation from the allocator does table allocation. + * Swap allocator uses a percpu cluster and holds the local lock. + */ + lockdep_assert_held(&ci->lock); + lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock); + + table =3D kmem_cache_zalloc(swap_table_cachep, + __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN); + if (table) { + rcu_assign_pointer(ci->table, table); + return ci; + } + + /* + * Try a sleep allocation. Each isolated free cluster may cause + * a sleep allocation, but there is a limited number of them, so + * the potential recursive allocation should be limited. + */ + spin_unlock(&ci->lock); + if (!(si->flags & SWP_SOLIDSTATE)) + spin_unlock(&si->global_cluster_lock); + local_unlock(&percpu_swap_cluster.lock); + table =3D kmem_cache_zalloc(swap_table_cachep, __GFP_HIGH | GFP_KERNEL); =20 - for (ci_off =3D 0; ci_off < SWAPFILE_CLUSTER; ci_off++) { - swp_tb =3D __swap_table_get(ci, ci_off); - if (!swp_tb_is_null(swp_tb)) - pr_err_once("swap: unclean swap space on swapoff: 0x%lx", - swp_tb); + local_lock(&percpu_swap_cluster.lock); + if (!(si->flags & SWP_SOLIDSTATE)) + spin_lock(&si->global_cluster_lock); + /* + * Back to atomic context. First, check if we migrated to a new + * CPU with a usable percpu cluster. If so, try using that instead. + * No need to check it for the spinning device, as swap is + * serialized by the global lock on them. + * + * The is_usable check is a bit rough, but ensures order 0 success. + */ + offset =3D this_cpu_read(percpu_swap_cluster.offset[order]); + if ((si->flags & SWP_SOLIDSTATE) && offset) { + pcp_ci =3D swap_cluster_lock(si, offset); + if (cluster_is_usable(pcp_ci, order) && + pcp_ci->count < SWAPFILE_CLUSTER) { + ci =3D pcp_ci; + goto free_table; + } + swap_cluster_unlock(pcp_ci); } =20 - kfree(ci->table); - ci->table =3D NULL; + if (!table) + return NULL; + + spin_lock(&ci->lock); + /* Nothing should have touched the dangling empty cluster. */ + if (WARN_ON_ONCE(cluster_table_is_alloced(ci))) + goto free_table; + + rcu_assign_pointer(ci->table, table); + return ci; + +free_table: + if (table) + kmem_cache_free(swap_table_cachep, table); + return ci; } =20 static void move_cluster(struct swap_info_struct *si, @@ -478,7 +553,7 @@ static void swap_cluster_schedule_discard(struct swap_i= nfo_struct *si, =20 static void __free_cluster(struct swap_info_struct *si, struct swap_cluste= r_info *ci) { - lockdep_assert_held(&ci->lock); + swap_cluster_free_table(ci); move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); ci->order =3D 0; } @@ -493,15 +568,11 @@ static void __free_cluster(struct swap_info_struct *s= i, struct swap_cluster_info * this returns NULL for an non-empty list. */ static struct swap_cluster_info *isolate_lock_cluster( - struct swap_info_struct *si, struct list_head *list) + struct swap_info_struct *si, struct list_head *list, int order) { - struct swap_cluster_info *ci, *ret =3D NULL; + struct swap_cluster_info *ci, *found =3D NULL; =20 spin_lock(&si->lock); - - if (unlikely(!(si->flags & SWP_WRITEOK))) - goto out; - list_for_each_entry(ci, list, list) { if (!spin_trylock(&ci->lock)) continue; @@ -513,13 +584,19 @@ static struct swap_cluster_info *isolate_lock_cluster( =20 list_del(&ci->list); ci->flags =3D CLUSTER_FLAG_NONE; - ret =3D ci; + found =3D ci; break; } -out: spin_unlock(&si->lock); =20 - return ret; + if (found && !cluster_table_is_alloced(found)) { + /* Only an empty free cluster's swap table can be freed. */ + VM_WARN_ON_ONCE(list !=3D &si->free_clusters); + VM_WARN_ON_ONCE(!cluster_is_empty(found)); + return swap_cluster_alloc_table(si, found, order); + } + + return found; } =20 /* @@ -652,17 +729,27 @@ static void relocate_cluster(struct swap_info_struct = *si, * added to free cluster list and its usage counter will be increased by 1. * Only used for initialization. */ -static void inc_cluster_info_page(struct swap_info_struct *si, +static int inc_cluster_info_page(struct swap_info_struct *si, struct swap_cluster_info *cluster_info, unsigned long page_nr) { unsigned long idx =3D page_nr / SWAPFILE_CLUSTER; + struct swap_table *table; struct swap_cluster_info *ci; =20 ci =3D cluster_info + idx; + if (!ci->table) { + table =3D kmem_cache_zalloc(swap_table_cachep, GFP_KERNEL); + if (!table) + return -ENOMEM; + rcu_assign_pointer(ci->table, table); + } + ci->count++; =20 VM_BUG_ON(ci->count > SWAPFILE_CLUSTER); VM_BUG_ON(ci->flags); + + return 0; } =20 static bool cluster_reclaim_range(struct swap_info_struct *si, @@ -844,7 +931,7 @@ static unsigned int alloc_swap_scan_list(struct swap_in= fo_struct *si, unsigned int found =3D SWAP_ENTRY_INVALID; =20 do { - struct swap_cluster_info *ci =3D isolate_lock_cluster(si, list); + struct swap_cluster_info *ci =3D isolate_lock_cluster(si, list, order); unsigned long offset; =20 if (!ci) @@ -869,7 +956,7 @@ static void swap_reclaim_full_clusters(struct swap_info= _struct *si, bool force) if (force) to_scan =3D swap_usage_in_pages(si) / SWAPFILE_CLUSTER; =20 - while ((ci =3D isolate_lock_cluster(si, &si->full_clusters))) { + while ((ci =3D isolate_lock_cluster(si, &si->full_clusters, 0))) { offset =3D cluster_offset(si, ci); end =3D min(si->max, offset + SWAPFILE_CLUSTER); to_scan--; @@ -1017,6 +1104,7 @@ static unsigned long cluster_alloc_swap_entry(struct = swap_info_struct *si, int o done: if (!(si->flags & SWP_SOLIDSTATE)) spin_unlock(&si->global_cluster_lock); + return found; } =20 @@ -1884,7 +1972,13 @@ swp_entry_t get_swap_page_of_type(int type) /* This is called for allocating swap entry, not cache */ if (get_swap_device_info(si)) { if (si->flags & SWP_WRITEOK) { + /* + * Grab the local lock to be complaint + * with swap table allocation. + */ + local_lock(&percpu_swap_cluster.lock); offset =3D cluster_alloc_swap_entry(si, 0, 1); + local_unlock(&percpu_swap_cluster.lock); if (offset) { entry =3D swp_entry(si->type, offset); atomic_long_dec(&nr_swap_pages); @@ -2677,12 +2771,21 @@ static void wait_for_allocation(struct swap_info_st= ruct *si) static void free_cluster_info(struct swap_cluster_info *cluster_info, unsigned long maxpages) { + struct swap_cluster_info *ci; int i, nr_clusters =3D DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); =20 if (!cluster_info) return; - for (i =3D 0; i < nr_clusters; i++) - swap_cluster_free_table(&cluster_info[i]); + for (i =3D 0; i < nr_clusters; i++) { + ci =3D cluster_info + i; + /* Cluster with bad marks count will have a remaining table */ + spin_lock(&ci->lock); + if (rcu_dereference_protected(ci->table, true)) { + ci->count =3D 0; + swap_cluster_free_table(ci); + } + spin_unlock(&ci->lock); + } kvfree(cluster_info); } =20 @@ -2718,6 +2821,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) struct address_space *mapping; struct inode *inode; struct filename *pathname; + unsigned int maxpages; int err, found =3D 0; =20 if (!capable(CAP_SYS_ADMIN)) @@ -2824,8 +2928,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) p->swap_map =3D NULL; zeromap =3D p->zeromap; p->zeromap =3D NULL; + maxpages =3D p->max; cluster_info =3D p->cluster_info; - free_cluster_info(cluster_info, p->max); p->max =3D 0; p->cluster_info =3D NULL; spin_unlock(&p->lock); @@ -2837,6 +2941,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) p->global_cluster =3D NULL; vfree(swap_map); kvfree(zeromap); + free_cluster_info(cluster_info, maxpages); /* Destroy swap account information */ swap_cgroup_swapoff(p->type); =20 @@ -3215,11 +3320,8 @@ static struct swap_cluster_info *setup_clusters(stru= ct swap_info_struct *si, if (!cluster_info) goto err; =20 - for (i =3D 0; i < nr_clusters; i++) { + for (i =3D 0; i < nr_clusters; i++) spin_lock_init(&cluster_info[i].lock); - if (swap_table_alloc_table(&cluster_info[i])) - goto err_free; - } =20 if (!(si->flags & SWP_SOLIDSTATE)) { si->global_cluster =3D kmalloc(sizeof(*si->global_cluster), @@ -3238,16 +3340,23 @@ static struct swap_cluster_info *setup_clusters(str= uct swap_info_struct *si, * See setup_swap_map(): header page, bad pages, * and the EOF part of the last cluster. */ - inc_cluster_info_page(si, cluster_info, 0); + err =3D inc_cluster_info_page(si, cluster_info, 0); + if (err) + goto err; for (i =3D 0; i < swap_header->info.nr_badpages; i++) { unsigned int page_nr =3D swap_header->info.badpages[i]; =20 if (page_nr >=3D maxpages) continue; - inc_cluster_info_page(si, cluster_info, page_nr); + err =3D inc_cluster_info_page(si, cluster_info, page_nr); + if (err) + goto err; + } + for (i =3D maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) { + err =3D inc_cluster_info_page(si, cluster_info, i); + if (err) + goto err; } - for (i =3D maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) - inc_cluster_info_page(si, cluster_info, i); =20 INIT_LIST_HEAD(&si->free_clusters); INIT_LIST_HEAD(&si->full_clusters); @@ -3961,6 +4070,15 @@ static int __init swapfile_init(void) =20 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. + */ + swap_table_cachep =3D kmem_cache_create("swap_table", + sizeof(struct swap_table), + 0, SLAB_PANIC | SLAB_TYPESAFE_BY_RCU, NULL); + #ifdef CONFIG_MIGRATION if (swapfile_maximum_size >=3D (1UL << SWP_MIG_TOTAL_BITS)) swap_migration_ad_supported =3D true; --=20 2.51.0 From nobody Wed Sep 10 05:31:00 2025 Received: from mail-pf1-f171.google.com (mail-pf1-f171.google.com [209.85.210.171]) (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 A96892C11D7 for ; Fri, 5 Sep 2025 19:15:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099734; cv=none; b=sUvgfI0WQkRjCKFYtQWjxTcqUIoXzfZ35inZ0vuve676jaVh/3Y2kAzi+wZ3X7bn104fUUJ4GTa7C5MlZXv868apd8Eo0lICM9Hy3wP1RIbrvKNrM+RZ/DsA02GlyCo57I1QBugsKefTn519jlK1RWF9kgJbGFr2ReEvGzzDFC4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1757099734; c=relaxed/simple; bh=NGwrA9wyWoMs2ccSuQdy7uAj7hR7kS65CEQYH5Ncug4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Pq6+G5W0PXzWzz68GxYmXg9mxTWbmA1WtnltwQD5IY1K/AYHKedbCMoMUoN6PO2gyq/kMPM9T+6+O+m04ObX0j5TzDCIcBxSE6xANBjYLwPoND1PvEvBP7BzDiV8u9rtiZ+nVs/ebUVprE0j8jdn6V0S6EWxeVkMkb+oez1puF8= 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=TrVCZyET; arc=none smtp.client-ip=209.85.210.171 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="TrVCZyET" Received: by mail-pf1-f171.google.com with SMTP id d2e1a72fcca58-77256e75eacso2307540b3a.0 for ; Fri, 05 Sep 2025 12:15:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1757099732; x=1757704532; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=e9tXoC30u8cptZoeY7RVmNYN+rcCikIe4hnTmAJUGE4=; b=TrVCZyETTQoxt7geUAVsxxKF7gQ7xVxwxo5osgwrswycibhMo4gesANTQUNtLHcvqS eIYyc8iPx8d/vRz968FJ4aHla/wZm0J5QrhBZRrQ2+tZediv1LyU/jj5So+e5QoEEALs T7Rs/E3/Wm5OBaXwJoL9BErMGQVQ5tSLfHy5/srOdar8UYpaynujuJ85vPQH5ITEkO41 qupzPdjbaB47nwnKz3cgiQfyPq6HMBRFEUk7MRY5tGKU6AsV+vLBUaW8r+3GQIWK7Dyl m6MZCM+Sk/0c4348A6yDLoupLra9k9g/LaRyaptpipjmOHvlpA7Qz+9mxPjzMIwupAQT XVvQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1757099732; x=1757704532; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=e9tXoC30u8cptZoeY7RVmNYN+rcCikIe4hnTmAJUGE4=; b=acQNu4KGMCzQ0kuTyVPUH0nAcoDAfMGckmKeYAhH1OyPdfKwfBRCNtcFdf7QocGPQR U5cicKNb5uRgOi4vlSFMaGjTE3xRJB5aN0RGXSSzpHkdZ0djhS6cfeuzu+lkrm+qjcM2 GOoZ8A1D7j3EvRxIzX3kr1qeibZs/V8ckUCcG1oJBn8dUBnNEALnJsqaVY8yp5mSy7kf qUKM38gv0VnPcJDtPwcZoBWANkPEPcOPjxMkZH4tSfZ1OsTWWxCg4FPcrCKSpwXqlCeM AfaWMiOzwRie2XANcO3bd+2/6gzWtuOreWARxafu8taxZaP3Z5YMhdC4h8lpJDIuEDH/ RmVg== X-Forwarded-Encrypted: i=1; AJvYcCX/Phf5Nn7qZPzq3i9RBXN0OjCAPSt1pbN1cIu0p9i0i4JMdw8+b1Aev/YWP3EGU5ZmQr+4SzIq4mvY4pc=@vger.kernel.org X-Gm-Message-State: AOJu0Ywz5Ab8icQ5mbmjK+Q8bH0YNceEasKrARWx6zfBRoY1I09Ia5qj hrojxCM/+Duuurpp3yKOPwI6dynX5Q8CCfnQj6Jr1mSXTtCXoSk5PoTC X-Gm-Gg: ASbGncuTSmOGam70Ddt2YDudjn9ZXuYqbnmWeI+g3ySCtYaEr4Hzi93Uq5IvNrm+i4Q dgCJyX0UcpWrBlAeoLYYgrpObn3l/QRT2COtfL9935Sytwn5p65r621RUsbOaEyysql5YkeXvkt M6eqfKPr9OhYrLW12v0OjmdOZzmLEhFytNSgft7Y7h2sdu/guPb4b3+DBDtAIAt9B04ZVQ9YKjK 2HbQorLd7v2taKho/hP8H1LFgDt7HetdD0Fu0NmFcKKiMCHxoZIIzMdYOtbUGNvS0puaN/ssm31 gLZqaT8SUYLx6bcHcz8KEskiZAAeXnpzIPHAX3lnssJKHBj7qaGzkFVTNjs4VKbTB+8Dr8jJcgR GahX7dDSrZx0gxooqfjHOAWl7pnaeeHx6yQEjXQt3yKZ+QCs= X-Google-Smtp-Source: AGHT+IHA4LeWAP5Z6VrdlIQxPr/w7slkyPGU20hMWH4nHy3XJM2DXNYOG9uwEY4Srtf0PoS266Phcw== X-Received: by 2002:a05:6a20:a109:b0:24f:2251:84f9 with SMTP id adf61e73a8af0-24f2252f7c0mr5988998637.15.1757099731766; Fri, 05 Sep 2025 12:15:31 -0700 (PDT) Received: from KASONG-MC4.tencent.com ([101.32.222.185]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-77256a0f916sm15871442b3a.63.2025.09.05.12.15.27 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 05 Sep 2025 12:15:31 -0700 (PDT) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Matthew Wilcox , Hugh Dickins , Chris Li , Barry Song , Baoquan He , Nhat Pham , Kemeng Shi , Baolin Wang , Ying Huang , Johannes Weiner , David Hildenbrand , Yosry Ahmed , Lorenzo Stoakes , Zi Yan , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 15/15] mm, swap: use a single page for swap table when the size fits Date: Sat, 6 Sep 2025 03:13:57 +0800 Message-ID: <20250905191357.78298-16-ryncsn@gmail.com> X-Mailer: git-send-email 2.51.0 In-Reply-To: <20250905191357.78298-1-ryncsn@gmail.com> References: <20250905191357.78298-1-ryncsn@gmail.com> Reply-To: Kairui Song 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" From: Kairui Song We have a cluster size of 512 slots. Each slot consumes 8 bytes in swap table so the swap table size of each cluster is exactly one page (4K). If that condition is true, allocate one page direct and disable the slab cache to reduce the memory usage of swap table and avoid fragmentation. Co-developed-by: Chris Li Signed-off-by: Chris Li Signed-off-by: Kairui Song Acked-by: Chris Li Suggested-by: Chris Li --- mm/swap_table.h | 2 ++ mm/swapfile.c | 50 ++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/mm/swap_table.h b/mm/swap_table.h index 52254e455304..ea244a57a5b7 100644 --- a/mm/swap_table.h +++ b/mm/swap_table.h @@ -11,6 +11,8 @@ struct swap_table { atomic_long_t entries[SWAPFILE_CLUSTER]; }; =20 +#define SWP_TABLE_USE_PAGE (sizeof(struct swap_table) =3D=3D PAGE_SIZE) + /* * 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 diff --git a/mm/swapfile.c b/mm/swapfile.c index 49f93069faef..ab6e877b0644 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -430,6 +430,38 @@ static inline unsigned int cluster_offset(struct swap_= info_struct *si, return cluster_index(si, ci) * SWAPFILE_CLUSTER; } =20 +static struct swap_table *swap_table_alloc(gfp_t gfp) +{ + struct folio *folio; + + if (!SWP_TABLE_USE_PAGE) + return kmem_cache_zalloc(swap_table_cachep, gfp); + + folio =3D folio_alloc(gfp | __GFP_ZERO, 0); + if (folio) + return folio_address(folio); + return NULL; +} + +static void swap_table_free_folio_rcu_cb(struct rcu_head *head) +{ + struct folio *folio; + + folio =3D page_folio(container_of(head, struct page, rcu_head)); + folio_put(folio); +} + +static void swap_table_free(struct swap_table *table) +{ + if (!SWP_TABLE_USE_PAGE) { + kmem_cache_free(swap_table_cachep, table); + return; + } + + call_rcu(&(folio_page(virt_to_folio(table), 0)->rcu_head), + swap_table_free_folio_rcu_cb); +} + static void swap_cluster_free_table(struct swap_cluster_info *ci) { unsigned int ci_off; @@ -443,7 +475,7 @@ static void swap_cluster_free_table(struct swap_cluster= _info *ci) table =3D (void *)rcu_dereference_protected(ci->table, true); rcu_assign_pointer(ci->table, NULL); =20 - kmem_cache_free(swap_table_cachep, table); + swap_table_free(table); } =20 /* @@ -467,8 +499,7 @@ swap_cluster_alloc_table(struct swap_info_struct *si, lockdep_assert_held(&ci->lock); lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock); =20 - table =3D kmem_cache_zalloc(swap_table_cachep, - __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN); + table =3D swap_table_alloc(__GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN); if (table) { rcu_assign_pointer(ci->table, table); return ci; @@ -483,7 +514,7 @@ swap_cluster_alloc_table(struct swap_info_struct *si, if (!(si->flags & SWP_SOLIDSTATE)) spin_unlock(&si->global_cluster_lock); local_unlock(&percpu_swap_cluster.lock); - table =3D kmem_cache_zalloc(swap_table_cachep, __GFP_HIGH | GFP_KERNEL); + table =3D swap_table_alloc(__GFP_HIGH | GFP_KERNEL); =20 local_lock(&percpu_swap_cluster.lock); if (!(si->flags & SWP_SOLIDSTATE)) @@ -520,7 +551,7 @@ swap_cluster_alloc_table(struct swap_info_struct *si, =20 free_table: if (table) - kmem_cache_free(swap_table_cachep, table); + swap_table_free(table); return ci; } =20 @@ -738,7 +769,7 @@ static int inc_cluster_info_page(struct swap_info_struc= t *si, =20 ci =3D cluster_info + idx; if (!ci->table) { - table =3D kmem_cache_zalloc(swap_table_cachep, GFP_KERNEL); + table =3D swap_table_alloc(GFP_KERNEL); if (!table) return -ENOMEM; rcu_assign_pointer(ci->table, table); @@ -4075,9 +4106,10 @@ static int __init swapfile_init(void) * only, and all swap cache readers (swap_cache_*) verifies * the content before use. So it's safe to use RCU slab here. */ - swap_table_cachep =3D kmem_cache_create("swap_table", - sizeof(struct swap_table), - 0, SLAB_PANIC | SLAB_TYPESAFE_BY_RCU, NULL); + if (!SWP_TABLE_USE_PAGE) + swap_table_cachep =3D kmem_cache_create("swap_table", + sizeof(struct swap_table), + 0, SLAB_PANIC | SLAB_TYPESAFE_BY_RCU, NULL); =20 #ifdef CONFIG_MIGRATION if (swapfile_maximum_size >=3D (1UL << SWP_MIG_TOTAL_BITS)) --=20 2.51.0