From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f172.google.com (mail-pl1-f172.google.com [209.85.214.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AC8B31CCED2 for ; Tue, 24 Dec 2024 14:39:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051174; cv=none; b=krLPjTc1pCpcvU//Xz1x1hAv2WnqvS6MJa6qQHZ6MoXyP3T3wzAzAY+rUe//novGDNuX9IoHd4iNqpmV1LtckwU+XaoKWUXieqHQr5NGMg9ObxL2BKMdxUzJoZfc/OO7e+zjJLPNcWXe2suWkNjgnOcCGRkn6SAobEDGT9GJtMU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051174; c=relaxed/simple; bh=0zwLEl1IX5lfCSiyPNTsbs+vpbZuqKYgJ688EZCFVa0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=oeAbpvw+ay6wiloYgoMLqpuM3KeSYSLol+/lAWnZz0Lwsv9p1Pa8AWY3As8LxywNwlQ0/faI5CHtGTliDL/7f3dCcVmd2I+CDVNWiwJ0K6ube/to7pgn3myUYWvDKSK+Oyvh8qJK+5BNc8wGwxw+FovHcqlNyZuTz+JhlRSkUWo= 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=G/CAbwb3; arc=none smtp.client-ip=209.85.214.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="G/CAbwb3" Received: by mail-pl1-f172.google.com with SMTP id d9443c01a7336-2165cb60719so54434365ad.0 for ; Tue, 24 Dec 2024 06:39:32 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051172; x=1735655972; 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=ByQEC8FsvBO2uOH/tvc24OCSxXwsTLkJSMXrTAjB9ew=; b=G/CAbwb31STjfDzPruH1pnTubhRcfSSLZRMFNvAUEqp5AV0s3rwUFQz0qFPWsssnbj TiQJTbIucFP+vJJMIVme5CM7J5O6UORkc9EHVdSm73XWQ7AMHcL3pWObjFzztYMaFfky cRayHGU34vYJr/bBIDMfUnSdGYi+60LBpqM/CqGwn61m9frC9gg8awTRjbhJwYnpj6BP vxORAeTbvWALQIjc6YNiDq0fz/uVbLM8xecT01Q9Oxq/whdRdHW7S5f35R/5ynUlH2Fd irhihbvZudhmFz4HbYAYL4yMcofpwgmSRn/EJiuw8wP0aThxBFpo+Vq04kRXPYSm3pc3 S1Bg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051172; x=1735655972; 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=ByQEC8FsvBO2uOH/tvc24OCSxXwsTLkJSMXrTAjB9ew=; b=CWYsxU7A38wcR7BsqKgoNOfsDi77Om1Tqk7uh4BN/QF9KoPH6bHzr+BwaWOwZzj0OY WHTgzSdJkNl/2lfPdRHzcqk9HQ1Nw310OBAZlVUgStoFFU8yiRXc1739CEIAjgPNvLxn 5qACr1NR8Jy76Bo5MO7APJjgZ8R6oyk42OdY/8a5byLHJoikwerbL4XKlqVTXOvony4r KlnZec7q7izeLWVrQK1yeZepr7Au7AMN4mP6tgvImWmwwsJxLGSGiA41YcfuGUcO3aO8 a3Cl/islAlU4xVyFXMWtvNyDurksf/FKBvAmTH7AJ5VUvgA3NTUsuXyc2oeHbQPVo/Si WESw== X-Forwarded-Encrypted: i=1; AJvYcCUYDNnVagy4JTulwA4g5RK6FrS19i993SsjWfpKuXCLAvCRScidTX8gl0U24O1VwTJog3flrnCU0zBgeaY=@vger.kernel.org X-Gm-Message-State: AOJu0Yygu7fpNRqBBuT9XnbBERB41mtT0U2joGY1ol4DfEkqLX0KDq1X /A7W436sJN+1onypVIgm/7jqCZjCn1NJNiQjfJSoiv8K3yOUAkTy X-Gm-Gg: ASbGnctTbhKao80p/fhurhOD8HytHf0bQQb4a+wd8elXz4OX4UHU6GzYvj3tH3FTmuy 8jOXbbZ9mBEfcRFXiIf+E4qB8ySiBv6dzlIrrd+EFRDETSvxiNzMe7Li9YVuSyn8zvLZ8XsN9SV 3IVFAsaXt23C1z7jTQUMwM3v3BeHM/V8/UoTKkZcf7E88er/gccErFTr2YnRnsuTtSByRAHUIv9 Ab11RCgzS6SayKSVOzAZzGxx0xWQ/sisKM0WtJhp0oixwztarNky2UyPySNP+rlCdBefLaMUXQK 7Q== X-Google-Smtp-Source: AGHT+IERM809iT3lGHUyfSmwzz85A7RBdI6+sHZNonAv7QDefMy2AtxZq5MCVgChbGhf0YMVvbHZ6g== X-Received: by 2002:a17:902:c407:b0:216:50c6:6b42 with SMTP id d9443c01a7336-219e6f25ddbmr196266805ad.56.1735051171988; Tue, 24 Dec 2024 06:39:31 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.28 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:39:31 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 01/13] mm, swap: minor clean up for swap entry allocation Date: Tue, 24 Dec 2024 22:37:59 +0800 Message-ID: <20241224143811.33462-2-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 Direct reclaim can skip the whole folio after reclaimed a set of folio based slots. Also simplify the code for allocation, reduce indention. Signed-off-by: Kairui Song Suggested-by: Chris Li --- mm/swapfile.c | 59 +++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index b0a9071cfe1d..f8002f110104 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -604,23 +604,28 @@ static bool cluster_reclaim_range(struct swap_info_st= ruct *si, unsigned long start, unsigned long end) { unsigned char *map =3D si->swap_map; - unsigned long offset; + unsigned long offset =3D start; + int nr_reclaim; =20 spin_unlock(&ci->lock); spin_unlock(&si->lock); =20 - for (offset =3D start; offset < end; offset++) { + do { switch (READ_ONCE(map[offset])) { case 0: - continue; + offset++; + break; case SWAP_HAS_CACHE: - if (__try_to_reclaim_swap(si, offset, TTRS_ANYWAY | TTRS_DIRECT) > 0) - continue; - goto out; + nr_reclaim =3D __try_to_reclaim_swap(si, offset, TTRS_ANYWAY | TTRS_DIR= ECT); + if (nr_reclaim > 0) + offset +=3D nr_reclaim; + else + goto out; + break; default: goto out; } - } + } while (offset < end); out: spin_lock(&si->lock); spin_lock(&ci->lock); @@ -838,35 +843,30 @@ static unsigned long cluster_alloc_swap_entry(struct = swap_info_struct *si, int o &found, order, usage); frags++; if (found) - break; + goto done; } =20 - if (!found) { + /* + * Nonfull clusters are moved to frag tail if we reached + * here, count them too, don't over scan the frag list. + */ + while (frags < si->frag_cluster_nr[order]) { + ci =3D list_first_entry(&si->frag_clusters[order], + struct swap_cluster_info, list); /* - * Nonfull clusters are moved to frag tail if we reached - * here, count them too, don't over scan the frag list. + * Rotate the frag list to iterate, they were all failing + * high order allocation or moved here due to per-CPU usage, + * this help keeping usable cluster ahead. */ - while (frags < si->frag_cluster_nr[order]) { - ci =3D list_first_entry(&si->frag_clusters[order], - struct swap_cluster_info, list); - /* - * Rotate the frag list to iterate, they were all failing - * high order allocation or moved here due to per-CPU usage, - * this help keeping usable cluster ahead. - */ - list_move_tail(&ci->list, &si->frag_clusters[order]); - offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, order, usage); - frags++; - if (found) - break; - } + list_move_tail(&ci->list, &si->frag_clusters[order]); + offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), + &found, order, usage); + frags++; + if (found) + goto done; } } =20 - if (found) - goto done; - if (!list_empty(&si->discard_clusters)) { /* * we don't have free cluster but have some clusters in @@ -904,7 +904,6 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o goto done; } } - done: cluster->next[order] =3D offset; return found; --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f182.google.com (mail-pl1-f182.google.com [209.85.214.182]) (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 5E88E1D9329 for ; Tue, 24 Dec 2024 14:39:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051178; cv=none; b=pirI69DKG+GPD88FUjQq4KRR9GS/6q/m9gD4oU1Qv84yF/QeJ5yz+/xeKfHTaKor7wPpVB/xc0fa9z0eGGwmc35o8Dk8AgCCkfxgT2DowSn/3XAzUkwuERIKcjXDST88RYtTdypMSAJv+QuCCovOaI8GWd1NrmqFZ7Txr1KTWLc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051178; c=relaxed/simple; bh=d2i28bIgwgBE/CLwLqgga3NoAc+ItA80i0MhwxzUBek=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=iInD71HnTRStSYwKTYMhPAzQ6O1ashjXpkqN3VpJv4wjNTzqG1V1OS79VhNr9j462WHKCGEeP1s8PfHn0I07xMF4Y9eYDBwFgbYeBNHBT3YxeAgEVjjU03Ju9u0LLnBAgm5AYudQItql7+XoeG6Opvq/PsAncbhPNDuMpqIQiKY= 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=D9h687YR; arc=none smtp.client-ip=209.85.214.182 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="D9h687YR" Received: by mail-pl1-f182.google.com with SMTP id d9443c01a7336-21670dce0a7so69351625ad.1 for ; Tue, 24 Dec 2024 06:39:37 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051176; x=1735655976; 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=rZtcJl9C6ncR1PQN3HhaQn7BWhIvEYupFW/4U59A+e4=; b=D9h687YRkv3ZoQZC7OWEvNlo9VyCZoBi3ac4tIK4CtLlgyza0ev1F2VHNO0+zM/gvQ iQYS0k9nNJIRa4cOUb/BBJYMCU0Gz9Qtrz0edAY7Fg9HAwBHP40QavP3kACpV9v/gwj7 NFKUfdJkbwN+aIpdR8iEQHIiKea/axhNHjoIVajH2s+0eKTHJV49+wgFCea3ZNkev4g2 m9mg4ugbnP42Jy6uWezmdy+Vg5XU/+3iQ0r8dUR+PNCYB39Y3qaZvXD+/xrbKV8qmHh6 xffRPZb5+a21zwOicOkk8uqVRAP+JZ6bdCIO4IPdhLzizotbMIaCKV/+VH/1/Jf/KOVi ozYQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051176; x=1735655976; 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=rZtcJl9C6ncR1PQN3HhaQn7BWhIvEYupFW/4U59A+e4=; b=me82zR+/b5b6yqG47znNmy9TLPICU8Mn5rWCLL3+vABakkJ3lTQlmKM1T15C2S3whK x6a4XIlck1GBnugdmW/teOwIcdo2n9rivi/rKGHkwhs9tbHFDNvonlxM/Jtr4i13bQPx IoFxx8MxEnSRFDWzbOhrOk0aleqB6F1Qzy7h9Bu74yIE0SwzeVraN+oBY8lreGV99ZoN MSMN9C38hOm+8gSvBJG9lGqv9hzlMZzo/1R09RWQOduShEg3WuEE4HBXXb1ocaBV1qsH z9nAeoguk0Fez6ZzSijPznEneAry3N6n3XXvSws3DJ+3oAk1/iU7VEQ/Y3mcaCybZuUC 9Gzw== X-Forwarded-Encrypted: i=1; AJvYcCUQ/y8PDeiLZTtQ0u5fDWeh9uD9FcO9lgWl8i8JMXKdL9skhnY9omYFSQ4F0dPL420eUNNBG8R44xYSjLQ=@vger.kernel.org X-Gm-Message-State: AOJu0YxvJEaUR6j3oSPiv2NSHl7/JXSolkDqFPOIy64sYiQlX84V76xX Kw6C37+9OBucc8lol17DJshYgJte25s67vHQqUscUh++ILD+UN+g X-Gm-Gg: ASbGnctzwnHilznMmQAEjQdjLainMjI8+Ncg6yoIeATWHmavOMeEzD1x8GLJe5/J0bq D2HLD/Ixz++yF4G+GeLsP6rFzn1dlPHGQ9EuSJU+KEHQprtyxmTCYjDU7CkSmg82280v0c0rRp6 trFDmufBsoWQi/o8WkD0xfCvnqHTxxzvZTLWkcyvQTW/ba8/JuWhTahT7KDbVXeIOmAtN4Rg33d wzWIIormsRfIjuMHywH5zJLqncKYqJWQysvQZo6iBYMkQNBVAVaB0KPortKZQL9COzDEXd6o5Vy sA== X-Google-Smtp-Source: AGHT+IEkDx4n/weETtq0G9ZPhvCOgy2IrUiCp+3qPSdSRiNgKT1LkatuidUbaG44s3+jtvqlnVPqTA== X-Received: by 2002:a17:902:d4c4:b0:211:ce91:63ea with SMTP id d9443c01a7336-219e6ea1accmr181270775ad.15.1735051176547; Tue, 24 Dec 2024 06:39:36 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.32 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:39:36 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 02/13] mm, swap: fold swap_info_get_cont in the only caller Date: Tue, 24 Dec 2024 22:38:00 +0800 Message-ID: <20241224143811.33462-3-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 name of the function is confusing, and the code is much easier to follow after folding, also rename the confusing naming "p" to more meaningful "si". Signed-off-by: Kairui Song Suggested-by: Chris Li --- mm/swapfile.c | 39 +++++++++++++++------------------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index f8002f110104..574059158627 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -1375,22 +1375,6 @@ static struct swap_info_struct *_swap_info_get(swp_e= ntry_t entry) return NULL; } =20 -static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry, - struct swap_info_struct *q) -{ - struct swap_info_struct *p; - - p =3D _swap_info_get(entry); - - if (p !=3D q) { - if (q !=3D NULL) - spin_unlock(&q->lock); - if (p !=3D NULL) - spin_lock(&p->lock); - } - return p; -} - static unsigned char __swap_entry_free_locked(struct swap_info_struct *si, unsigned long offset, unsigned char usage) @@ -1687,14 +1671,14 @@ static int swp_entry_cmp(const void *ent1, const vo= id *ent2) =20 void swapcache_free_entries(swp_entry_t *entries, int n) { - struct swap_info_struct *p, *prev; + struct swap_info_struct *si, *prev; int i; =20 if (n <=3D 0) return; =20 prev =3D NULL; - p =3D NULL; + si =3D NULL; =20 /* * Sort swap entries by swap device, so each lock is only taken once. @@ -1704,13 +1688,20 @@ void swapcache_free_entries(swp_entry_t *entries, i= nt n) if (nr_swapfiles > 1) sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL); for (i =3D 0; i < n; ++i) { - p =3D swap_info_get_cont(entries[i], prev); - if (p) - swap_entry_range_free(p, entries[i], 1); - prev =3D p; + si =3D _swap_info_get(entries[i]); + + if (si !=3D prev) { + if (prev !=3D NULL) + spin_unlock(&prev->lock); + if (si !=3D NULL) + spin_lock(&si->lock); + } + if (si) + swap_entry_range_free(si, entries[i], 1); + prev =3D si; } - if (p) - spin_unlock(&p->lock); + if (si) + spin_unlock(&si->lock); } =20 int __swap_count(swp_entry_t entry) --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f172.google.com (mail-pl1-f172.google.com [209.85.214.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AA9B61D9A62 for ; Tue, 24 Dec 2024 14:39:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051183; cv=none; b=LZO7Y2Po9daNjSgmLmtxlIb54G9jrEKOk/wo7IvLQw40rC0/+5BhMs9lV90P4PAzcnOVNXD17Zx5Sz1MkL8bYPS24A469QTx5DkiSN3FQ7tYxkZXECOC/brfmxXEs9eGAMtcKnihn8FOeexdx00ipi6AjwLfenINaSkcfgxFxCc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051183; c=relaxed/simple; bh=3Lfnz2+vuuz8Svu2Veu5BJVNFuY1l6suJncnYKa52D0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=NP/rZu2Zso0sm9Jrpigy3hYkkWX8ocqcEaiVTs2TvKiuKuXtRmvl7NIEGOOwHUNRBY9iX6GYZOqUnAmMCDPGDaXEqAIKsiRgE1OGHJk/eI3ooZ8Q6y5pyKc2IJIVVN/P/OhDEYpkRV/K6md2PVhopKkzCCaaiUPBH1DrKkM+N2k= 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=RA8mOBL6; arc=none smtp.client-ip=209.85.214.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="RA8mOBL6" Received: by mail-pl1-f172.google.com with SMTP id d9443c01a7336-21680814d42so49321865ad.2 for ; Tue, 24 Dec 2024 06:39:41 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051181; x=1735655981; 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=7vSxPva/IzAffauQhXhMBUxAGj3ydaL87rJATVq3axg=; b=RA8mOBL6NBtTyBiapUFnrRqtYnnisJSRvnOmSbvSDPzkZiYfIJB7wT4MbIVQHIe1kI c2sCeUYpPvv68fhglNGIyPqR36ndOao9OVMS/6V6otvC4IMXkHJCB/n4FQDw4SoWtkTA 8ZP+BYfJwnNLgdMqIXkr97iKXg7Qz2J68GXauZuuFYcgN0EmH9ndct4J9fCtgyAZzZxI zJrBvU7JnsjFXJnzhgKeihJK7k7ZH6LIpchB+PMgXX5h0Ach+S1tHe3XIKwRfgGDKMma OqTrGERc6mQk53vjeVzryQLzpqMlJmuozvfrh2N/kRQeZBvinMqsG3LKC3eU9D8rlxY1 jAvA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051181; x=1735655981; 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=7vSxPva/IzAffauQhXhMBUxAGj3ydaL87rJATVq3axg=; b=TdEPJLqFxApEfYAua1XrJRPC93P/toaPSSCKxXDKw4NL/JxX6kUzsgIPCYkBZRH9y1 yv/DcIR4sexDQOIv8xAR1+HiOJyZT0KRIdhdeGAd3gVxnht1Xi8OdQ27TnPox+Ek25ee dtiD82zsyiGPkY4Hsr8BMdo+vl+JHP5ObcLaLorfynZLqiJROFehimTQWdCaUaE4skgE Lb0dn0OBFtQ2WOWYFj567d3t9bIHeeRBIxo9CCuDwm2c8El9b9hJS/RNHo2BLXLS04I1 R0IGBv4WpRGNZxiBfZtkIXkFaeEVEg38xG2jRTLyH9zyDLpjSFTEiCU5VcjXLKK1sHCs M6nw== X-Forwarded-Encrypted: i=1; AJvYcCXP6Q/5ysVM+9KsZEg/4kvcMCqbeb5lZgmCyUvRH2wx3CTDGx8NogM96EqjnW6dLVVWUfDf7cYutN3XK6s=@vger.kernel.org X-Gm-Message-State: AOJu0YwdCHHbdNhCfal/oUwuj0rRKvekS8noymUuYoUT2cOx52iD30nu 8b3kFzGbL362MMr00hi49hj3zSo/nqemGsbC8TyXTsM1WyfDJWhj X-Gm-Gg: ASbGncvmoPoS8XobaaHxBJTGnpxefReLyWIsYfWtRCzFP5dN6BBe4Z55QQ0YiD8dVnM doZQGCqx39VcRQ9CRq+iP5LqMFmlchAkuVxYtQdSfNKk+LsOQ5Y/Mn6z3ACo4e8XtM0WXFHQPTT GnO9lJHrd9DWplFlNmgZDHLpRz32PGOl7xTcl4/W4RXuq5DvXi6eW6fKmz1t1ig/yfNIevebE3g 4u3UaLWkOsdXG40lRMh4U45dl6XCAdDkdtf0vGLINSnkZkGK580CO4fFJpWFOZRxhrlJKYnJSvZ 5w== X-Google-Smtp-Source: AGHT+IFUIbkJj2uiK0mi+sirzvJ+kxdlR40mR42wJ1gQTLR/qHCcG61l6wFzaFQioRKEUmA2LCan7A== X-Received: by 2002:a17:903:2442:b0:211:7156:4283 with SMTP id d9443c01a7336-219e70c0085mr249317255ad.43.1735051180901; Tue, 24 Dec 2024 06:39:40 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.36 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:39:40 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 03/13] mm, swap: remove old allocation path for HDD Date: Tue, 24 Dec 2024 22:38:01 +0800 Message-ID: <20241224143811.33462-4-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 are currently using different swap allocation algorithm for HDD and non-HDD. This leads to the existence of a different set of locks, and the code path is heavily bloated, causing difficulties for further optimization and maintenance. This commit removes all HDD swap allocation and related dead code, and uses the cluster allocation algorithm instead. The performance may drop temporarily, but this should be negligible: The main advantage of the legacy HDD allocation algorithm is that it tends to use continuous slots, but swap device gets fragmented quickly anyway, and the attempt to use continuous slots will fail easily. This commit also enables mTHP swap on HDD, which is expected to be beneficial, and following commits will adapt and optimize the cluster allocator for HDD. Suggested-by: Chris Li Suggested-by: "Huang, Ying" Signed-off-by: Kairui Song --- include/linux/swap.h | 3 - mm/swapfile.c | 235 ++----------------------------------------- 2 files changed, 9 insertions(+), 229 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 187715eec3cb..0c681aa5cb98 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -310,9 +310,6 @@ struct swap_info_struct { unsigned int highest_bit; /* index of last free in swap_map */ unsigned int pages; /* total of usable pages of swap */ unsigned int inuse_pages; /* number of those currently in use */ - unsigned int cluster_next; /* likely index for next allocation */ - unsigned int cluster_nr; /* countdown to next cluster search */ - unsigned int __percpu *cluster_next_cpu; /*percpu index for next allocati= on */ struct percpu_cluster __percpu *percpu_cluster; /* per cpu's swap locatio= n */ struct rb_root swap_extent_root;/* root of the swap extent rbtree */ struct block_device *bdev; /* swap device or bdev of swap file */ diff --git a/mm/swapfile.c b/mm/swapfile.c index 574059158627..fca58d43b836 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -1001,49 +1001,6 @@ static void swap_range_free(struct swap_info_struct = *si, unsigned long offset, WRITE_ONCE(si->inuse_pages, si->inuse_pages - nr_entries); } =20 -static void set_cluster_next(struct swap_info_struct *si, unsigned long ne= xt) -{ - unsigned long prev; - - if (!(si->flags & SWP_SOLIDSTATE)) { - si->cluster_next =3D next; - return; - } - - prev =3D this_cpu_read(*si->cluster_next_cpu); - /* - * Cross the swap address space size aligned trunk, choose - * another trunk randomly to avoid lock contention on swap - * address space if possible. - */ - if ((prev >> SWAP_ADDRESS_SPACE_SHIFT) !=3D - (next >> SWAP_ADDRESS_SPACE_SHIFT)) { - /* No free swap slots available */ - if (si->highest_bit <=3D si->lowest_bit) - return; - next =3D get_random_u32_inclusive(si->lowest_bit, si->highest_bit); - next =3D ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES); - next =3D max_t(unsigned int, next, si->lowest_bit); - } - this_cpu_write(*si->cluster_next_cpu, next); -} - -static bool swap_offset_available_and_locked(struct swap_info_struct *si, - unsigned long offset) -{ - if (data_race(!si->swap_map[offset])) { - spin_lock(&si->lock); - return true; - } - - if (vm_swap_full() && READ_ONCE(si->swap_map[offset]) =3D=3D SWAP_HAS_CAC= HE) { - spin_lock(&si->lock); - return true; - } - - return false; -} - static int cluster_alloc_swap(struct swap_info_struct *si, unsigned char usage, int nr, swp_entry_t slots[], int order) @@ -1071,13 +1028,7 @@ static int scan_swap_map_slots(struct swap_info_stru= ct *si, unsigned char usage, int nr, swp_entry_t slots[], int order) { - unsigned long offset; - unsigned long scan_base; - unsigned long last_in_cluster =3D 0; - int latency_ration =3D LATENCY_LIMIT; unsigned int nr_pages =3D 1 << order; - int n_ret =3D 0; - bool scanned_many =3D false; =20 /* * We try to cluster swap pages by allocating them sequentially @@ -1089,7 +1040,6 @@ static int scan_swap_map_slots(struct swap_info_struc= t *si, * But we do now try to find an empty cluster. -Andrea * And we let swap pages go all over an SSD partition. Hugh */ - if (order > 0) { /* * Should not even be attempting large allocations when huge @@ -1109,158 +1059,7 @@ static int scan_swap_map_slots(struct swap_info_str= uct *si, return 0; } =20 - if (si->cluster_info) - return cluster_alloc_swap(si, usage, nr, slots, order); - - si->flags +=3D SWP_SCANNING; - - /* For HDD, sequential access is more important. */ - scan_base =3D si->cluster_next; - offset =3D scan_base; - - if (unlikely(!si->cluster_nr--)) { - if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) { - si->cluster_nr =3D SWAPFILE_CLUSTER - 1; - goto checks; - } - - spin_unlock(&si->lock); - - /* - * If seek is expensive, start searching for new cluster from - * start of partition, to minimize the span of allocated swap. - */ - scan_base =3D offset =3D si->lowest_bit; - last_in_cluster =3D offset + SWAPFILE_CLUSTER - 1; - - /* Locate the first empty (unaligned) cluster */ - for (; last_in_cluster <=3D READ_ONCE(si->highest_bit); offset++) { - if (si->swap_map[offset]) - last_in_cluster =3D offset + SWAPFILE_CLUSTER; - else if (offset =3D=3D last_in_cluster) { - spin_lock(&si->lock); - offset -=3D SWAPFILE_CLUSTER - 1; - si->cluster_next =3D offset; - si->cluster_nr =3D SWAPFILE_CLUSTER - 1; - goto checks; - } - if (unlikely(--latency_ration < 0)) { - cond_resched(); - latency_ration =3D LATENCY_LIMIT; - } - } - - offset =3D scan_base; - spin_lock(&si->lock); - si->cluster_nr =3D SWAPFILE_CLUSTER - 1; - } - -checks: - if (!(si->flags & SWP_WRITEOK)) - goto no_page; - if (!si->highest_bit) - goto no_page; - if (offset > si->highest_bit) - scan_base =3D offset =3D si->lowest_bit; - - /* reuse swap entry of cache-only swap if not busy. */ - if (vm_swap_full() && si->swap_map[offset] =3D=3D SWAP_HAS_CACHE) { - int swap_was_freed; - spin_unlock(&si->lock); - swap_was_freed =3D __try_to_reclaim_swap(si, offset, TTRS_ANYWAY | TTRS_= DIRECT); - spin_lock(&si->lock); - /* entry was freed successfully, try to use this again */ - if (swap_was_freed > 0) - goto checks; - goto scan; /* check next one */ - } - - if (si->swap_map[offset]) { - if (!n_ret) - goto scan; - else - goto done; - } - memset(si->swap_map + offset, usage, nr_pages); - - swap_range_alloc(si, offset, nr_pages); - slots[n_ret++] =3D swp_entry(si->type, offset); - - /* got enough slots or reach max slots? */ - if ((n_ret =3D=3D nr) || (offset >=3D si->highest_bit)) - goto done; - - /* search for next available slot */ - - /* time to take a break? */ - if (unlikely(--latency_ration < 0)) { - if (n_ret) - goto done; - spin_unlock(&si->lock); - cond_resched(); - spin_lock(&si->lock); - latency_ration =3D LATENCY_LIMIT; - } - - if (si->cluster_nr && !si->swap_map[++offset]) { - /* non-ssd case, still more slots in cluster? */ - --si->cluster_nr; - goto checks; - } - - /* - * Even if there's no free clusters available (fragmented), - * try to scan a little more quickly with lock held unless we - * have scanned too many slots already. - */ - if (!scanned_many) { - unsigned long scan_limit; - - if (offset < scan_base) - scan_limit =3D scan_base; - else - scan_limit =3D si->highest_bit; - for (; offset <=3D scan_limit && --latency_ration > 0; - offset++) { - if (!si->swap_map[offset]) - goto checks; - } - } - -done: - if (order =3D=3D 0) - set_cluster_next(si, offset + 1); - si->flags -=3D SWP_SCANNING; - return n_ret; - -scan: - VM_WARN_ON(order > 0); - spin_unlock(&si->lock); - while (++offset <=3D READ_ONCE(si->highest_bit)) { - if (unlikely(--latency_ration < 0)) { - cond_resched(); - latency_ration =3D LATENCY_LIMIT; - scanned_many =3D true; - } - if (swap_offset_available_and_locked(si, offset)) - goto checks; - } - offset =3D si->lowest_bit; - while (offset < scan_base) { - if (unlikely(--latency_ration < 0)) { - cond_resched(); - latency_ration =3D LATENCY_LIMIT; - scanned_many =3D true; - } - if (swap_offset_available_and_locked(si, offset)) - goto checks; - offset++; - } - spin_lock(&si->lock); - -no_page: - si->flags -=3D SWP_SCANNING; - return n_ret; + return cluster_alloc_swap(si, usage, nr, slots, order); } =20 int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_order) @@ -2871,8 +2670,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) mutex_unlock(&swapon_mutex); free_percpu(p->percpu_cluster); p->percpu_cluster =3D NULL; - free_percpu(p->cluster_next_cpu); - p->cluster_next_cpu =3D NULL; vfree(swap_map); kvfree(zeromap); kvfree(cluster_info); @@ -3184,8 +2981,6 @@ static unsigned long read_swap_header(struct swap_inf= o_struct *si, } =20 si->lowest_bit =3D 1; - si->cluster_next =3D 1; - si->cluster_nr =3D 0; =20 maxpages =3D swapfile_maximum_size; last_page =3D swap_header->info.last_page; @@ -3271,7 +3066,6 @@ static struct swap_cluster_info *setup_clusters(struc= t swap_info_struct *si, unsigned long maxpages) { unsigned long nr_clusters =3D DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); - unsigned long col =3D si->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_= COLS; struct swap_cluster_info *cluster_info; unsigned long i, j, k, idx; int cpu, err =3D -ENOMEM; @@ -3283,15 +3077,6 @@ static struct swap_cluster_info *setup_clusters(stru= ct swap_info_struct *si, for (i =3D 0; i < nr_clusters; i++) spin_lock_init(&cluster_info[i].lock); =20 - si->cluster_next_cpu =3D alloc_percpu(unsigned int); - if (!si->cluster_next_cpu) - goto err_free; - - /* Random start position to help with wear leveling */ - for_each_possible_cpu(cpu) - per_cpu(*si->cluster_next_cpu, cpu) =3D - get_random_u32_inclusive(1, si->highest_bit); - si->percpu_cluster =3D alloc_percpu(struct percpu_cluster); if (!si->percpu_cluster) goto err_free; @@ -3333,7 +3118,7 @@ static struct swap_cluster_info *setup_clusters(struc= t swap_info_struct *si, * sharing same address space. */ for (k =3D 0; k < SWAP_CLUSTER_COLS; k++) { - j =3D (k + col) % SWAP_CLUSTER_COLS; + j =3D k % SWAP_CLUSTER_COLS; 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; @@ -3483,18 +3268,18 @@ SYSCALL_DEFINE2(swapon, const char __user *, specia= lfile, int, swap_flags) =20 if (si->bdev && bdev_nonrot(si->bdev)) { si->flags |=3D SWP_SOLIDSTATE; - - cluster_info =3D setup_clusters(si, swap_header, maxpages); - if (IS_ERR(cluster_info)) { - error =3D PTR_ERR(cluster_info); - cluster_info =3D NULL; - goto bad_swap_unlock_inode; - } } else { atomic_inc(&nr_rotate_swap); inced_nr_rotate_swap =3D true; } =20 + cluster_info =3D setup_clusters(si, swap_header, maxpages); + if (IS_ERR(cluster_info)) { + error =3D PTR_ERR(cluster_info); + cluster_info =3D NULL; + goto bad_swap_unlock_inode; + } + if ((swap_flags & SWAP_FLAG_DISCARD) && si->bdev && bdev_max_discard_sectors(si->bdev)) { /* @@ -3575,8 +3360,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) bad_swap: free_percpu(si->percpu_cluster); si->percpu_cluster =3D NULL; - free_percpu(si->cluster_next_cpu); - si->cluster_next_cpu =3D NULL; inode =3D NULL; destroy_swap_extents(si); swap_cgroup_swapoff(si->type); --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f182.google.com (mail-pl1-f182.google.com [209.85.214.182]) (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 278081DA103 for ; Tue, 24 Dec 2024 14:39:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051187; cv=none; b=dGaVNtTAmzDM6uUoCzOOPG1KzWPK5699cKON61kW+G7fd4OtuRsN9ygyHdJS2+D8N8J7hVYMoTwWuBqu4WuLWS7zIxB6VybZ8EfZI3RA0kGeo0oxUqadJkyNiZRYLmE9gXBB1wlhfj72iF4NS8EQRAU92+yXxQNhr/34zjR6/Ak= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051187; c=relaxed/simple; bh=3jCDeyFvOqAl0p9a8+jgxU4Yeqh/4b2T3Q6OpygKl+w=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=LIK47zNLs/O+MkL1Ou2ds69Gr4hZjoQ0tGu5ofAMGbZFp6nZBmPIPjKdc1k99XNpuM5PGv/IlXDPgyZd3+Ob50rO/dPvwGJDg2jyaWCeiPcsfTAcA7/jvUXR2vUSTzyfDFfa1OGWZLZjgql6m6sNU3sHDMVDUkzCWdmnnyoCU+Q= 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=X6vq2Z4L; arc=none smtp.client-ip=209.85.214.182 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="X6vq2Z4L" Received: by mail-pl1-f182.google.com with SMTP id d9443c01a7336-21644aca3a0so61862075ad.3 for ; Tue, 24 Dec 2024 06:39:45 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051185; x=1735655985; 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=OUd7wiP5I69QsBZ6QEaFt/A5eIkrt9OzZ0llQ5gAam8=; b=X6vq2Z4LsR2xFX51FjPmRysY4Pr3JXoY9P3hc6j4BnerwJL4jHXgRNOzmzEN844QeD VsNPZ6kDsaO26I5PmEEpsnvesO0fgnOkWQ9puWfqKLngMYD3m7aNGGpxX2HBhloLQJcY FMaOP9OV4kUxs/AhqrIJrl9nAg8YssaVsn9Wy29KRY3c95dyGS7VkAEKGTPiTx2Jd/Xz OBhI/A053OQjKgBmCN+UCWyog17hKTtv+rEMoyEPujDLiXi4BVv3o7g3rAunaw9PUzMv 526KW8NGw/jiVMbc/Qb7QeakubGzeQFHKFIx36Z4a62MtV/Gd53TBP0tuo3CGsjkJGUg TAgg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051185; x=1735655985; 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=OUd7wiP5I69QsBZ6QEaFt/A5eIkrt9OzZ0llQ5gAam8=; b=WyJRv7pOgEWC/xYBvYpf4M1jT6IoVQcnTkRSTPFjVUgd2oj82KrF4zSAEt4B/a+mxH lmJMTCIwT14mAhgeUaSKQs0M30MpXS7GrZhlTJ3wvstASmYt7kU2OxU4x6hSDmyyOFfC 7U+a6g0vqtBKyJLmpYANAmcYFecY86wiu6HLqHO/pTtIeEAuI6sZTQS5f4NaGAOnu0D7 PvajCtL3zmgN3/0By2FgzhnwEPRIojPJykj+VTDERBEhLfbUsTiIxlh10JOJA5PMXtF+ ApTWxhMPn87+CaTE5TM27jBigL/McA6WTdmNmWuz+V9D8wbub8hZ4iCBKhVGT1h8x/B4 U4Gg== X-Forwarded-Encrypted: i=1; AJvYcCXWf+lblgIHBLJDLLoFJt05K8ZXYpxdJC3MmjbSDa1U5Zd02KMsx4NM3nodE1Z8lzEcgo18034ZWdXO0tY=@vger.kernel.org X-Gm-Message-State: AOJu0YwSIvlrWxyqES0+NWDUT4zjtx11KZDeqAt132s7y7S8nS4krJUS 0UfJNcRUTr415BkK0yIP+DgMunfy8quWho9W73Ga6aBI/et7k56K X-Gm-Gg: ASbGncuTSDj9SjmzMA9hUOSMaLJj8ueynJd5JRVRfpNTIimHyCrg+2tCVDn1G1zvEQz gZqYgPvIAc3gWWVW/7yvo6Y5fQ39z8HOUT5a2SqZ5mmC0A0WEJKwYLlGE/tIxak7DkH/EZetxU2 IoWjq1Y+j2YwFSkh5DiZoo0YVfohjjOt5X8n/fUaBV5FXU+cl6HWvtuwtl3lqHSLp+PZIXVE06P IPYNcnTJU/Z3dnEP1qYPCaD65ieXrcxxL04T046+wqwghsKFVIDJW5S/po9v7E4VbhsuxaVr8KI Bg== X-Google-Smtp-Source: AGHT+IE4+37LkTR/shstkl6vwn0NHWgUrerMEPAg5MTpigYxllj3TZwSffwTFxM6mFeGjyntkHJiPQ== X-Received: by 2002:a17:902:dace:b0:216:4064:53ad with SMTP id d9443c01a7336-219e6f26fd6mr211789875ad.48.1735051185324; Tue, 24 Dec 2024 06:39:45 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.41 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:39:44 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 04/13] mm, swap: use cluster lock for HDD Date: Tue, 24 Dec 2024 22:38:02 +0800 Message-ID: <20241224143811.33462-5-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 Cluster lock (ci->lock) was introduce to reduce contention for certain operations. Using cluster lock for HDD is not helpful as HDD have a poor performance, so locking isn't the bottleneck. But having different set of locks for HDD / non-HDD prevents further rework of device lock (si->lock). This commit just changed all lock_cluster_or_swap_info to lock_cluster, which is a safe and straight conversion since cluster info is always allocated now, also removed all cluster_info related checks. Suggested-by: Chris Li Signed-off-by: Kairui Song --- mm/swapfile.c | 107 ++++++++++++++++---------------------------------- 1 file changed, 34 insertions(+), 73 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index fca58d43b836..d0e5b9fa0c48 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -58,10 +58,9 @@ static void swap_entry_range_free(struct swap_info_struc= t *si, swp_entry_t entry static void swap_range_alloc(struct swap_info_struct *si, unsigned long of= fset, unsigned int nr_entries); static bool folio_swapcache_freeable(struct folio *folio); -static struct swap_cluster_info *lock_cluster_or_swap_info( - struct swap_info_struct *si, unsigned long offset); -static void unlock_cluster_or_swap_info(struct swap_info_struct *si, - struct swap_cluster_info *ci); +static struct swap_cluster_info *lock_cluster(struct swap_info_struct *si, + unsigned long offset); +static void unlock_cluster(struct swap_cluster_info *ci); =20 static DEFINE_SPINLOCK(swap_lock); static unsigned int nr_swapfiles; @@ -222,9 +221,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_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); need_reclaim =3D swap_is_has_cache(si, offset, nr_pages); - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); if (!need_reclaim) goto out_unlock; =20 @@ -404,45 +403,15 @@ static inline struct swap_cluster_info *lock_cluster(= struct swap_info_struct *si { struct swap_cluster_info *ci; =20 - ci =3D si->cluster_info; - if (ci) { - ci +=3D offset / SWAPFILE_CLUSTER; - spin_lock(&ci->lock); - } - return ci; -} - -static inline void unlock_cluster(struct swap_cluster_info *ci) -{ - if (ci) - spin_unlock(&ci->lock); -} - -/* - * Determine the locking method in use for this device. Return - * swap_cluster_info if SSD-style cluster-based locking is in place. - */ -static inline struct swap_cluster_info *lock_cluster_or_swap_info( - struct swap_info_struct *si, unsigned long offset) -{ - struct swap_cluster_info *ci; - - /* Try to use fine-grained SSD-style locking if available: */ - ci =3D lock_cluster(si, offset); - /* Otherwise, fall back to traditional, coarse locking: */ - if (!ci) - spin_lock(&si->lock); + ci =3D &si->cluster_info[offset / SWAPFILE_CLUSTER]; + spin_lock(&ci->lock); =20 return ci; } =20 -static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si, - struct swap_cluster_info *ci) +static inline void unlock_cluster(struct swap_cluster_info *ci) { - if (ci) - unlock_cluster(ci); - else - spin_unlock(&si->lock); + spin_unlock(&ci->lock); } =20 /* Add a cluster to discard list and schedule it to do discard */ @@ -558,9 +527,6 @@ static void inc_cluster_info_page(struct swap_info_stru= ct *si, unsigned long idx =3D page_nr / SWAPFILE_CLUSTER; struct swap_cluster_info *ci; =20 - if (!cluster_info) - return; - ci =3D cluster_info + idx; ci->count++; =20 @@ -576,9 +542,6 @@ static void inc_cluster_info_page(struct swap_info_stru= ct *si, static void dec_cluster_info_page(struct swap_info_struct *si, struct swap_cluster_info *ci, int nr_pages) { - if (!si->cluster_info) - return; - VM_BUG_ON(ci->count < nr_pages); VM_BUG_ON(cluster_is_free(ci)); lockdep_assert_held(&si->lock); @@ -1007,8 +970,6 @@ static int cluster_alloc_swap(struct swap_info_struct = *si, { int n_ret =3D 0; =20 - VM_BUG_ON(!si->cluster_info); - si->flags +=3D SWP_SCANNING; =20 while (n_ret < nr) { @@ -1052,10 +1013,10 @@ static int scan_swap_map_slots(struct swap_info_str= uct *si, } =20 /* - * Swapfile is not block device or not using clusters so unable + * Swapfile is not block device so unable * to allocate large entries. */ - if (!(si->flags & SWP_BLKDEV) || !si->cluster_info) + if (!(si->flags & SWP_BLKDEV)) return 0; } =20 @@ -1295,9 +1256,9 @@ static unsigned char __swap_entry_free(struct swap_in= fo_struct *si, unsigned long offset =3D swp_offset(entry); unsigned char usage; =20 - ci =3D lock_cluster_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); usage =3D __swap_entry_free_locked(si, offset, 1); - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); if (!usage) free_swap_slot(entry); =20 @@ -1320,14 +1281,14 @@ static bool __swap_entries_free(struct swap_info_st= ruct *si, if (nr > SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER) goto fallback; =20 - ci =3D lock_cluster_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); if (!swap_is_last_map(si, offset, nr, &has_cache)) { - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); goto fallback; } for (i =3D 0; i < nr; i++) WRITE_ONCE(si->swap_map[offset + i], SWAP_HAS_CACHE); - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); =20 if (!has_cache) { for (i =3D 0; i < nr; i++) @@ -1383,7 +1344,7 @@ static void cluster_swap_free_nr(struct swap_info_str= uct *si, DECLARE_BITMAP(to_free, BITS_PER_LONG) =3D { 0 }; int i, nr; =20 - ci =3D lock_cluster_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); while (nr_pages) { nr =3D min(BITS_PER_LONG, nr_pages); for (i =3D 0; i < nr; i++) { @@ -1391,18 +1352,18 @@ static void cluster_swap_free_nr(struct swap_info_s= truct *si, bitmap_set(to_free, i, 1); } if (!bitmap_empty(to_free, BITS_PER_LONG)) { - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); for_each_set_bit(i, to_free, BITS_PER_LONG) free_swap_slot(swp_entry(si->type, offset + i)); if (nr =3D=3D nr_pages) return; bitmap_clear(to_free, 0, BITS_PER_LONG); - ci =3D lock_cluster_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); } offset +=3D nr; nr_pages -=3D nr; } - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); } =20 /* @@ -1441,9 +1402,9 @@ void put_swap_folio(struct folio *folio, swp_entry_t = entry) if (!si) return; =20 - ci =3D lock_cluster_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); if (size > 1 && swap_is_has_cache(si, offset, size)) { - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); spin_lock(&si->lock); swap_entry_range_free(si, entry, size); spin_unlock(&si->lock); @@ -1451,14 +1412,14 @@ void put_swap_folio(struct folio *folio, swp_entry_= t entry) } for (int i =3D 0; i < size; i++, entry.val++) { if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) { - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); free_swap_slot(entry); if (i =3D=3D size - 1) return; - lock_cluster_or_swap_info(si, offset); + lock_cluster(si, offset); } } - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); } =20 static int swp_entry_cmp(const void *ent1, const void *ent2) @@ -1522,9 +1483,9 @@ int swap_swapcount(struct swap_info_struct *si, swp_e= ntry_t entry) struct swap_cluster_info *ci; int count; =20 - ci =3D lock_cluster_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); count =3D swap_count(si->swap_map[offset]); - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); return count; } =20 @@ -1547,7 +1508,7 @@ int swp_swapcount(swp_entry_t entry) =20 offset =3D swp_offset(entry); =20 - ci =3D lock_cluster_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); =20 count =3D swap_count(si->swap_map[offset]); if (!(count & COUNT_CONTINUED)) @@ -1570,7 +1531,7 @@ int swp_swapcount(swp_entry_t entry) n *=3D (SWAP_CONT_MAX + 1); } while (tmp_count & COUNT_CONTINUED); out: - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); return count; } =20 @@ -1585,8 +1546,8 @@ static bool swap_page_trans_huge_swapped(struct swap_= info_struct *si, int i; bool ret =3D false; =20 - ci =3D lock_cluster_or_swap_info(si, offset); - if (!ci || nr_pages =3D=3D 1) { + ci =3D lock_cluster(si, offset); + if (nr_pages =3D=3D 1) { if (swap_count(map[roffset])) ret =3D true; goto unlock_out; @@ -1598,7 +1559,7 @@ static bool swap_page_trans_huge_swapped(struct swap_= info_struct *si, } } unlock_out: - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); return ret; } =20 @@ -3428,7 +3389,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_or_swap_info(si, offset); + ci =3D lock_cluster(si, offset); =20 err =3D 0; for (i =3D 0; i < nr; i++) { @@ -3483,7 +3444,7 @@ static int __swap_duplicate(swp_entry_t entry, unsign= ed char usage, int nr) } =20 unlock_out: - unlock_cluster_or_swap_info(si, ci); + unlock_cluster(ci); return err; } =20 --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f177.google.com (mail-pl1-f177.google.com [209.85.214.177]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 44C171D86C0 for ; Tue, 24 Dec 2024 14:39:50 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051191; cv=none; b=iXqF0jQoebR6yIrs+d/O1j0vSQ7Ck4AFgWbMdeO5A7951zDhudiQzVeD/q0qsrpkvz48dS7TQUdzR3UlDS9SOrL9sOpOXYliNf74wXAeGEcrwknjajJymbTsyLuz/WUAa/I+7A7lVi3OHIeNennCQ8172ODNZhYQTvyiIInGhsk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051191; c=relaxed/simple; bh=dtNcCmTYRKXK6CZ3QO3jZvfGSnOtB9P7pdG0quS09Qs=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Vkv4/DlC8yS0zvZl1nAHdhz05GpCapSfDhlhVJKQZDYESJT6q9XNylrH98O8UsAKQRawCoX2zAiy9P7ro0rF+Xts+tJ7V3bnwQAJbsUm5E6b7lBGVuwTFG/xkuctBPb5ta+eNOEctSXm+RlvCwFOUGGhIV8HFiOphG283PmrqQo= 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=eadvbEpL; arc=none smtp.client-ip=209.85.214.177 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="eadvbEpL" Received: by mail-pl1-f177.google.com with SMTP id d9443c01a7336-2166022c5caso47527755ad.2 for ; Tue, 24 Dec 2024 06:39:50 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051189; x=1735655989; 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=wrLhjYRLlutCAl1gCOYOsbHS82zDx2LhvG3HLqe+qww=; b=eadvbEpL4k9En66vlQtk0DOwjKuZ4KyivUnnnvsG7fLO/1C+JM+ukM08/A/V+uCWUp pcb7J8Z7VVvXmNx5lj0m1UQI4wKODu0wRWx6e2S5ZwByNjgPwyRLUdmyAgqJi7ZygpX5 vSV6gs4doxTAValogamOOMDvjxzeLeEqYOvFMrqa4FnpQUHyiyMlmlhyOnYP1HNCgUTs 31Zfffl/mBj7Ft467eW6iPWdvxW8mpUrKOsuRJItXOrtrZlXAuUMWiDZoNtbQsZaG/bt qIAH3mjoRUb+LkaDdTRMqdpZlmNJ6e2mZA6gMvtlqckWhrieRSC+V/rqMQWmlF+aOOxt ji3A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051189; x=1735655989; 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=wrLhjYRLlutCAl1gCOYOsbHS82zDx2LhvG3HLqe+qww=; b=IOVghXu9wTXxoUydWlkIFL4kGlc7BY6gqC4pdJFBVEsJZch0zRlO/syKB9WAQC5dhh jyMNzjdWu6TUXdIXJEmijbbj8FeN8X90ABZp+WJNNsw3KedIWj6LyfCY+PNQH5wf8wT5 l77E4K8+ugyzxC+VXonxpwZljdPh9nlN03Oelt9lTnt2tb49JoSaqPqd+CFCLqCiA5zK x8pw/uuiH3W9ATHXdm4g4P9ycz/cKoVLWyJTOn4sdKIwiZ5bgaJuA3lbJ3bxzkahfuN0 p60UTa3N9ReX24HQ9MGgKuusAyHww8jQAC6ee2CnhXflhY+ACVGa5SWCUkqHSjvAEdgx oCtA== X-Forwarded-Encrypted: i=1; AJvYcCUXt5ix1iQWk5hdEYlu+CkomwAZHq6cmFxS8JeB7f5BJOfmUHDNmByAT1+k3XUG9PdY4AsiJRpb/n4MyVg=@vger.kernel.org X-Gm-Message-State: AOJu0Yw9DTfNQTyD/V0AzvQio0AmlWHbl+Ex4LjVDfJnGtgZDFY0bJRI hg/Fg2nMWfw+6YhLDdqWd+k9oVGSF3rh6JGkJ1oP26LDlZ2T4DhT X-Gm-Gg: ASbGncvYijh+TNzPDDX8K8v1f1+JzXZvnXJlOeKcp2SqNjoyr+aZyWHWty4X7D10oG3 SAFuYf6cY5JHmfLzlXQ+3lQvwu8CLBo/ZKjHLn2irOglFTzyY1cZsRToePzh8OU/JsANbydWMNp Xt/6/ohic4XDfUaqAniJ8tDquPzJFxTHhCwFW+XxHHFkogY2WMJXrZpuMjiMIPOapSQpBP+IuQL LR0kcSWARLsILSj8/oQekm8Hlu+xdxZ7XT6T9gIPzCAtEQUd/6dLZ5nkD3/iwf5w/DgeRRuiA0R 4w== X-Google-Smtp-Source: AGHT+IGNGHWwQc63B1avFd+9enD0tjMC22ByFTa2Ud87N8om2hjQ66akQBxyJtCo/qcrn+jE1mHd2w== X-Received: by 2002:a17:902:d501:b0:216:6f1a:1c81 with SMTP id d9443c01a7336-219e6e8c975mr258344285ad.2.1735051189528; Tue, 24 Dec 2024 06:39:49 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.45 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:39:49 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 05/13] mm, swap: clean up device availability check Date: Tue, 24 Dec 2024 22:38:03 +0800 Message-ID: <20241224143811.33462-6-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 Remove highest_bit and lowest_bit. After the HDD allocation path has been removed, the only purpose of these two fields is to determine whether the device is full or not, which can instead be determined by checking the inuse_pages. Signed-off-by: Kairui Song Suggested-by: Chris Li --- fs/btrfs/inode.c | 1 - fs/iomap/swapfile.c | 1 - include/linux/swap.h | 2 -- mm/page_io.c | 1 - mm/swapfile.c | 38 ++++++++------------------------------ 5 files changed, 8 insertions(+), 35 deletions(-) diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index 488edca8333a..a1ba78afab2c 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -10044,7 +10044,6 @@ static int btrfs_swap_activate(struct swap_info_str= uct *sis, struct file *file, *span =3D bsi.highest_ppage - bsi.lowest_ppage + 1; sis->max =3D bsi.nr_pages; sis->pages =3D bsi.nr_pages - 1; - sis->highest_bit =3D bsi.nr_pages - 1; return bsi.nr_extents; } #else diff --git a/fs/iomap/swapfile.c b/fs/iomap/swapfile.c index 5fc0ac36dee3..b90d0eda9e51 100644 --- a/fs/iomap/swapfile.c +++ b/fs/iomap/swapfile.c @@ -189,7 +189,6 @@ int iomap_swapfile_activate(struct swap_info_struct *si= s, *pagespan =3D 1 + isi.highest_ppage - isi.lowest_ppage; sis->max =3D isi.nr_pages; sis->pages =3D isi.nr_pages - 1; - sis->highest_bit =3D isi.nr_pages - 1; return isi.nr_extents; } EXPORT_SYMBOL_GPL(iomap_swapfile_activate); diff --git a/include/linux/swap.h b/include/linux/swap.h index 0c681aa5cb98..0c222017b5c6 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -306,8 +306,6 @@ struct swap_info_struct { struct list_head frag_clusters[SWAP_NR_ORDERS]; /* list of cluster that are fragmented or contented */ unsigned int frag_cluster_nr[SWAP_NR_ORDERS]; - unsigned int lowest_bit; /* index of first free in swap_map */ - unsigned int highest_bit; /* index of last free in swap_map */ unsigned int pages; /* total of usable pages of swap */ unsigned int inuse_pages; /* number of those currently in use */ struct percpu_cluster __percpu *percpu_cluster; /* per cpu's swap locatio= n */ diff --git a/mm/page_io.c b/mm/page_io.c index 4b4ea8e49cf6..9b983de351f9 100644 --- a/mm/page_io.c +++ b/mm/page_io.c @@ -163,7 +163,6 @@ int generic_swapfile_activate(struct swap_info_struct *= sis, page_no =3D 1; /* force Empty message */ sis->max =3D page_no; sis->pages =3D page_no - 1; - sis->highest_bit =3D page_no - 1; out: return ret; bad_bmap: diff --git a/mm/swapfile.c b/mm/swapfile.c index d0e5b9fa0c48..7963a0c646a4 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -55,7 +55,7 @@ static bool swap_count_continued(struct swap_info_struct = *, pgoff_t, static void free_swap_count_continuations(struct swap_info_struct *); static void swap_entry_range_free(struct swap_info_struct *si, swp_entry_t= entry, unsigned int nr_pages); -static void swap_range_alloc(struct swap_info_struct *si, unsigned long of= fset, +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, @@ -650,7 +650,7 @@ static bool cluster_alloc_range(struct swap_info_struct= *si, struct swap_cluster } =20 memset(si->swap_map + start, usage, nr_pages); - swap_range_alloc(si, start, nr_pages); + swap_range_alloc(si, nr_pages); ci->count +=3D nr_pages; =20 if (ci->count =3D=3D SWAPFILE_CLUSTER) { @@ -888,19 +888,11 @@ static void del_from_avail_list(struct swap_info_stru= ct *si) spin_unlock(&swap_avail_lock); } =20 -static void swap_range_alloc(struct swap_info_struct *si, unsigned long of= fset, +static void swap_range_alloc(struct swap_info_struct *si, unsigned int nr_entries) { - unsigned int end =3D offset + nr_entries - 1; - - if (offset =3D=3D si->lowest_bit) - si->lowest_bit +=3D nr_entries; - if (end =3D=3D si->highest_bit) - WRITE_ONCE(si->highest_bit, si->highest_bit - nr_entries); WRITE_ONCE(si->inuse_pages, si->inuse_pages + nr_entries); if (si->inuse_pages =3D=3D si->pages) { - si->lowest_bit =3D si->max; - si->highest_bit =3D 0; del_from_avail_list(si); =20 if (si->cluster_info && vm_swap_full()) @@ -933,15 +925,8 @@ static void swap_range_free(struct swap_info_struct *s= i, unsigned long offset, for (i =3D 0; i < nr_entries; i++) clear_bit(offset + i, si->zeromap); =20 - if (offset < si->lowest_bit) - si->lowest_bit =3D offset; - if (end > si->highest_bit) { - bool was_full =3D !si->highest_bit; - - WRITE_ONCE(si->highest_bit, end); - if (was_full && (si->flags & SWP_WRITEOK)) - add_to_avail_list(si); - } + if (si->inuse_pages =3D=3D si->pages) + add_to_avail_list(si); if (si->flags & SWP_BLKDEV) swap_slot_free_notify =3D si->bdev->bd_disk->fops->swap_slot_free_notify; @@ -1051,15 +1036,12 @@ int get_swap_pages(int n_goal, swp_entry_t swp_entr= ies[], int entry_order) plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]); spin_unlock(&swap_avail_lock); spin_lock(&si->lock); - if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) { + if ((si->inuse_pages =3D=3D si->pages) || !(si->flags & SWP_WRITEOK)) { spin_lock(&swap_avail_lock); if (plist_node_empty(&si->avail_lists[node])) { spin_unlock(&si->lock); goto nextsi; } - WARN(!si->highest_bit, - "swap_info %d in list but !highest_bit\n", - si->type); WARN(!(si->flags & SWP_WRITEOK), "swap_info %d in list but !SWP_WRITEOK\n", si->type); @@ -2441,8 +2423,8 @@ static void _enable_swap_info(struct swap_info_struct= *si) */ plist_add(&si->list, &swap_active_head); =20 - /* add to available list iff swap device is not full */ - if (si->highest_bit) + /* add to available list if swap device is not full */ + if (si->inuse_pages < si->pages) add_to_avail_list(si); } =20 @@ -2606,7 +2588,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) drain_mmlist(); =20 /* wait for anyone still in scan_swap_map_slots */ - p->highest_bit =3D 0; /* cuts scans short */ while (p->flags >=3D SWP_SCANNING) { spin_unlock(&p->lock); spin_unlock(&swap_lock); @@ -2941,8 +2922,6 @@ static unsigned long read_swap_header(struct swap_inf= o_struct *si, return 0; } =20 - si->lowest_bit =3D 1; - maxpages =3D swapfile_maximum_size; last_page =3D swap_header->info.last_page; if (!last_page) { @@ -2959,7 +2938,6 @@ static unsigned long read_swap_header(struct swap_inf= o_struct *si, if ((unsigned int)maxpages =3D=3D 0) maxpages =3D UINT_MAX; } - si->highest_bit =3D maxpages - 1; =20 if (!maxpages) return 0; --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f174.google.com (mail-pl1-f174.google.com [209.85.214.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 9F99C1DBB36 for ; Tue, 24 Dec 2024 14:39:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051196; cv=none; b=ZDTRgm27QfcKVBAzsmzygnvtNekyLK91EQr1rS9acuXPYIYQ9EVphNyXr6y/gLrZra5NsgmoHU/u6+kgeBUWhXvbf32jfjjUksaD9GmFbMlNveGoJlvvR0vydq7F4vFAcaiA3BIqiN9Xux2aT+3pI3wA/0SacgFBTQ3X6CMX+n4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051196; c=relaxed/simple; bh=PsmCvpiLh85Sjo/WkCeNbDstRNN3M0IKfxY7LHlaxYI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=sNAAFk1FzLmC7abIfQG4IuzNGQAoi/dOrYU2Pu025C01eAVykHHT9E88TSGsB/hOysMyA4IWtyPajUCbrGx3jC7gZ937EPDHlrLjppUTCsc5jP9046V29JOMPNxblEKofX1gvCIK5OqzTb9gTTCoLETdJF5Osd4ACXSCMaAtA9w= 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=Pk3BLJxW; arc=none smtp.client-ip=209.85.214.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="Pk3BLJxW" Received: by mail-pl1-f174.google.com with SMTP id d9443c01a7336-218c8aca5f1so62516995ad.0 for ; Tue, 24 Dec 2024 06:39:54 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051194; x=1735655994; 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=mhVpmJTS6rGzEbGdCTwpT/iR8iNpYNa0AWyURPUsTrM=; b=Pk3BLJxWKFR8K6I8XIhVK6Pdk+Gr2Hy8+3IcMbqub9Vb6IhEUuyNEpp/uM+gYXGHEC Iold+U3ydW3zqImbyi/E/dqi4fs6+zOVjYUa0GxRY7BpzYlyctcMpzJ8yQT0R7mppfOV 7dCQf2vtuGLJcS+k4OrBPESGlF/zCXmgDz1A4LoS5ngBFjFXX/W5JgHEk1FzB6uNZRiC qbFxXdzD2cK+tR8c4SCzHR9Jw1LM03yIPQ5JCrFKWqbMAejtyZrNMQG4YJKHk9L5mnaA Qr9VY34b0P56h1ANdsBLZVq6pmE9/6Jf4JdOs7c+/RzD6Q+59sNFMqPeWSEmyuz7MFTQ qCtw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051194; x=1735655994; 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=mhVpmJTS6rGzEbGdCTwpT/iR8iNpYNa0AWyURPUsTrM=; b=CTe0Fy3Hj8924BWPM3N1Vmc0cjzWwMzoOuBUqiDyEw2aEpfWt0zNVLk82PfBP6e+69 OL5XWqMreJ9b5OHCiOp+V6THUt1j7BjB8f1eHPxW6DsY3zWKof4F4xAOGIaJ3/aV7pDr RBCmct8p4dpBt5L0epysnHtuRxSG6RVAkUIqenQcsrZdtR8/fQxcQ2v8cx4u3eCS37rc kyrFENDQBu5neKb2/seQO1ZKrL6h4zkoGvRbWk6Y4d/3iiHJPgKrqUV4M8pWPKH5PFTM zO4DbT0tQNN7Nz2ImBYE3J0Y3/4+FlFupKJk00KuYxWs3JlSEPchcbtb0X5+NRA8j1gK S9og== X-Forwarded-Encrypted: i=1; AJvYcCVpif6NUlsfiCVQdMzoYu6WoP60Deg+NNZljkJNh1X3FJ3kfHA2sdR3d2RWeDvZyoL1Q8VXNLRolUKjqxY=@vger.kernel.org X-Gm-Message-State: AOJu0YwMlQjSmTO5Ou+9fUrfd8sO6zTitg+dGHqcM56gFf5+MCSyg8Eg 8QbLqqkGHvxadOhZY9X8gqB5OS11BbiaNbKTk4H6zXP1WGy5GSH0 X-Gm-Gg: ASbGncsp+mDiV6NARLSbGm9vLOWRL4+rN1wBbBAm/5Jg/aW7GEVWuWPewDIgcXnFg+p hAMJvtWoPHrJp350NPomShMQ3Nm+h7dQbok2UXE36H66Ns7qqPVr9Q+jzNck7s+xGjs8gBad1ul K/IPUI9xEGu+yu/0kOUGivODQ5mxMLhgmw+I4bCN9hQVMQNwq0/dVA6m7YT2cdEWPwauv+x8nLr O1gXDBPk283VBhUB0uIJ55xBH2wzj1hHrwD3PhRpQ9Q6M/FopWI0HC1lJgHpdgqshH5b97GmYqL xA== X-Google-Smtp-Source: AGHT+IF0Mieft9SPZ9YL6n6WOz7rzrI2R1GTud1LrsAnCe1roQtNTk+vccAeFonoqRhrlCFIHfMJ1Q== X-Received: by 2002:a17:902:eccc:b0:20c:9936:f0ab with SMTP id d9443c01a7336-219e6f27fecmr238487775ad.47.1735051193891; Tue, 24 Dec 2024 06:39:53 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.49 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:39:53 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 06/13] mm, swap: clean up plist removal and adding Date: Tue, 24 Dec 2024 22:38:04 +0800 Message-ID: <20241224143811.33462-7-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 When the swap device is full (inuse_pages =3D=3D pages), it should be removed from the allocation available plist. If any slot is freed, the swap device should be added back to the plist. Additionally, during swapon or swapoff, the swap device is forcefully added or removed. Currently, the condition (inuse_pages =3D=3D pages) is checked after every counter update, then remove or add the device accordingly. This is serialized by si->lock. This commit decouples it from the protection of si->lock and reworked plist removal and adding, making it possible to get rid of the hard dependency on si->lock in allocation path in later commits. To achieve this, simply using another lock is not an optimal approach, as the overhead is observable for a hot counter, and may cause complex locking issues. Thus, this commit manages to make it a lock-free atomic operation, by embedding the plist state into the second highest bit of the atomic counter. Simply making the counter an atomic will not work, if the update and plist status check are not performed atomically, we may miss an addition or removal. With the embedded info we can update the counter and check the plist status with single atomic operations, and avoid any extra overheads: If the counter is full (inuse_pages =3D=3D pages) and the off-list bit is unset, we attempt to remove it from the plist. If the counter is not full (inuse_pages !=3D pages) and the off-list bit is set, we attempt to add it to the plist. Removing, adding and bit update is serialized with a lock, which is a cold path. Ordinary counter updates will be lock-free. Signed-off-by: Kairui Song Suggested-by: Chris Li --- include/linux/swap.h | 2 +- mm/swapfile.c | 184 +++++++++++++++++++++++++++++++------------ 2 files changed, 135 insertions(+), 51 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 0c222017b5c6..e1eeea6307cd 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -307,7 +307,7 @@ struct swap_info_struct { /* list of cluster that are fragmented or contented */ unsigned int frag_cluster_nr[SWAP_NR_ORDERS]; unsigned int pages; /* total of usable pages of swap */ - unsigned int inuse_pages; /* number of those currently in use */ + atomic_long_t inuse_pages; /* number of those currently in use */ struct percpu_cluster __percpu *percpu_cluster; /* per cpu's swap locatio= n */ struct rb_root swap_extent_root;/* root of the swap extent rbtree */ struct block_device *bdev; /* swap device or bdev of swap file */ diff --git a/mm/swapfile.c b/mm/swapfile.c index 7963a0c646a4..ae0f7df06474 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -128,6 +128,26 @@ static inline unsigned char swap_count(unsigned char e= nt) return ent & ~SWAP_HAS_CACHE; /* may include COUNT_CONTINUED flag */ } =20 +/* + * Use the second highest bit of inuse_pages counter as the indicator + * of if one swap device is on the available plist, so the atomic can + * still be updated arithmetic while having special data embedded. + * + * inuse_pages counter is the only thing indicating if a device should + * be on avail_lists or not (except swapon / swapoff). By embedding the + * on-list bit in the atomic counter, updates no longer need any lock + * to check the list status. + * + * This bit will be set if the device is not on the plist and not + * usable, will be cleared if the device is on the plist. + */ +#define SWAP_USAGE_OFFLIST_BIT (1UL << (BITS_PER_TYPE(atomic_t) - 2)) +#define SWAP_USAGE_COUNTER_MASK (~SWAP_USAGE_OFFLIST_BIT) +static long swap_usage_in_pages(struct swap_info_struct *si) +{ + return atomic_long_read(&si->inuse_pages) & SWAP_USAGE_COUNTER_MASK; +} + /* Reclaim the swap entry anyway if possible */ #define TTRS_ANYWAY 0x1 /* @@ -717,7 +737,7 @@ static void swap_reclaim_full_clusters(struct swap_info= _struct *si, bool force) int nr_reclaim; =20 if (force) - to_scan =3D si->inuse_pages / SWAPFILE_CLUSTER; + to_scan =3D swap_usage_in_pages(si) / SWAPFILE_CLUSTER; =20 while (!list_empty(&si->full_clusters)) { ci =3D list_first_entry(&si->full_clusters, struct swap_cluster_info, li= st); @@ -872,42 +892,124 @@ static unsigned long cluster_alloc_swap_entry(struct= swap_info_struct *si, int o return found; } =20 -static void __del_from_avail_list(struct swap_info_struct *si) +/* SWAP_USAGE_OFFLIST_BIT can only be cleared by this helper. */ +static void del_from_avail_list(struct swap_info_struct *si, bool swapoff) { int nid; =20 - assert_spin_locked(&si->lock); + spin_lock(&swap_avail_lock); + + if (swapoff) { + /* + * Forcefully remove it. Clear the SWP_WRITEOK flags for + * swapoff here so it's synchronized by both si->lock and + * swap_avail_lock, to ensure the result can be seen by + * add_to_avail_list. + */ + lockdep_assert_held(&si->lock); + si->flags &=3D ~SWP_WRITEOK; + atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages); + } else { + /* + * If not called by swapoff, take it off-list only if it's + * full and SWAP_USAGE_OFFLIST_BIT is not set (strictly + * si->inuse_pages =3D=3D pages), any concurrent slot freeing, + * or device already removed from plist by someone else + * will make this return false. + */ + if (atomic_long_cmpxchg(&si->inuse_pages, si->pages, + si->pages | SWAP_USAGE_OFFLIST_BIT) !=3D si->pages) + goto skip; + } + for_each_node(nid) plist_del(&si->avail_lists[nid], &swap_avail_heads[nid]); + +skip: + spin_unlock(&swap_avail_lock); } =20 -static void del_from_avail_list(struct swap_info_struct *si) +/* SWAP_USAGE_OFFLIST_BIT can only be set by this helper. */ +static void add_to_avail_list(struct swap_info_struct *si, bool swapon) { + int nid; + long val; + spin_lock(&swap_avail_lock); - __del_from_avail_list(si); + + /* Corresponding to SWP_WRITEOK clearing in del_from_avail_list */ + if (swapon) { + lockdep_assert_held(&si->lock); + si->flags |=3D SWP_WRITEOK; + } else { + if (!(READ_ONCE(si->flags) & SWP_WRITEOK)) + goto skip; + } + + if (!(atomic_long_read(&si->inuse_pages) & SWAP_USAGE_OFFLIST_BIT)) + goto skip; + + val =3D atomic_long_fetch_and_relaxed(~SWAP_USAGE_OFFLIST_BIT, &si->inuse= _pages); + + /* + * When device is full and device is on the plist, only one updater will + * see (inuse_pages =3D=3D si->pages) and will call del_from_avail_list. = If + * that updater happen to be here, just skip adding. + */ + if (val =3D=3D si->pages) { + /* Just like the cmpxchg in del_from_avail_list */ + if (atomic_long_cmpxchg(&si->inuse_pages, si->pages, + si->pages | SWAP_USAGE_OFFLIST_BIT) =3D=3D si->pages) + goto skip; + } + + for_each_node(nid) + plist_add(&si->avail_lists[nid], &swap_avail_heads[nid]); + +skip: spin_unlock(&swap_avail_lock); } =20 -static void swap_range_alloc(struct swap_info_struct *si, - unsigned int nr_entries) +/* + * swap_usage_add / swap_usage_sub of each slot are serialized by ci->lock + * within each cluster, so the total contribution to the global counter sh= ould + * always be positive and cannot exceed the total number of usable slots. + */ +static bool swap_usage_add(struct swap_info_struct *si, unsigned int nr_en= tries) { - WRITE_ONCE(si->inuse_pages, si->inuse_pages + nr_entries); - if (si->inuse_pages =3D=3D si->pages) { - del_from_avail_list(si); + long val =3D atomic_long_add_return_relaxed(nr_entries, &si->inuse_pages); =20 - if (si->cluster_info && vm_swap_full()) - schedule_work(&si->reclaim_work); + /* + * If device is full, and SWAP_USAGE_OFFLIST_BIT is not set, + * remove it from the plist. + */ + if (unlikely(val =3D=3D si->pages)) { + del_from_avail_list(si, false); + return true; } + + return false; } =20 -static void add_to_avail_list(struct swap_info_struct *si) +static void swap_usage_sub(struct swap_info_struct *si, unsigned int nr_en= tries) { - int nid; + long val =3D atomic_long_sub_return_relaxed(nr_entries, &si->inuse_pages); =20 - spin_lock(&swap_avail_lock); - for_each_node(nid) - plist_add(&si->avail_lists[nid], &swap_avail_heads[nid]); - spin_unlock(&swap_avail_lock); + /* + * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set, + * remove it from the plist. + */ + if (unlikely(val & SWAP_USAGE_OFFLIST_BIT)) + add_to_avail_list(si, false); +} + +static void swap_range_alloc(struct swap_info_struct *si, + unsigned int nr_entries) +{ + if (swap_usage_add(si, nr_entries)) { + if (si->cluster_info && vm_swap_full()) + schedule_work(&si->reclaim_work); + } } =20 static void swap_range_free(struct swap_info_struct *si, unsigned long off= set, @@ -925,8 +1027,6 @@ static void swap_range_free(struct swap_info_struct *s= i, unsigned long offset, for (i =3D 0; i < nr_entries; i++) clear_bit(offset + i, si->zeromap); =20 - if (si->inuse_pages =3D=3D si->pages) - add_to_avail_list(si); if (si->flags & SWP_BLKDEV) swap_slot_free_notify =3D si->bdev->bd_disk->fops->swap_slot_free_notify; @@ -946,7 +1046,7 @@ static void swap_range_free(struct swap_info_struct *s= i, unsigned long offset, */ smp_wmb(); atomic_long_add(nr_entries, &nr_swap_pages); - WRITE_ONCE(si->inuse_pages, si->inuse_pages - nr_entries); + swap_usage_sub(si, nr_entries); } =20 static int cluster_alloc_swap(struct swap_info_struct *si, @@ -1036,19 +1136,6 @@ int get_swap_pages(int n_goal, swp_entry_t swp_entri= es[], int entry_order) plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]); spin_unlock(&swap_avail_lock); spin_lock(&si->lock); - if ((si->inuse_pages =3D=3D si->pages) || !(si->flags & SWP_WRITEOK)) { - spin_lock(&swap_avail_lock); - if (plist_node_empty(&si->avail_lists[node])) { - spin_unlock(&si->lock); - goto nextsi; - } - WARN(!(si->flags & SWP_WRITEOK), - "swap_info %d in list but !SWP_WRITEOK\n", - si->type); - __del_from_avail_list(si); - spin_unlock(&si->lock); - goto nextsi; - } n_ret =3D scan_swap_map_slots(si, SWAP_HAS_CACHE, n_goal, swp_entries, order); spin_unlock(&si->lock); @@ -1057,7 +1144,6 @@ int get_swap_pages(int n_goal, swp_entry_t swp_entrie= s[], int entry_order) cond_resched(); =20 spin_lock(&swap_avail_lock); -nextsi: /* * if we got here, it's likely that si was almost full before, * and since scan_swap_map_slots() can drop the si->lock, @@ -1789,7 +1875,7 @@ unsigned int count_swap_pages(int type, int free) if (sis->flags & SWP_WRITEOK) { n =3D sis->pages; if (free) - n -=3D sis->inuse_pages; + n -=3D swap_usage_in_pages(sis); } spin_unlock(&sis->lock); } @@ -2124,7 +2210,7 @@ static int try_to_unuse(unsigned int type) swp_entry_t entry; unsigned int i; =20 - if (!READ_ONCE(si->inuse_pages)) + if (!swap_usage_in_pages(si)) goto success; =20 retry: @@ -2137,7 +2223,7 @@ static int try_to_unuse(unsigned int type) =20 spin_lock(&mmlist_lock); p =3D &init_mm.mmlist; - while (READ_ONCE(si->inuse_pages) && + while (swap_usage_in_pages(si) && !signal_pending(current) && (p =3D p->next) !=3D &init_mm.mmlist) { =20 @@ -2165,7 +2251,7 @@ static int try_to_unuse(unsigned int type) mmput(prev_mm); =20 i =3D 0; - while (READ_ONCE(si->inuse_pages) && + while (swap_usage_in_pages(si) && !signal_pending(current) && (i =3D find_next_to_unuse(si, i)) !=3D 0) { =20 @@ -2200,7 +2286,7 @@ static int try_to_unuse(unsigned int type) * folio_alloc_swap(), temporarily hiding that swap. It's easy * and robust (though cpu-intensive) just to keep retrying. */ - if (READ_ONCE(si->inuse_pages)) { + if (swap_usage_in_pages(si)) { if (!signal_pending(current)) goto retry; return -EINTR; @@ -2209,7 +2295,7 @@ static int try_to_unuse(unsigned int type) success: /* * Make sure that further cleanups after try_to_unuse() returns happen - * after swap_range_free() reduces si->inuse_pages to 0. + * after swap_range_free() reduces inuse_pages to 0. */ smp_mb(); return 0; @@ -2227,7 +2313,7 @@ static void drain_mmlist(void) unsigned int type; =20 for (type =3D 0; type < nr_swapfiles; type++) - if (swap_info[type]->inuse_pages) + if (swap_usage_in_pages(swap_info[type])) return; spin_lock(&mmlist_lock); list_for_each_safe(p, next, &init_mm.mmlist) @@ -2406,7 +2492,6 @@ static void setup_swap_info(struct swap_info_struct *= si, int prio, =20 static void _enable_swap_info(struct swap_info_struct *si) { - si->flags |=3D SWP_WRITEOK; atomic_long_add(si->pages, &nr_swap_pages); total_swap_pages +=3D si->pages; =20 @@ -2423,9 +2508,8 @@ static void _enable_swap_info(struct swap_info_struct= *si) */ plist_add(&si->list, &swap_active_head); =20 - /* add to available list if swap device is not full */ - if (si->inuse_pages < si->pages) - add_to_avail_list(si); + /* Add back to available list */ + add_to_avail_list(si, true); } =20 static void enable_swap_info(struct swap_info_struct *si, int prio, @@ -2523,7 +2607,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) goto out_dput; } spin_lock(&p->lock); - del_from_avail_list(p); + del_from_avail_list(p, true); if (p->prio < 0) { struct swap_info_struct *si =3D p; int nid; @@ -2541,7 +2625,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) plist_del(&p->list, &swap_active_head); atomic_long_sub(p->pages, &nr_swap_pages); total_swap_pages -=3D p->pages; - p->flags &=3D ~SWP_WRITEOK; spin_unlock(&p->lock); spin_unlock(&swap_lock); =20 @@ -2721,7 +2804,7 @@ static int swap_show(struct seq_file *swap, void *v) } =20 bytes =3D K(si->pages); - inuse =3D K(READ_ONCE(si->inuse_pages)); + inuse =3D K(swap_usage_in_pages(si)); =20 file =3D si->swap_file; len =3D seq_file_path(swap, file, " \t\n\\"); @@ -2838,6 +2921,7 @@ static struct swap_info_struct *alloc_swap_info(void) } spin_lock_init(&p->lock); spin_lock_init(&p->cont_lock); + atomic_long_set(&p->inuse_pages, SWAP_USAGE_OFFLIST_BIT); init_completion(&p->comp); =20 return p; @@ -3335,7 +3419,7 @@ void si_swapinfo(struct sysinfo *val) struct swap_info_struct *si =3D swap_info[type]; =20 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK)) - nr_to_be_unused +=3D READ_ONCE(si->inuse_pages); + nr_to_be_unused +=3D swap_usage_in_pages(si); } val->freeswap =3D atomic_long_read(&nr_swap_pages) + nr_to_be_unused; val->totalswap =3D total_swap_pages + nr_to_be_unused; --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f182.google.com (mail-pl1-f182.google.com [209.85.214.182]) (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 A7A8D1D8DE1 for ; Tue, 24 Dec 2024 14:39:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051200; cv=none; b=iAXHU7K6oFLMiduqmmEpJqHOgOXxU2lY+sxtkI4o3Z6YaTrg4I5QQRA80+emSwY0ju90yQK+vC3Qp2/9+noCyPlUVt9+2pcDnGYFAvZGslF8TvGaVNRApAiXlHXQaBXehIJxO7nERoc9bivEdGK1c5LNPIIB76IEUABvihzjhes= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051200; c=relaxed/simple; bh=dKGm1GuCRiWTfxKsd/z6BiVWR7Z0xgv3xtT3S1va8hk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=nOH8PCBfAzTpc0gUMPZP6AzkMhXV6sghedUBWrrFFvrg3CGJHGhglhX1OCWoDZyQr6LfnQ+iVvM+8pOQpm/cWgOB/7uGE3bKTHq5fn8LKoUap+WIc2o8If+phTFOONS6cpPuVUwAUzyPRDLlCxNoiYCuabI/soE4Pp8Lg+t2Zwk= 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=l1djGjqb; arc=none smtp.client-ip=209.85.214.182 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="l1djGjqb" Received: by mail-pl1-f182.google.com with SMTP id d9443c01a7336-216426b0865so52320905ad.0 for ; Tue, 24 Dec 2024 06:39:58 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051198; x=1735655998; 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=9HF1qACSod1kWAoA/COSAk5nfGEmiGZxS1K9zisyvtY=; b=l1djGjqbK9CqOwUhl3nasjT2Zp5/m7GIJowgi3SLYAzzskW9GJ1V9lBFuLpBbGbb1t peYKsRC5oianuLB+KAF0BQyABaQdZsqIWiyhhHaHKY3VqxXwXP4kYxNCO6R940JUE0qA +1u3QQhS77AqxpeFqzSDvKdDUhze7ArSDofKR66AsYLPJEYd6xCWDIEh7l5DspV1jnVu /BysEfzneYEQdqDJ/H7CejL/Qen/6R7K5BmxWUrVExycQSxycRNuv7ImEsVPWgct3pzC WIWEzg4b/1MQUTQG1oRdf2X0c0YTz364621qCnF7pXDZIqvrLpAXhthmBTmuPgYajJff Oo2Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051198; x=1735655998; 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=9HF1qACSod1kWAoA/COSAk5nfGEmiGZxS1K9zisyvtY=; b=sHXPY8+/SjJSVQAJUXhqTjX0SIxiA1tQ8xHUzuT7O3eLxsR5ZplbNMzIT6+Zw8feQh FP0iw42N0UGphu27nquaEX4AmtdRZg890FFnFOJ7D0B1uE5kzFW21VPgfLzrbNRi04nf Nkuwmb36zD/h8lzzjA/Hh4dWlUGFW2X49+6kiuzJ70FBepQCUjwYyleJjW/C8t4Nh2VR KmdmUyUyMzTlaTDiQE6vUqfk27d8M521vKOHetAqbM+Dy6FcosjfM8H/fSVhn2FSoUbI n+eza5Yt9plBojVd/9UwMk7yNINOXZ7693k6IIglDFzordSR/DCoL5PgE84I2UHmJpSk hNUQ== X-Forwarded-Encrypted: i=1; AJvYcCXOIsRm7wYh+kBy8Ol/hQmKk5FX+rOKaIX7ouLY9TjMCSy0nvNELz3Bfsq62vtIm5DNXzzugsrAlAsu0Q8=@vger.kernel.org X-Gm-Message-State: AOJu0YybgjZowMH7ZIIQB9S4h+2oetJVg5CEzRit6EgBmQJsm24608s7 rSQ0Lk7xayW6JlgxLkKtt5bsUhrH0gPniyrcSZfHRJGWyG2kKhQG8/1tKzD7bG0= X-Gm-Gg: ASbGnctMGf5QBsDl9TJt/oKCk40aFZcdiAJ1Hp3qzC7Y4tUNf1ciqDtkli5kNp6X3zK vSmCG05WYFjwmZdYuhgWeXEsKlVOUOcsYiIyB0D/fhUYHcClagEznoxZg70OGYZcJLUj5yusfpl /zaiQwsuek7R22JdSzI8D4J+3DnFCQtg4Z0fedwGRWBtfE+hXy2woBOZR7Y6i7rCLvbMf/qUbAn Quqyf7/Wiu0ZTNhSS2mb0LkuQcBJa3JPPuvG8BUnABdu8Y2/0lH0vCrf1x1ZIBWMSwAolPLnnda ug== X-Google-Smtp-Source: AGHT+IG6ErdK7jWxaeL/lueO5nmWZSFVm6gM6DX2BhsbGjPUTsi72O0feo489S4NIqCP9JZBLNzB4w== X-Received: by 2002:a17:903:182:b0:216:4943:e575 with SMTP id d9443c01a7336-219e6f28547mr173619465ad.57.1735051198014; Tue, 24 Dec 2024 06:39:58 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.54 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:39:57 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 07/13] mm, swap: hold a reference during scan and cleanup flag usage Date: Tue, 24 Dec 2024 22:38:05 +0800 Message-ID: <20241224143811.33462-8-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 flag SWP_SCANNING was used as an indicator of whether a device is being scanned for allocation, and prevents swapoff. Combined with SWP_WRITEOK, they work as a set of barriers for a clean swapoff: 1. Swapoff clears SWP_WRITEOK, allocation requests will see ~SWP_WRITEOK and abort as it's serialized by si->lock. 2. Swapoff unuses all allocated entries. 3. Swapoff waits for SWP_SCANNING flag to be cleared, so ongoing allocations will stop, preventing UAF. 4. Now swapoff can free everything safely. This will make the allocation path have a hard dependency on si->lock. Allocation always have to acquire si->lock first for setting SWP_SCANNING and checking SWP_WRITEOK. This commit removes this flag, and just uses the existing per-CPU refcount instead to prevent UAF in step 3, which serves well for such usage without dependency on si->lock, and scales very well too. Just hold a reference during the whole scan and allocation process. Swapoff will kill and wait for the counter. And for preventing any allocation from happening after step 1 so the unuse in step 2 can ensure all slots are free, swapoff will acquire the ci->lock of each cluster one by one to ensure all allocations see ~SWP_WRITEOK and abort. This way these dependences on si->lock are gone. And worth noting we can't kill the refcount as the first step for swapoff as the unuse process have to acquire the refcount. Signed-off-by: Kairui Song Suggested-by: Chris Li --- include/linux/swap.h | 1 - mm/swapfile.c | 90 ++++++++++++++++++++++++++++---------------- 2 files changed, 57 insertions(+), 34 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index e1eeea6307cd..02120f1005d5 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -219,7 +219,6 @@ enum { SWP_STABLE_WRITES =3D (1 << 11), /* no overwrite PG_writeback pages */ SWP_SYNCHRONOUS_IO =3D (1 << 12), /* synchronous IO is efficient */ /* add others here before... */ - SWP_SCANNING =3D (1 << 14), /* refcount in scan_swap_map */ }; =20 #define SWAP_CLUSTER_MAX 32UL diff --git a/mm/swapfile.c b/mm/swapfile.c index ae0f7df06474..0abff343f5f0 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -658,6 +658,8 @@ static bool cluster_alloc_range(struct swap_info_struct= *si, struct swap_cluster { unsigned int nr_pages =3D 1 << order; =20 + lockdep_assert_held(&ci->lock); + if (!(si->flags & SWP_WRITEOK)) return false; =20 @@ -1055,8 +1057,6 @@ static int cluster_alloc_swap(struct swap_info_struct= *si, { int n_ret =3D 0; =20 - si->flags +=3D SWP_SCANNING; - while (n_ret < nr) { unsigned long offset =3D cluster_alloc_swap_entry(si, order, usage); =20 @@ -1065,8 +1065,6 @@ static int cluster_alloc_swap(struct swap_info_struct= *si, slots[n_ret++] =3D swp_entry(si->type, offset); } =20 - si->flags -=3D SWP_SCANNING; - return n_ret; } =20 @@ -1108,6 +1106,22 @@ static int scan_swap_map_slots(struct swap_info_stru= ct *si, return cluster_alloc_swap(si, usage, nr, slots, order); } =20 +static bool get_swap_device_info(struct swap_info_struct *si) +{ + if (!percpu_ref_tryget_live(&si->users)) + return false; + /* + * Guarantee the si->users are checked before accessing other + * fields of swap_info_struct, and si->flags (SWP_WRITEOK) is + * up to dated. + * + * Paired with the spin_unlock() after setup_swap_info() in + * enable_swap_info(), and smp_wmb() in swapoff. + */ + smp_rmb(); + return true; +} + int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_order) { int order =3D swap_entry_order(entry_order); @@ -1135,13 +1149,16 @@ int get_swap_pages(int n_goal, swp_entry_t swp_entr= ies[], int entry_order) /* requeue si to after same-priority siblings */ plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]); spin_unlock(&swap_avail_lock); - spin_lock(&si->lock); - n_ret =3D scan_swap_map_slots(si, SWAP_HAS_CACHE, - n_goal, swp_entries, order); - spin_unlock(&si->lock); - if (n_ret || size > 1) - goto check_out; - cond_resched(); + if (get_swap_device_info(si)) { + spin_lock(&si->lock); + n_ret =3D scan_swap_map_slots(si, SWAP_HAS_CACHE, + n_goal, swp_entries, order); + spin_unlock(&si->lock); + put_swap_device(si); + if (n_ret || size > 1) + goto check_out; + cond_resched(); + } =20 spin_lock(&swap_avail_lock); /* @@ -1292,16 +1309,8 @@ struct swap_info_struct *get_swap_device(swp_entry_t= entry) si =3D swp_swap_info(entry); if (!si) goto bad_nofile; - if (!percpu_ref_tryget_live(&si->users)) + if (!get_swap_device_info(si)) goto out; - /* - * Guarantee the si->users are checked before accessing other - * fields of swap_info_struct. - * - * Paired with the spin_unlock() after setup_swap_info() in - * enable_swap_info(). - */ - smp_rmb(); offset =3D swp_offset(entry); if (offset >=3D si->max) goto put_out; @@ -1781,10 +1790,13 @@ swp_entry_t get_swap_page_of_type(int type) goto fail; =20 /* This is called for allocating swap entry, not cache */ - spin_lock(&si->lock); - if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry, 0)) - atomic_long_dec(&nr_swap_pages); - spin_unlock(&si->lock); + if (get_swap_device_info(si)) { + spin_lock(&si->lock); + if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry, 0= )) + atomic_long_dec(&nr_swap_pages); + spin_unlock(&si->lock); + put_swap_device(si); + } fail: return entry; } @@ -2558,6 +2570,25 @@ bool has_usable_swap(void) return ret; } =20 +/* + * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range + * see the updated flags, so there will be no more allocations. + */ +static void wait_for_allocation(struct swap_info_struct *si) +{ + unsigned long offset; + unsigned long end =3D ALIGN(si->max, SWAPFILE_CLUSTER); + struct swap_cluster_info *ci; + + BUG_ON(si->flags & SWP_WRITEOK); + + for (offset =3D 0; offset < end; offset +=3D SWAPFILE_CLUSTER) { + ci =3D lock_cluster(si, offset); + unlock_cluster(ci); + offset +=3D SWAPFILE_CLUSTER; + } +} + SYSCALL_DEFINE1(swapoff, const char __user *, specialfile) { struct swap_info_struct *p =3D NULL; @@ -2628,6 +2659,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) spin_unlock(&p->lock); spin_unlock(&swap_lock); =20 + wait_for_allocation(p); + disable_swap_slots_cache_lock(); =20 set_current_oom_origin(); @@ -2670,15 +2703,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specia= lfile) spin_lock(&p->lock); drain_mmlist(); =20 - /* wait for anyone still in scan_swap_map_slots */ - while (p->flags >=3D SWP_SCANNING) { - spin_unlock(&p->lock); - spin_unlock(&swap_lock); - schedule_timeout_uninterruptible(1); - spin_lock(&swap_lock); - spin_lock(&p->lock); - } - swap_file =3D p->swap_file; p->swap_file =3D NULL; p->max =3D 0; --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f181.google.com (mail-pl1-f181.google.com [209.85.214.181]) (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 98E1F1DCB09 for ; Tue, 24 Dec 2024 14:40:02 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.181 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051204; cv=none; b=afn8+7dW+CH3BcI2dq5LC7Z1q86eRQ1uxpBshkJU/EoZx78YQFcqxObWwnYT4pd7krhTWS03npx+dK28k/gKQsTIL/ltzh4jrRYFB1KWmU9tFa+WMwZZrrsf5R0ynlvOL/fm4m9SwMhLkzFH1wToXvVdYMKZkxpaPDeFJzzhSD4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051204; c=relaxed/simple; bh=bfRIZoiLDC7uYJuWQ2h/8jbX6KyOpRKVXb8/AWIs2yU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=sASb6RV+MECNVRejQ6Op/KT/78BFgVsDKRWCMJJgj0CMNE5asvhIm1aV9PiXhAunKgbmgjzW7Wl+GdjVQYUJ9jkjbCKUr88L270qPtOj57Xdun2ZA+UdkM5EBAoJA1CD2+VKTUMXCsnYgCgRQVngPKzZqQ9rqU0v2NJ66taXZRE= 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=cKEofLKy; arc=none smtp.client-ip=209.85.214.181 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="cKEofLKy" Received: by mail-pl1-f181.google.com with SMTP id d9443c01a7336-216281bc30fso62090015ad.0 for ; Tue, 24 Dec 2024 06:40:02 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051202; x=1735656002; 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=x1wPQexfBO4aVb9VNyBG+dw97Ap+sARYAr0a6bgjO1Q=; b=cKEofLKyaNTSSEqdFN0laXuaRLG9DUcb4AQVsWP1e9iHwML5bChOhpWYPNf6B4lDIr bskEUJKAPlBmwyMMTOPV1B5dQd83hnguMRqOvd+MttW5ub00MsnLgqMkidTFzdyPrWCo IAROdfne3DfQkBMkMXUWXkQK5SnQFliRR51mO5SC3XC5j6CHDCJMsRZL0nbOQQa/zEXZ 5HG1FF20O5S42TasgPZ2VR1iz391ccZ+oQyKnSGjmRhN4kqZmbmSKeKWcyZahYN/Tkbt jiJzsUZ4U6P+/VxEFyQI2D9QZxcdSMfnY8Xj+HDTVdaZ9jOnBxgpvhxjvZZZrH9WNmFh 5stw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051202; x=1735656002; 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=x1wPQexfBO4aVb9VNyBG+dw97Ap+sARYAr0a6bgjO1Q=; b=YvISBnSv3WwX7Knxxiai4rNTHQKZ45DiospxdO2mC8h9SfmpkSWPgG5e/MSvnpNTva ZkG5gR0NBL6FMHHAe6QcpZF+r65ipCOsnMKZL3+S6HiN8a4DSxh/gQNnCo3n4YhmSpHz 6DhnWWkrV0zHbOb06r/NCTZq2mw4YatnOu7c+C1s1fqfv3QHlMr/ZeoRoJCiOPPa52ro B15ZPrQxVp9i2AMQBf/Za2BgXBWFyAdJ68hqZK9qv8jY58m8N1SC48wG/TfcxekUSEYn ObDtskViIoGALxCBfWoFWZZZzmVMWbwyk28NuwXWWd3DoGbDUJi65B9WKlMSYQG0y3o5 cd1g== X-Forwarded-Encrypted: i=1; AJvYcCXUQxEWu68CFzIHwjaepwHVYHmblctDA4a4+MfhC5qBr1/ArZ6Gnv4MF8RuNXZdmtM5ORcDCtwz5Oqy5Z4=@vger.kernel.org X-Gm-Message-State: AOJu0Yx8xZ2TzjqWy87JC1k5/euetL4IZXSJUfKb3QwW/c9n0X57K+cO RCMxR6phLpf2gVYaLoIzzGcg0vOIuXrlvFkvnhfzhV2f0qgLzogiIaMVvJyPlNE= X-Gm-Gg: ASbGncvi6KnLXHsGShyzVroXsX2cYbWO/kprEMTamm1xuFY7NbjGYVje4QuExYiTDhr syMiCj9O55eRtX1XeUykToH6OljqXWNi+YucXPM3X1MVmhTPB8tLzZqCGmWvrls0JJvhxwqTCQY uJlELiedMtd2zv0XnJzWfyc40K5a88LZvN4W+92gcaJGVIWVm8eiTLBNAL6emf4MYW2I+1U3fnJ aJmHC9ctzp2vudN0LwavC3dbN4JyQkIMoxTJ5EZBeEzp6e9jnNZo4e1SyjEv+3Qbgb1ZtDxvnbi uQ== X-Google-Smtp-Source: AGHT+IEysBcICmtcsLy08l3mcesaPslPW6JfCL1D4WCO+ovHstzHh+/6NlLWVBwW4F+V5pf421KQkA== X-Received: by 2002:a17:903:1105:b0:215:a3fb:b4d6 with SMTP id d9443c01a7336-219e6e8c5a0mr250562295ad.8.1735051201813; Tue, 24 Dec 2024 06:40:01 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.39.58 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:40:01 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 08/13] mm, swap: use an enum to define all cluster flags and wrap flags changes Date: Tue, 24 Dec 2024 22:38:06 +0800 Message-ID: <20241224143811.33462-9-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 Currently, we are only using flags to indicate which list the cluster is on. Using one bit for each list type might be a waste, as the list type grows, we will consume too many bits. Additionally, the current mixed usage of '&' and '=3D=3D' is a bit confusing. Make it clean by using an enum to define all possible cluster statuses. Only an off-list cluster will have the NONE (0) flag. And use a wrapper to annotate and sanitize all flag settings and list movements. Suggested-by: Chris Li Signed-off-by: Kairui Song --- include/linux/swap.h | 17 +++++++--- mm/swapfile.c | 75 +++++++++++++++++++++++--------------------- 2 files changed, 52 insertions(+), 40 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 02120f1005d5..339d7f0192ff 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -257,10 +257,19 @@ struct swap_cluster_info { u8 order; struct list_head list; }; -#define CLUSTER_FLAG_FREE 1 /* This cluster is free */ -#define CLUSTER_FLAG_NONFULL 2 /* This cluster is on nonfull list */ -#define CLUSTER_FLAG_FRAG 4 /* This cluster is on nonfull list */ -#define CLUSTER_FLAG_FULL 8 /* This cluster is on full 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, +}; =20 /* * The first page in the swap file is the swap header, which is always mar= ked diff --git a/mm/swapfile.c b/mm/swapfile.c index 0abff343f5f0..be2c719a51bb 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -403,7 +403,7 @@ static void discard_swap_cluster(struct swap_info_struc= t *si, =20 static inline bool cluster_is_free(struct swap_cluster_info *info) { - return info->flags & CLUSTER_FLAG_FREE; + return info->flags =3D=3D CLUSTER_FLAG_FREE; } =20 static inline unsigned int cluster_index(struct swap_info_struct *si, @@ -434,6 +434,27 @@ static inline void unlock_cluster(struct swap_cluster_= info *ci) spin_unlock(&ci->lock); } =20 +static void cluster_move(struct swap_info_struct *si, + struct swap_cluster_info *ci, struct list_head *list, + enum swap_cluster_flags new_flags) +{ + VM_WARN_ON(ci->flags =3D=3D new_flags); + BUILD_BUG_ON(1 << sizeof(ci->flags) * BITS_PER_BYTE < CLUSTER_FLAG_MAX); + + if (ci->flags =3D=3D CLUSTER_FLAG_NONE) { + list_add_tail(&ci->list, list); + } else { + if (ci->flags =3D=3D CLUSTER_FLAG_FRAG) { + VM_WARN_ON(!si->frag_cluster_nr[ci->order]); + si->frag_cluster_nr[ci->order]--; + } + list_move_tail(&ci->list, list); + } + ci->flags =3D new_flags; + if (new_flags =3D=3D CLUSTER_FLAG_FRAG) + si->frag_cluster_nr[ci->order]++; +} + /* Add a cluster to discard list and schedule it to do discard */ static void swap_cluster_schedule_discard(struct swap_info_struct *si, struct swap_cluster_info *ci) @@ -447,10 +468,8 @@ static void swap_cluster_schedule_discard(struct swap_= info_struct *si, */ memset(si->swap_map + idx * SWAPFILE_CLUSTER, SWAP_MAP_BAD, SWAPFILE_CLUSTER); - - VM_BUG_ON(ci->flags & CLUSTER_FLAG_FREE); - list_move_tail(&ci->list, &si->discard_clusters); - ci->flags =3D 0; + VM_BUG_ON(ci->flags =3D=3D CLUSTER_FLAG_FREE); + cluster_move(si, ci, &si->discard_clusters, CLUSTER_FLAG_DISCARD); schedule_work(&si->discard_work); } =20 @@ -458,12 +477,7 @@ static void __free_cluster(struct swap_info_struct *si= , struct swap_cluster_info { lockdep_assert_held(&si->lock); lockdep_assert_held(&ci->lock); - - if (ci->flags) - list_move_tail(&ci->list, &si->free_clusters); - else - list_add_tail(&ci->list, &si->free_clusters); - ci->flags =3D CLUSTER_FLAG_FREE; + cluster_move(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); ci->order =3D 0; } =20 @@ -479,6 +493,8 @@ static void swap_do_scheduled_discard(struct swap_info_= struct *si) while (!list_empty(&si->discard_clusters)) { ci =3D list_first_entry(&si->discard_clusters, struct swap_cluster_info,= list); list_del(&ci->list); + /* Must clear flag when taking a cluster off-list */ + ci->flags =3D CLUSTER_FLAG_NONE; idx =3D cluster_index(si, ci); spin_unlock(&si->lock); =20 @@ -519,9 +535,6 @@ static void free_cluster(struct swap_info_struct *si, s= truct swap_cluster_info * lockdep_assert_held(&si->lock); lockdep_assert_held(&ci->lock); =20 - if (ci->flags & CLUSTER_FLAG_FRAG) - si->frag_cluster_nr[ci->order]--; - /* * If the swap is discardable, prepare discard the cluster * instead of free it immediately. The cluster will be freed @@ -573,13 +586,9 @@ static void dec_cluster_info_page(struct swap_info_str= uct *si, return; } =20 - if (!(ci->flags & CLUSTER_FLAG_NONFULL)) { - VM_BUG_ON(ci->flags & CLUSTER_FLAG_FREE); - if (ci->flags & CLUSTER_FLAG_FRAG) - si->frag_cluster_nr[ci->order]--; - list_move_tail(&ci->list, &si->nonfull_clusters[ci->order]); - ci->flags =3D CLUSTER_FLAG_NONFULL; - } + if (ci->flags !=3D CLUSTER_FLAG_NONFULL) + cluster_move(si, ci, &si->nonfull_clusters[ci->order], + CLUSTER_FLAG_NONFULL); } =20 static bool cluster_reclaim_range(struct swap_info_struct *si, @@ -663,11 +672,13 @@ static bool cluster_alloc_range(struct swap_info_stru= ct *si, struct swap_cluster if (!(si->flags & SWP_WRITEOK)) return false; =20 + VM_BUG_ON(ci->flags =3D=3D CLUSTER_FLAG_NONE); + VM_BUG_ON(ci->flags > CLUSTER_FLAG_USABLE); + if (cluster_is_free(ci)) { - if (nr_pages < SWAPFILE_CLUSTER) { - list_move_tail(&ci->list, &si->nonfull_clusters[order]); - ci->flags =3D CLUSTER_FLAG_NONFULL; - } + if (nr_pages < SWAPFILE_CLUSTER) + cluster_move(si, ci, &si->nonfull_clusters[order], + CLUSTER_FLAG_NONFULL); ci->order =3D order; } =20 @@ -675,14 +686,8 @@ static bool cluster_alloc_range(struct swap_info_struc= t *si, struct swap_cluster swap_range_alloc(si, nr_pages); ci->count +=3D nr_pages; =20 - if (ci->count =3D=3D SWAPFILE_CLUSTER) { - VM_BUG_ON(!(ci->flags & - (CLUSTER_FLAG_FREE | CLUSTER_FLAG_NONFULL | CLUSTER_FLAG_FRAG))); - if (ci->flags & CLUSTER_FLAG_FRAG) - si->frag_cluster_nr[ci->order]--; - list_move_tail(&ci->list, &si->full_clusters); - ci->flags =3D CLUSTER_FLAG_FULL; - } + if (ci->count =3D=3D SWAPFILE_CLUSTER) + cluster_move(si, ci, &si->full_clusters, CLUSTER_FLAG_FULL); =20 return true; } @@ -821,9 +826,7 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o while (!list_empty(&si->nonfull_clusters[order])) { ci =3D list_first_entry(&si->nonfull_clusters[order], struct swap_cluster_info, list); - list_move_tail(&ci->list, &si->frag_clusters[order]); - ci->flags =3D CLUSTER_FLAG_FRAG; - si->frag_cluster_nr[order]++; + cluster_move(si, ci, &si->frag_clusters[order], CLUSTER_FLAG_FRAG); offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), &found, order, usage); frags++; --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f169.google.com (mail-pl1-f169.google.com [209.85.214.169]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E79B61DDA2D for ; Tue, 24 Dec 2024 14:40:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.169 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051210; cv=none; b=rnhp0bBJ39Dg4k05WOvK70yZql1H9XG5aZElwnemrOy+ym3guDitTIqtIs2vCGZoqyNeGXjvozlZhWBS/lfUH7SeEyI0M7NrgKvDTL5RaPBwcfCsxc+fDRVTDGKLjh0Pw9usYx2/99zGt2JHQTV73R1kATM0EziQOaNTUJDti1g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051210; c=relaxed/simple; bh=veb+H/dtzZLQPrqXuGv3kDR1KJ5e6SDHNBH+nXhi6Qg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=kTMkzp4DwhQ4hhxdwJ3ajoIr3juIXlutt7cConY5YdgIWcHHQxTuXGSYp/JylVGyf1T7wUw3bl5zn41OrIHiJWJ9UjQaTYWhRsBvPNRAhRVAWIQrDeVgCjbW9fXXeWZPbOGqhlTRrqfTMnjoa9MwGkt3pp+CQV7LHmyKzVC72K0= 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=TqDOz8FO; arc=none smtp.client-ip=209.85.214.169 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="TqDOz8FO" Received: by mail-pl1-f169.google.com with SMTP id d9443c01a7336-2166360285dso54010805ad.1 for ; Tue, 24 Dec 2024 06:40:07 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051207; x=1735656007; 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=ME3+zD7lj7HjkKMbVGqaEWjurYQ2nckLRVsGy7KATEg=; b=TqDOz8FOFl46yhiOSlarR5zSoEQ9o3vcIyA4BmRmJB/vAyvvsgkK439PJ/nbjgyl7r 2siyQ6Hjt2qhAObJ2iGDsQY2zeHbr+xqm/iYNQsfMQWOV9Db+cjjsLKis+ywVWwAyLad JOg0YhwUU3EoSnDElIMMou0Vk65iVex70TvOGyJyGsbvqh1hURjab7GKeIPIlWbU2O7e k8ox80ZuY+F5Iva/vKJepoV2SF0eyWF1t91CIf7KNxt20M1x4fRaMDiHfqMe2TnPQ8H3 b3Ba/MNsseUdr1bybgRcFgqJp/JyPR6YWtpCuVet1uygL0s/L9ZumNNwRjsnsn/MEbOh 1kFw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051207; x=1735656007; 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=ME3+zD7lj7HjkKMbVGqaEWjurYQ2nckLRVsGy7KATEg=; b=lP6PtKy1WEQoW68DofF3WveFyYHdA93HFZn9fyTKWw2YjMmmBP+72zRH1OG5+i3Pmo ptulieJZRAo4tlSZ/wIHy7jVJ+AaQivexUpS0IWhgMUN0csS5+XLcArSW/nUEN5p5VbV bTCW+HHF5udtJannmwmS/UQEXN5tYBNEcRK/EqpIXkUR15yILqQfesxJjsusae4WTvWb 7L97HndWleJR0v6bbATniQJylU9MXdi5J8a014caoV+J10xadAhCPHqKCU7sVUtMeU8E R42Sl0thRzV2ML/ESfjAE62/LzkKPGCUTAwZYT/rDTBK/GZ133KXpi4J9COr3uLSnEnO E26g== X-Forwarded-Encrypted: i=1; AJvYcCUMh5DPkow/FZomq1dkwHBIDhBHdNgt2Y8st9EI52pazFkYxnniq7b+5Gknv7tkEpLRW2WvCcAac68ToLM=@vger.kernel.org X-Gm-Message-State: AOJu0YzW0P4gKfhft4Z7v+jME8KbbC3S6kcfK8LC/7jQWcFjsuBZioXT 32SWZYgBYjY+yatCYbrwFH12VTiZPZPLSmdbtO3fHc/pgcpm69Qa X-Gm-Gg: ASbGncuL8HXJZjYXN8DcMbCf7h2qZT0sjKQevjrUWr16wEdW0uBeYe666HcrWbNchIl btBXemuR8yycuAjHWd4AEIo2Wi36E4IXULvFQXbsp4hyD2JuaWd4OCXoo+76svV8yodlZlK8puG VsmggfzpzNkeKslH/F+a3EYN/wzMcljLDfFWz1yX/5Kk3ETIFpcqMJlXW4KL9emnOfAUoEuj5Cw L/E0FsmoSlJ3lnXZe16wYx9sxqYDmuz0TGT0hxf+nsbQip0Y55e1WssUki+rRNRUPtUyDevxoeQ 6g== X-Google-Smtp-Source: AGHT+IEJmuSwenPjD3zFn8/72DrjxeSYMyc/SNGORcCuKwsk9/ba5LKYVBZqu+p5nbj2Buyvuo+UkA== X-Received: by 2002:a17:902:d2cc:b0:216:70b6:8723 with SMTP id d9443c01a7336-219e6f1090dmr233491155ad.44.1735051207001; Tue, 24 Dec 2024 06:40:07 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.40.02 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:40:06 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 09/13] mm, swap: reduce contention on device lock Date: Tue, 24 Dec 2024 22:38:07 +0800 Message-ID: <20241224143811.33462-10-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 Currently, swap locking is mainly composed of two locks: the cluster lock (ci->lock) and the device lock (si->lock). The cluster lock is much more fine-grained, so it is best to use ci->lock instead of si->lock as much as possible. We have cleaned up other hard dependencies on si->lock. Following the new cluster allocator design, most operations don't need to touch si->lock at all. In practice, we only need to take si->lock when moving clusters between lists. To achieve this, this commit reworks the locking pattern of all si->lock and ci->lock users, eliminates all usage of ci->lock inside si->lock, and introduces a new design to avoid touching si->lock unless needed. For minimal contention and easier understanding of the system, two ideas are introduced with the corresponding helpers: isolation and relocation. - Clusters will be `isolated` from the list when iterating the list to search for an allocatable cluster. This ensures other CPUs won't walk into the same cluster easily, and it releases si->lock after acquiring ci->lock, providing the only place that handles the inversion of two locks, and avoids contention. Iterating the cluster list almost always moves the cluster (free -> nonfull, nonfull -> frag, frag -> frag tail), but it doesn't know where the cluster should be moved to until scanning is done. So keeping the cluster off-list is a good option with low overhead. The off-list time window of a cluster is also minimal. In the worst case, one CPU will return the cluster after scanning the 512 entries on it, which we used to busy wait with a spin lock. This is done with the new helper `cluster_isolate_lock`. - Clusters will be `relocated` after allocation or freeing, according to their usage count and status. Allocations no longer hold si->lock now, and may drop ci->lock for reclaim, so the cluster could be moved to any location while no lock is held. Besides, isolation clears all flags when it takes the cluster off the list (the flags must be in sync with the list status, so cluster users don't need to touch si->lock for checking its list status). So the cluster has to be relocated to the right list according to its usage after allocation or freeing. Relocation is optional, if the cluster flags indicate it's already on the right list, it will skip touching the list or si->lock. This is done with relocate_cluster after allocation or with [partial_]free_cluster after freeing. This handled usage of all kinds of clusters in a clean way. Scanning and allocation by iterating the cluster list is handled by "isolate - - relocate". Scanning and allocation of per-CPU clusters will only involve " - relocate", as it knows which cluster to lock and use. Freeing will only involve "relocate". Each CPU will keep using its per-CPU cluster until the 512 entries are all consumed. Freeing also has to free 512 entries to trigger cluster movement in the best case, so si->lock is rarely touched. Testing with building the Linux kernel with defconfig showed huge improvement: tiem make -j96 / 768M memcg, 4K pages, 10G ZRAM, on Intel 8255C: Before: Sys time: 73578.30, Real time: 864.05 After: (-50.7% sys time, -44.8% real time) Sys time: 36227.49, Real time: 476.66 time make -j96 / 1152M memcg, 64K mTHP, 10G ZRAM, on Intel 8255C: (avg of 4 test run) Before: Sys time: 74044.85, Real time: 846.51 hugepages-64kB/stats/swpout: 1735216 hugepages-64kB/stats/swpout_fallback: 430333 After: (-40.4% sys time, -37.1% real time) Sys time: 44160.56, Real time: 532.07 hugepages-64kB/stats/swpout: 1786288 hugepages-64kB/stats/swpout_fallback: 243384 time make -j32 / 512M memcg, 4K pages, 5G ZRAM, on AMD 7K62: Before: Sys time: 8098.21, Real time: 401.3 After: (-22.6% sys time, -12.8% real time ) Sys time: 6265.02, Real time: 349.83 The allocation success rate also slightly improved as we sanitized the usage of clusters with new defined helpers, previously dropping si->lock or ci->lock during scan will cause cluster order shuffle. Suggested-by: Chris Li Signed-off-by: Kairui Song --- include/linux/swap.h | 3 +- mm/swapfile.c | 435 ++++++++++++++++++++++++------------------- 2 files changed, 246 insertions(+), 192 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 339d7f0192ff..c4ff31cb6bde 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -291,6 +291,7 @@ enum swap_cluster_flags { * throughput. */ struct percpu_cluster { + local_lock_t lock; /* Protect the percpu_cluster above */ unsigned int next[SWAP_NR_ORDERS]; /* Likely next allocation offset */ }; =20 @@ -313,7 +314,7 @@ struct swap_info_struct { /* list of cluster that contains at least one free slot */ struct list_head frag_clusters[SWAP_NR_ORDERS]; /* list of cluster that are fragmented or contented */ - unsigned int frag_cluster_nr[SWAP_NR_ORDERS]; + atomic_long_t frag_cluster_nr[SWAP_NR_ORDERS]; unsigned int pages; /* total of usable pages of swap */ atomic_long_t inuse_pages; /* number of those currently in use */ struct percpu_cluster __percpu *percpu_cluster; /* per cpu's swap locatio= n */ diff --git a/mm/swapfile.c b/mm/swapfile.c index be2c719a51bb..bb1ef9192d99 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -261,12 +261,10 @@ static int __try_to_reclaim_swap(struct swap_info_str= uct *si, folio_ref_sub(folio, nr_pages); folio_set_dirty(folio); =20 - spin_lock(&si->lock); /* Only sinple page folio can be backed by zswap */ if (nr_pages =3D=3D 1) zswap_invalidate(entry); swap_entry_range_free(si, entry, nr_pages); - spin_unlock(&si->lock); ret =3D nr_pages; out_unlock: folio_unlock(folio); @@ -403,7 +401,21 @@ static void discard_swap_cluster(struct swap_info_stru= ct *si, =20 static inline bool cluster_is_free(struct swap_cluster_info *info) { - return info->flags =3D=3D CLUSTER_FLAG_FREE; + return info->count =3D=3D 0; +} + +static inline bool cluster_is_discard(struct swap_cluster_info *info) +{ + return info->flags =3D=3D CLUSTER_FLAG_DISCARD; +} + +static inline bool cluster_is_usable(struct swap_cluster_info *ci, int ord= er) +{ + if (unlikely(ci->flags > CLUSTER_FLAG_USABLE)) + return false; + if (!order) + return true; + return cluster_is_free(ci) || order =3D=3D ci->order; } =20 static inline unsigned int cluster_index(struct swap_info_struct *si, @@ -440,19 +452,20 @@ static void cluster_move(struct swap_info_struct *si, { VM_WARN_ON(ci->flags =3D=3D new_flags); BUILD_BUG_ON(1 << sizeof(ci->flags) * BITS_PER_BYTE < CLUSTER_FLAG_MAX); + lockdep_assert_held(&ci->lock); =20 - if (ci->flags =3D=3D CLUSTER_FLAG_NONE) { + spin_lock(&si->lock); + if (ci->flags =3D=3D CLUSTER_FLAG_NONE) list_add_tail(&ci->list, list); - } else { - if (ci->flags =3D=3D CLUSTER_FLAG_FRAG) { - VM_WARN_ON(!si->frag_cluster_nr[ci->order]); - si->frag_cluster_nr[ci->order]--; - } + else list_move_tail(&ci->list, list); - } + spin_unlock(&si->lock); + + if (ci->flags =3D=3D CLUSTER_FLAG_FRAG) + atomic_long_dec(&si->frag_cluster_nr[ci->order]); + else if (new_flags =3D=3D CLUSTER_FLAG_FRAG) + atomic_long_inc(&si->frag_cluster_nr[ci->order]); ci->flags =3D new_flags; - if (new_flags =3D=3D CLUSTER_FLAG_FRAG) - si->frag_cluster_nr[ci->order]++; } =20 /* Add a cluster to discard list and schedule it to do discard */ @@ -475,39 +488,90 @@ static void swap_cluster_schedule_discard(struct swap= _info_struct *si, =20 static void __free_cluster(struct swap_info_struct *si, struct swap_cluste= r_info *ci) { - lockdep_assert_held(&si->lock); lockdep_assert_held(&ci->lock); cluster_move(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); ci->order =3D 0; } =20 +/* + * Isolate and lock the first cluster that is not contented on a list, + * clean its flag before taken off-list. Cluster flag must be in sync + * with list status, so cluster updaters can always know the cluster + * list status without touching si lock. + * + * Note it's possible that all clusters on a list are contented so + * this returns NULL for an non-empty list. + */ +static struct swap_cluster_info *cluster_isolate_lock( + struct swap_info_struct *si, struct list_head *list) +{ + struct swap_cluster_info *ci, *ret =3D NULL; + + 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; + + /* We may only isolate and clear flags of following lists */ + VM_BUG_ON(!ci->flags); + VM_BUG_ON(ci->flags > CLUSTER_FLAG_USABLE && + ci->flags !=3D CLUSTER_FLAG_FULL); + + list_del(&ci->list); + ci->flags =3D CLUSTER_FLAG_NONE; + ret =3D ci; + break; + } +out: + spin_unlock(&si->lock); + + return ret; +} + /* * Doing discard actually. After a cluster discard is finished, the cluster - * will be added to free cluster list. caller should hold si->lock. -*/ -static void swap_do_scheduled_discard(struct swap_info_struct *si) + * will be added to free cluster list. Discard cluster is a bit special as + * they don't participate in allocation or reclaim, so clusters marked as + * CLUSTER_FLAG_DISCARD must remain off-list or on discard list. + */ +static bool swap_do_scheduled_discard(struct swap_info_struct *si) { struct swap_cluster_info *ci; + bool ret =3D false; unsigned int idx; =20 + spin_lock(&si->lock); while (!list_empty(&si->discard_clusters)) { ci =3D list_first_entry(&si->discard_clusters, struct swap_cluster_info,= list); + /* + * Delete the cluster from list but don't clear its flags until + * discard is done, so isolation and relocation will skip it. + */ list_del(&ci->list); - /* Must clear flag when taking a cluster off-list */ - ci->flags =3D CLUSTER_FLAG_NONE; idx =3D cluster_index(si, ci); spin_unlock(&si->lock); - discard_swap_cluster(si, idx * SWAPFILE_CLUSTER, SWAPFILE_CLUSTER); =20 - spin_lock(&si->lock); spin_lock(&ci->lock); - __free_cluster(si, ci); + /* + * Discard is done, clear its flags as it's now off-list, + * then return the cluster to allocation list. + */ + ci->flags =3D CLUSTER_FLAG_NONE; memset(si->swap_map + idx * SWAPFILE_CLUSTER, 0, SWAPFILE_CLUSTER); + __free_cluster(si, ci); spin_unlock(&ci->lock); + ret =3D true; + spin_lock(&si->lock); } + spin_unlock(&si->lock); + return ret; } =20 static void swap_discard_work(struct work_struct *work) @@ -516,9 +580,7 @@ static void swap_discard_work(struct work_struct *work) =20 si =3D container_of(work, struct swap_info_struct, discard_work); =20 - spin_lock(&si->lock); swap_do_scheduled_discard(si); - spin_unlock(&si->lock); } =20 static void swap_users_ref_free(struct percpu_ref *ref) @@ -529,10 +591,14 @@ static void swap_users_ref_free(struct percpu_ref *re= f) complete(&si->comp); } =20 +/* + * Must be called after freeing if ci->count =3D=3D 0, moves the cluster t= o free + * or discard list. + */ static void free_cluster(struct swap_info_struct *si, struct swap_cluster_= info *ci) { VM_BUG_ON(ci->count !=3D 0); - lockdep_assert_held(&si->lock); + VM_BUG_ON(ci->flags =3D=3D CLUSTER_FLAG_FREE); lockdep_assert_held(&ci->lock); =20 /* @@ -549,6 +615,48 @@ static void free_cluster(struct swap_info_struct *si, = struct swap_cluster_info * __free_cluster(si, ci); } =20 +/* + * Must be called after freeing if ci->count !=3D 0, moves the cluster to + * nonfull list. + */ +static void partial_free_cluster(struct swap_info_struct *si, + struct swap_cluster_info *ci) +{ + VM_BUG_ON(!ci->count || ci->count =3D=3D SWAPFILE_CLUSTER); + lockdep_assert_held(&ci->lock); + + if (ci->flags !=3D CLUSTER_FLAG_NONFULL) + cluster_move(si, ci, &si->nonfull_clusters[ci->order], + CLUSTER_FLAG_NONFULL); +} + +/* + * Must be called after allocation, moves the cluster to full or frag list. + * Note: allocation doesn't acquire si lock, and may drop the ci lock for + * reclaim, so the cluster could be any where when called. + */ +static void relocate_cluster(struct swap_info_struct *si, + struct swap_cluster_info *ci) +{ + lockdep_assert_held(&ci->lock); + + /* Discard cluster must remain off-list or on discard list */ + if (cluster_is_discard(ci)) + return; + + if (!ci->count) { + free_cluster(si, ci); + } else if (ci->count !=3D SWAPFILE_CLUSTER) { + if (ci->flags !=3D CLUSTER_FLAG_FRAG) + cluster_move(si, ci, &si->frag_clusters[ci->order], + CLUSTER_FLAG_FRAG); + } else { + if (ci->flags !=3D CLUSTER_FLAG_FULL) + cluster_move(si, ci, &si->full_clusters, + CLUSTER_FLAG_FULL); + } +} + /* * The cluster corresponding to page_nr will be used. The cluster will not= be * added to free cluster list and its usage counter will be increased by 1. @@ -567,30 +675,6 @@ static void inc_cluster_info_page(struct swap_info_str= uct *si, VM_BUG_ON(ci->flags); } =20 -/* - * The cluster ci decreases @nr_pages usage. If the usage counter becomes = 0, - * which means no page in the cluster is in use, we can optionally discard - * the cluster and add it to free cluster list. - */ -static void dec_cluster_info_page(struct swap_info_struct *si, - struct swap_cluster_info *ci, int nr_pages) -{ - VM_BUG_ON(ci->count < nr_pages); - VM_BUG_ON(cluster_is_free(ci)); - lockdep_assert_held(&si->lock); - lockdep_assert_held(&ci->lock); - ci->count -=3D nr_pages; - - if (!ci->count) { - free_cluster(si, ci); - return; - } - - if (ci->flags !=3D CLUSTER_FLAG_NONFULL) - cluster_move(si, ci, &si->nonfull_clusters[ci->order], - CLUSTER_FLAG_NONFULL); -} - static bool cluster_reclaim_range(struct swap_info_struct *si, struct swap_cluster_info *ci, unsigned long start, unsigned long end) @@ -600,8 +684,6 @@ static bool cluster_reclaim_range(struct swap_info_stru= ct *si, int nr_reclaim; =20 spin_unlock(&ci->lock); - spin_unlock(&si->lock); - do { switch (READ_ONCE(map[offset])) { case 0: @@ -619,9 +701,7 @@ static bool cluster_reclaim_range(struct swap_info_stru= ct *si, } } while (offset < end); out: - spin_lock(&si->lock); spin_lock(&ci->lock); - /* * Recheck the range no matter reclaim succeeded or not, the slot * could have been be freed while we are not holding the lock. @@ -635,11 +715,11 @@ static bool cluster_reclaim_range(struct swap_info_st= ruct *si, =20 static bool cluster_scan_range(struct swap_info_struct *si, struct swap_cluster_info *ci, - unsigned long start, unsigned int nr_pages) + unsigned long start, unsigned int nr_pages, + bool *need_reclaim) { unsigned long offset, end =3D start + nr_pages; unsigned char *map =3D si->swap_map; - bool need_reclaim =3D false; =20 for (offset =3D start; offset < end; offset++) { switch (READ_ONCE(map[offset])) { @@ -648,16 +728,13 @@ static bool cluster_scan_range(struct swap_info_struc= t *si, case SWAP_HAS_CACHE: if (!vm_swap_full()) return false; - need_reclaim =3D true; + *need_reclaim =3D true; continue; default: return false; } } =20 - if (need_reclaim) - return cluster_reclaim_range(si, ci, start, end); - return true; } =20 @@ -672,23 +749,13 @@ static bool cluster_alloc_range(struct swap_info_stru= ct *si, struct swap_cluster if (!(si->flags & SWP_WRITEOK)) return false; =20 - VM_BUG_ON(ci->flags =3D=3D CLUSTER_FLAG_NONE); - VM_BUG_ON(ci->flags > CLUSTER_FLAG_USABLE); - - if (cluster_is_free(ci)) { - if (nr_pages < SWAPFILE_CLUSTER) - cluster_move(si, ci, &si->nonfull_clusters[order], - CLUSTER_FLAG_NONFULL); + if (cluster_is_free(ci)) ci->order =3D order; - } =20 memset(si->swap_map + start, usage, nr_pages); swap_range_alloc(si, nr_pages); ci->count +=3D nr_pages; =20 - if (ci->count =3D=3D SWAPFILE_CLUSTER) - cluster_move(si, ci, &si->full_clusters, CLUSTER_FLAG_FULL); - return true; } =20 @@ -699,37 +766,55 @@ static unsigned int alloc_swap_scan_cluster(struct sw= ap_info_struct *si, unsigne unsigned long start =3D offset & ~(SWAPFILE_CLUSTER - 1); unsigned long end =3D min(start + SWAPFILE_CLUSTER, si->max); unsigned int nr_pages =3D 1 << order; + bool need_reclaim, ret; struct swap_cluster_info *ci; =20 - if (end < nr_pages) - return SWAP_NEXT_INVALID; - end -=3D nr_pages; + ci =3D &si->cluster_info[offset / SWAPFILE_CLUSTER]; + lockdep_assert_held(&ci->lock); =20 - ci =3D lock_cluster(si, offset); - if (ci->count + nr_pages > SWAPFILE_CLUSTER) { + if (end < nr_pages || ci->count + nr_pages > SWAPFILE_CLUSTER) { offset =3D SWAP_NEXT_INVALID; - goto done; + goto out; } =20 - while (offset <=3D end) { - if (cluster_scan_range(si, ci, offset, nr_pages)) { - if (!cluster_alloc_range(si, ci, offset, usage, order)) { - offset =3D SWAP_NEXT_INVALID; - goto done; - } - *foundp =3D offset; - if (ci->count =3D=3D SWAPFILE_CLUSTER) { + for (end -=3D nr_pages; offset <=3D end; offset +=3D nr_pages) { + need_reclaim =3D false; + if (!cluster_scan_range(si, ci, offset, nr_pages, &need_reclaim)) + continue; + if (need_reclaim) { + ret =3D cluster_reclaim_range(si, ci, start, end); + /* + * Reclaim drops ci->lock and cluster could be used + * by another order. Not checking flag as off-list + * cluster has no flag set, and change of list + * won't cause fragmentation. + */ + if (!cluster_is_usable(ci, order)) { offset =3D SWAP_NEXT_INVALID; - goto done; + goto out; } - offset +=3D nr_pages; - break; + if (cluster_is_free(ci)) + offset =3D start; + /* Reclaim failed but cluster is usable, try next */ + if (!ret) + continue; + } + if (!cluster_alloc_range(si, ci, offset, usage, order)) { + offset =3D SWAP_NEXT_INVALID; + goto out; + } + *foundp =3D offset; + if (ci->count =3D=3D SWAPFILE_CLUSTER) { + offset =3D SWAP_NEXT_INVALID; + goto out; } offset +=3D nr_pages; + break; } if (offset > end) offset =3D SWAP_NEXT_INVALID; -done: +out: + relocate_cluster(si, ci); unlock_cluster(ci); return offset; } @@ -746,18 +831,17 @@ static void swap_reclaim_full_clusters(struct swap_in= fo_struct *si, bool force) if (force) to_scan =3D swap_usage_in_pages(si) / SWAPFILE_CLUSTER; =20 - while (!list_empty(&si->full_clusters)) { - ci =3D list_first_entry(&si->full_clusters, struct swap_cluster_info, li= st); - list_move_tail(&ci->list, &si->full_clusters); + while ((ci =3D cluster_isolate_lock(si, &si->full_clusters))) { offset =3D cluster_offset(si, ci); end =3D min(si->max, offset + SWAPFILE_CLUSTER); to_scan--; =20 - spin_unlock(&si->lock); while (offset < end) { if (READ_ONCE(map[offset]) =3D=3D SWAP_HAS_CACHE) { + spin_unlock(&ci->lock); nr_reclaim =3D __try_to_reclaim_swap(si, offset, TTRS_ANYWAY | TTRS_DIRECT); + spin_lock(&ci->lock); if (nr_reclaim) { offset +=3D abs(nr_reclaim); continue; @@ -765,8 +849,8 @@ static void swap_reclaim_full_clusters(struct swap_info= _struct *si, bool force) } offset++; } - spin_lock(&si->lock); =20 + unlock_cluster(ci); if (to_scan <=3D 0) break; } @@ -778,9 +862,7 @@ static void swap_reclaim_work(struct work_struct *work) =20 si =3D container_of(work, struct swap_info_struct, reclaim_work); =20 - spin_lock(&si->lock); swap_reclaim_full_clusters(si, true); - spin_unlock(&si->lock); } =20 /* @@ -791,29 +873,34 @@ static void swap_reclaim_work(struct work_struct *wor= k) static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,= int order, unsigned char usage) { - struct percpu_cluster *cluster; struct swap_cluster_info *ci; unsigned int offset, found =3D 0; =20 -new_cluster: - lockdep_assert_held(&si->lock); - cluster =3D this_cpu_ptr(si->percpu_cluster); - offset =3D cluster->next[order]; + /* Fast path using per CPU cluster */ + local_lock(&si->percpu_cluster->lock); + offset =3D __this_cpu_read(si->percpu_cluster->next[order]); if (offset) { - offset =3D alloc_swap_scan_cluster(si, offset, &found, order, usage); + ci =3D lock_cluster(si, offset); + /* Cluster could have been used by another order */ + if (cluster_is_usable(ci, order)) { + if (cluster_is_free(ci)) + offset =3D cluster_offset(si, ci); + offset =3D alloc_swap_scan_cluster(si, offset, &found, + order, usage); + } else { + unlock_cluster(ci); + } if (found) goto done; } =20 - if (!list_empty(&si->free_clusters)) { - ci =3D list_first_entry(&si->free_clusters, struct swap_cluster_info, li= st); - offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), &found, o= rder, usage); - /* - * Either we didn't touch the cluster due to swapoff, - * or the allocation must success. - */ - VM_BUG_ON((si->flags & SWP_WRITEOK) && !found); - goto done; +new_cluster: + ci =3D cluster_isolate_lock(si, &si->free_clusters); + if (ci) { + offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), + &found, order, usage); + if (found) + goto done; } =20 /* Try reclaim from full clusters if free clusters list is drained */ @@ -821,49 +908,45 @@ static unsigned long cluster_alloc_swap_entry(struct = swap_info_struct *si, int o swap_reclaim_full_clusters(si, false); =20 if (order < PMD_ORDER) { - unsigned int frags =3D 0; + unsigned int frags =3D 0, frags_existing; =20 - while (!list_empty(&si->nonfull_clusters[order])) { - ci =3D list_first_entry(&si->nonfull_clusters[order], - struct swap_cluster_info, list); - cluster_move(si, ci, &si->frag_clusters[order], CLUSTER_FLAG_FRAG); + while ((ci =3D cluster_isolate_lock(si, &si->nonfull_clusters[order]))) { offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), &found, order, usage); - frags++; + /* + * With `fragmenting` set to true, it will surely take + * the cluster off nonfull list + */ if (found) goto done; + frags++; } =20 - /* - * Nonfull clusters are moved to frag tail if we reached - * here, count them too, don't over scan the frag list. - */ - while (frags < si->frag_cluster_nr[order]) { - ci =3D list_first_entry(&si->frag_clusters[order], - struct swap_cluster_info, list); + frags_existing =3D atomic_long_read(&si->frag_cluster_nr[order]); + while (frags < frags_existing && + (ci =3D cluster_isolate_lock(si, &si->frag_clusters[order]))) { + atomic_long_dec(&si->frag_cluster_nr[order]); /* - * Rotate the frag list to iterate, they were all failing - * high order allocation or moved here due to per-CPU usage, - * this help keeping usable cluster ahead. + * Rotate the frag list to iterate, they were all + * failing high order allocation or moved here due to + * per-CPU usage, but they could contain newly released + * reclaimable (eg. lazy-freed swap cache) slots. */ - list_move_tail(&ci->list, &si->frag_clusters[order]); offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), &found, order, usage); - frags++; if (found) goto done; + frags++; } } =20 - if (!list_empty(&si->discard_clusters)) { - /* - * we don't have free cluster but have some clusters in - * discarding, do discard now and reclaim them, then - * reread cluster_next_cpu since we dropped si->lock - */ - swap_do_scheduled_discard(si); + /* + * We don't have free cluster but have some clusters in + * discarding, do discard now and reclaim them, then + * reread cluster_next_cpu since we dropped si->lock + */ + if ((si->flags & SWP_PAGE_DISCARD) && swap_do_scheduled_discard(si)) goto new_cluster; - } =20 if (order) goto done; @@ -874,26 +957,25 @@ static unsigned long cluster_alloc_swap_entry(struct = swap_info_struct *si, int o * Clusters here have at least one usable slots and can't fail order 0 * allocation, but reclaim may drop si->lock and race with another user. */ - while (!list_empty(&si->frag_clusters[o])) { - ci =3D list_first_entry(&si->frag_clusters[o], - struct swap_cluster_info, list); + while ((ci =3D cluster_isolate_lock(si, &si->frag_clusters[o]))) { + atomic_long_dec(&si->frag_cluster_nr[o]); offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, 0, usage); + &found, order, usage); if (found) goto done; } =20 - while (!list_empty(&si->nonfull_clusters[o])) { - ci =3D list_first_entry(&si->nonfull_clusters[o], - struct swap_cluster_info, list); + while ((ci =3D cluster_isolate_lock(si, &si->nonfull_clusters[o]))) { offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, 0, usage); + &found, order, usage); if (found) goto done; } } done: - cluster->next[order] =3D offset; + __this_cpu_write(si->percpu_cluster->next[order], offset); + local_unlock(&si->percpu_cluster->lock); + return found; } =20 @@ -1153,14 +1235,11 @@ int get_swap_pages(int n_goal, swp_entry_t swp_entr= ies[], int entry_order) plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]); spin_unlock(&swap_avail_lock); if (get_swap_device_info(si)) { - spin_lock(&si->lock); n_ret =3D scan_swap_map_slots(si, SWAP_HAS_CACHE, n_goal, swp_entries, order); - spin_unlock(&si->lock); put_swap_device(si); if (n_ret || size > 1) goto check_out; - cond_resched(); } =20 spin_lock(&swap_avail_lock); @@ -1373,9 +1452,7 @@ static bool __swap_entries_free(struct swap_info_stru= ct *si, if (!has_cache) { for (i =3D 0; i < nr; i++) zswap_invalidate(swp_entry(si->type, offset + i)); - spin_lock(&si->lock); swap_entry_range_free(si, entry, nr); - spin_unlock(&si->lock); } return has_cache; =20 @@ -1404,16 +1481,27 @@ static void swap_entry_range_free(struct swap_info_= struct *si, swp_entry_t entry unsigned char *map_end =3D map + nr_pages; struct swap_cluster_info *ci; =20 + /* It should never free entries across different clusters */ + VM_BUG_ON((offset / SWAPFILE_CLUSTER) !=3D ((offset + nr_pages - 1) / SWA= PFILE_CLUSTER)); + ci =3D lock_cluster(si, offset); + VM_BUG_ON(cluster_is_free(ci)); + VM_BUG_ON(ci->count < nr_pages); + + ci->count -=3D nr_pages; do { VM_BUG_ON(*map !=3D SWAP_HAS_CACHE); *map =3D 0; } while (++map < map_end); - dec_cluster_info_page(si, ci, nr_pages); - unlock_cluster(ci); =20 mem_cgroup_uncharge_swap(entry, nr_pages); swap_range_free(si, offset, nr_pages); + + if (!ci->count) + free_cluster(si, ci); + else + partial_free_cluster(si, ci); + unlock_cluster(ci); } =20 static void cluster_swap_free_nr(struct swap_info_struct *si, @@ -1485,9 +1573,7 @@ void put_swap_folio(struct folio *folio, swp_entry_t = entry) ci =3D lock_cluster(si, offset); if (size > 1 && swap_is_has_cache(si, offset, size)) { unlock_cluster(ci); - spin_lock(&si->lock); swap_entry_range_free(si, entry, size); - spin_unlock(&si->lock); return; } for (int i =3D 0; i < size; i++, entry.val++) { @@ -1502,46 +1588,19 @@ void put_swap_folio(struct folio *folio, swp_entry_= t entry) unlock_cluster(ci); } =20 -static int swp_entry_cmp(const void *ent1, const void *ent2) -{ - const swp_entry_t *e1 =3D ent1, *e2 =3D ent2; - - return (int)swp_type(*e1) - (int)swp_type(*e2); -} - void swapcache_free_entries(swp_entry_t *entries, int n) { - struct swap_info_struct *si, *prev; int i; + struct swap_info_struct *si =3D NULL; =20 if (n <=3D 0) return; =20 - prev =3D NULL; - si =3D NULL; - - /* - * Sort swap entries by swap device, so each lock is only taken once. - * nr_swapfiles isn't absolutely correct, but the overhead of sort() is - * so low that it isn't necessary to optimize further. - */ - if (nr_swapfiles > 1) - sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL); for (i =3D 0; i < n; ++i) { si =3D _swap_info_get(entries[i]); - - if (si !=3D prev) { - if (prev !=3D NULL) - spin_unlock(&prev->lock); - if (si !=3D NULL) - spin_lock(&si->lock); - } if (si) swap_entry_range_free(si, entries[i], 1); - prev =3D si; } - if (si) - spin_unlock(&si->lock); } =20 int __swap_count(swp_entry_t entry) @@ -1793,13 +1852,8 @@ swp_entry_t get_swap_page_of_type(int type) goto fail; =20 /* This is called for allocating swap entry, not cache */ - if (get_swap_device_info(si)) { - spin_lock(&si->lock); - if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry, 0= )) - atomic_long_dec(&nr_swap_pages); - spin_unlock(&si->lock); - put_swap_device(si); - } + if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry, 0)) + atomic_long_dec(&nr_swap_pages); fail: return entry; } @@ -3137,6 +3191,7 @@ static struct swap_cluster_info *setup_clusters(struc= t swap_info_struct *si, cluster =3D per_cpu_ptr(si->percpu_cluster, cpu); for (i =3D 0; i < SWAP_NR_ORDERS; i++) cluster->next[i] =3D SWAP_NEXT_INVALID; + local_lock_init(&cluster->lock); } =20 /* @@ -3160,7 +3215,7 @@ static struct swap_cluster_info *setup_clusters(struc= t swap_info_struct *si, for (i =3D 0; i < SWAP_NR_ORDERS; i++) { INIT_LIST_HEAD(&si->nonfull_clusters[i]); INIT_LIST_HEAD(&si->frag_clusters[i]); - si->frag_cluster_nr[i] =3D 0; + atomic_long_set(&si->frag_cluster_nr[i], 0); } =20 /* @@ -3642,7 +3697,6 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) */ goto outer; } - spin_lock(&si->lock); =20 offset =3D swp_offset(entry); =20 @@ -3707,7 +3761,6 @@ int add_swap_count_continuation(swp_entry_t entry, gf= p_t gfp_mask) spin_unlock(&si->cont_lock); out: unlock_cluster(ci); - spin_unlock(&si->lock); put_swap_device(si); outer: if (page) --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 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 3E6AE1D935C for ; Tue, 24 Dec 2024 14:40:12 +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=1735051214; cv=none; b=MEr+J9kCqUDgiP1pEYNg7BSvzpgDVVijC/50hMgB/q8Z/N36g2zYV4U4lghqdjei7SlgeVNddi8TN8Ft29kqdasGv4Uc3TmvBwTTs223hZQh0bFd7gXBGjbpYe4eFiaTmezmn+XxcL3BBVBFxk/z0tuYZ1lPWvpP7b7KiYwZYps= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051214; c=relaxed/simple; bh=+pRwarSS3rJ9eQRZ3l11H4YiyDvqMpDS+WyC8vBC0lA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=vGPeGn9oMvzXxVe93A7JQ7GwTiN7GGDkeCMQ+S/MmyqBj9ZFSKFVREFcgke4gsB2hp1ZWtqy4a0sX9l3bt8uHZHGsRK7i0E8ZoqftnEYLgRlKxVQgAXoHwsBwwypExTqOQoqdmRC/171Yrd0WNTz4kksACpDGjJxLXxroQabq8g= 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=LcvIhDbK; 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="LcvIhDbK" Received: by mail-pj1-f50.google.com with SMTP id 98e67ed59e1d1-2f4409fc8fdso4499353a91.1 for ; Tue, 24 Dec 2024 06:40:12 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051211; x=1735656011; 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=OeMbPM60Q8v3Qfaz9R6/9c2/Ea7K6oyXleY7O4H/Tp8=; b=LcvIhDbKbPDzKykNlz+uaLoGgS8Tp29n/PPVtynTp+ml5PnDuuuPOqn8KEIckvJKk2 V7RQPpI34553A0flsJcHmKE2sEEzqYGAXnfHyJrAIQ+u/QSRtLESAmi1/1LQfrl1HdJB ArZs0RFx0G/4/b11TZEXmdrQWW1ijIvR+Z6kMfH+5SX8pot6EvGqNpx2uTciN1xWj0zo memQcRLEOnHZON/+6Odalpry0+XA9W0GLk3ZPAgDK9UcmRJuv9rFBlpG27uhMXIadzzo r6nS5+GLlTYk4l+hXUAf/mWtKn8sgfwLSp1N+nCMCR4RfBo/Wpq38B+KyAMAZxTtLr6x OsuQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051211; x=1735656011; 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=OeMbPM60Q8v3Qfaz9R6/9c2/Ea7K6oyXleY7O4H/Tp8=; b=bi+BGiRWQzmIK/tJuG6CFTRJdWIhOlg86yfS+gd5INIvIFCRCi5zZMKjNaRYW/P6Lu uAK/TQ8/XTI3tpzDmWz6WQWSJhEX75/ymQiKcnSUgZlfGcNipk+RsyYRX9zIB4/DKviw nCYe/fdYyJuuvqOuOILwqo6OH7G1ZGqrGy+yubZLDPoMW9hQ4DZafm+k8GV2en7r0lry S7p7mONl+vCNj2s2C2Rc8UihH/V2rnr+zpDKlHnqVwK2xq1+krFkoQ7qxg/UQWykRv68 g5BT1IwEDI35TP9JZUTi4fI67SHOtrljbiOp7jRy882tjpcd37BROUIMwG88SnXQzvqA 1GXg== X-Forwarded-Encrypted: i=1; AJvYcCVZHmfPaG59Zl0V/3txusHZz16o1Yqy4FUJOk8koBQ781/mszouBP7q6pKXwSV6ujOxLx0fzh8MeaD3P40=@vger.kernel.org X-Gm-Message-State: AOJu0YyetWT/m64lUmrHnLXavD2vm5pLqKTVCZp8dAfRmUaE+XQMyf5w nEa7nZ3uamZuK/dQk9yUU9y+kaHqe7M481/ygWrkTvwSLASeqNeE X-Gm-Gg: ASbGncsHRWQFYcy0A14Si6TKTRWh4Fte998xJaqgY8m+2rL8l+BJyGOjJdxNuISyRN8 cWX6SNYBIuvkLLEkEk7FFif4uKJkH8dii+lp3C0TdjdEecfPrF8sq9N4TZ3r6gSOGAnOP/wQadq ZcmHIi0xzrm76Jgk2jm+IuQR+IHXOWsCOv5pvovK+6tFHmp/QiBXmBLnP/aPTNRiNv5ihjNSJRd rhDpIXyvGxhDAHZeTKs4fQs8KQS1eaRaKWAIV1y3fH+V6zhDJvWqTFpO9WDwFNjOMDPk2Yid70/ pQ== X-Google-Smtp-Source: AGHT+IGbB/29Y+1ZgUGrQ+JERD995978jUTdlYdu6QWEKgLiCQEmWerJkgBsrHNrNTQtYolF6Xq0WQ== X-Received: by 2002:a17:90a:d64f:b0:2ee:9661:eafb with SMTP id 98e67ed59e1d1-2f4536d18a7mr24570769a91.12.1735051211431; Tue, 24 Dec 2024 06:40:11 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.40.07 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:40:11 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 10/13] mm, swap: simplify percpu cluster updating Date: Tue, 24 Dec 2024 22:38:08 +0800 Message-ID: <20241224143811.33462-11-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 using a returning argument, we can simply store the next cluster offset to the fixed percpu location, which reduce the stack usage and simplify the function: Object size: ./scripts/bloat-o-meter mm/swapfile.o mm/swapfile.o.new add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-271 (-271) Function old new delta get_swap_pages 2847 2733 -114 alloc_swap_scan_cluster 894 737 -157 Total: Before=3D30833, After=3D30562, chg -0.88% Stack usage: Before: swapfile.c:1190:5:get_swap_pages 240 static After: swapfile.c:1185:5:get_swap_pages 216 static Signed-off-by: Kairui Song Suggested-by: Chris Li --- include/linux/swap.h | 4 +-- mm/swapfile.c | 66 +++++++++++++++++++------------------------- 2 files changed, 31 insertions(+), 39 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index c4ff31cb6bde..4c1d2e69689f 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -275,9 +275,9 @@ enum swap_cluster_flags { * 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 * cluster to which it belongs being marked free. Therefore 0 is safe to u= se as - * a sentinel to indicate next is not valid in percpu_cluster. + * a sentinel to indicate an entry is not valid. */ -#define SWAP_NEXT_INVALID 0 +#define SWAP_ENTRY_INVALID 0 =20 #ifdef CONFIG_THP_SWAP #define SWAP_NR_ORDERS (PMD_ORDER + 1) diff --git a/mm/swapfile.c b/mm/swapfile.c index bb1ef9192d99..ac170acf55a7 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -759,23 +759,23 @@ static bool cluster_alloc_range(struct swap_info_stru= ct *si, struct swap_cluster return true; } =20 -static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si, u= nsigned long offset, - unsigned int *foundp, unsigned int order, +/* Try use a new cluster for current CPU and allocate from it. */ +static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si, + struct swap_cluster_info *ci, + unsigned long offset, + unsigned int order, unsigned char usage) { - unsigned long start =3D offset & ~(SWAPFILE_CLUSTER - 1); + unsigned int next =3D SWAP_ENTRY_INVALID, found =3D SWAP_ENTRY_INVALID; + unsigned long start =3D ALIGN_DOWN(offset, SWAPFILE_CLUSTER); unsigned long end =3D min(start + SWAPFILE_CLUSTER, si->max); unsigned int nr_pages =3D 1 << order; bool need_reclaim, ret; - struct swap_cluster_info *ci; =20 - ci =3D &si->cluster_info[offset / SWAPFILE_CLUSTER]; lockdep_assert_held(&ci->lock); =20 - if (end < nr_pages || ci->count + nr_pages > SWAPFILE_CLUSTER) { - offset =3D SWAP_NEXT_INVALID; + if (end < nr_pages || ci->count + nr_pages > SWAPFILE_CLUSTER) goto out; - } =20 for (end -=3D nr_pages; offset <=3D end; offset +=3D nr_pages) { need_reclaim =3D false; @@ -789,34 +789,27 @@ static unsigned int alloc_swap_scan_cluster(struct sw= ap_info_struct *si, unsigne * cluster has no flag set, and change of list * won't cause fragmentation. */ - if (!cluster_is_usable(ci, order)) { - offset =3D SWAP_NEXT_INVALID; + if (!cluster_is_usable(ci, order)) goto out; - } if (cluster_is_free(ci)) offset =3D start; /* Reclaim failed but cluster is usable, try next */ if (!ret) continue; } - if (!cluster_alloc_range(si, ci, offset, usage, order)) { - offset =3D SWAP_NEXT_INVALID; - goto out; - } - *foundp =3D offset; - if (ci->count =3D=3D SWAPFILE_CLUSTER) { - offset =3D SWAP_NEXT_INVALID; - goto out; - } + if (!cluster_alloc_range(si, ci, offset, usage, order)) + break; + found =3D offset; offset +=3D nr_pages; + if (ci->count < SWAPFILE_CLUSTER && offset <=3D end) + next =3D offset; break; } - if (offset > end) - offset =3D SWAP_NEXT_INVALID; out: relocate_cluster(si, ci); unlock_cluster(ci); - return offset; + __this_cpu_write(si->percpu_cluster->next[order], next); + return found; } =20 /* Return true if reclaimed a whole cluster */ @@ -885,8 +878,8 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o if (cluster_is_usable(ci, order)) { if (cluster_is_free(ci)) offset =3D cluster_offset(si, ci); - offset =3D alloc_swap_scan_cluster(si, offset, &found, - order, usage); + found =3D alloc_swap_scan_cluster(si, ci, offset, + order, usage); } else { unlock_cluster(ci); } @@ -897,8 +890,8 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o new_cluster: ci =3D cluster_isolate_lock(si, &si->free_clusters); if (ci) { - offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, order, usage); + found =3D alloc_swap_scan_cluster(si, ci, cluster_offset(si, ci), + order, usage); if (found) goto done; } @@ -911,8 +904,8 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o unsigned int frags =3D 0, frags_existing; =20 while ((ci =3D cluster_isolate_lock(si, &si->nonfull_clusters[order]))) { - offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, order, usage); + found =3D alloc_swap_scan_cluster(si, ci, cluster_offset(si, ci), + order, usage); /* * With `fragmenting` set to true, it will surely take * the cluster off nonfull list @@ -932,8 +925,8 @@ static unsigned long cluster_alloc_swap_entry(struct sw= ap_info_struct *si, int o * per-CPU usage, but they could contain newly released * reclaimable (eg. lazy-freed swap cache) slots. */ - offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, order, usage); + found =3D alloc_swap_scan_cluster(si, ci, cluster_offset(si, ci), + order, usage); if (found) goto done; frags++; @@ -959,21 +952,20 @@ static unsigned long cluster_alloc_swap_entry(struct = swap_info_struct *si, int o */ while ((ci =3D cluster_isolate_lock(si, &si->frag_clusters[o]))) { atomic_long_dec(&si->frag_cluster_nr[o]); - offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, order, usage); + found =3D alloc_swap_scan_cluster(si, ci, cluster_offset(si, ci), + 0, usage); if (found) goto done; } =20 while ((ci =3D cluster_isolate_lock(si, &si->nonfull_clusters[o]))) { - offset =3D alloc_swap_scan_cluster(si, cluster_offset(si, ci), - &found, order, usage); + found =3D alloc_swap_scan_cluster(si, ci, cluster_offset(si, ci), + 0, usage); if (found) goto done; } } done: - __this_cpu_write(si->percpu_cluster->next[order], offset); local_unlock(&si->percpu_cluster->lock); =20 return found; @@ -3190,7 +3182,7 @@ static struct swap_cluster_info *setup_clusters(struc= t swap_info_struct *si, =20 cluster =3D per_cpu_ptr(si->percpu_cluster, cpu); for (i =3D 0; i < SWAP_NR_ORDERS; i++) - cluster->next[i] =3D SWAP_NEXT_INVALID; + cluster->next[i] =3D SWAP_ENTRY_INVALID; local_lock_init(&cluster->lock); } =20 --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f175.google.com (mail-pl1-f175.google.com [209.85.214.175]) (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 EA4F91DDC02 for ; Tue, 24 Dec 2024 14:40:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.175 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051218; cv=none; b=jBaPpSGAtkgYVkC9R1SVdzoiO+vA9V55K+YYReTxSxiWgayCFNDd22nWU40Z26UOzk1cJAh5HM2zHKAnN6/S6Bjs0UUyaxIqUyEPrcuMVge20/MYk3BWt4CfbZOwUYeMXHqu6N2mrD42mkat9SEdT/LBNON0GW3f60noQMIxnVg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051218; c=relaxed/simple; bh=q+ZBnuXjSMW/VMrrlhQcdfffqJIgLNXBnSJjonGwDWE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=A5FrFN0omzvHbFrLOEerlQu8i+RlbvpAb5P5pm8118lXzf22tPH3wSHfxeQwKxRehivF8sx7Llon3baizFVvZ8QHgFEw+cuDo8fcGMoVdlpZCgry1bzkgyg2POSbbhZxqDEKo3vJHjT+dNpvx1CYJleqWMBra9u5LZsDfk5HY3I= 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=e9Lwti8E; arc=none smtp.client-ip=209.85.214.175 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="e9Lwti8E" Received: by mail-pl1-f175.google.com with SMTP id d9443c01a7336-21683192bf9so58668165ad.3 for ; Tue, 24 Dec 2024 06:40:15 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051215; x=1735656015; 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=Bzlbcu02fLqLzv6kaO1DSu6E6WlQUI1ISyd8RxZxJr8=; b=e9Lwti8EP8jb1NnPQueO6Kk8YNXhV6NktRErYjAzqACdanvCJzwoQgt0z6Zi0yeref KUAYptCvXXhxKlQp6QpRU9oglK9sTAQE5pyIYgCh1gFKI/AYYn0WYJG98f79IJDtnmZ5 BAtmqU9VO9TAF5QjEMfXipyTjw9QXkRIp2ZuebaPzjM0/AR8o6Cp+Ul+s81WDK5lbYIH mGKy4hpQK5vw1ytLq//Lk7iNjwzKU9uOmjTkgDRtIFquLFw8VwhDYQtJSnpIwOay99Hc tkVO6eCt/npMXvoWPGU0cnAPMcCZk9mIPNwjxY9ryHFbBWxK3xANeof046zUtLZr9rcX VorA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051215; x=1735656015; 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=Bzlbcu02fLqLzv6kaO1DSu6E6WlQUI1ISyd8RxZxJr8=; b=qB5XQyGffHIc5f2a2PrvFyyVuLDJTHo2ufq3p0cq2Xy/d8TDSgtFcfKhyFT9MDzQ9G 3VP+aZLw1xiQFgtzueO4x5t2XE2YU01SoYfdQPDp9f6Bhopp5eTQE+uCfCjN0hhs+/Dl KRO2y6vNRacmNBCY2o8ZrEbMjAvWBd50N7NpdgiSNXJTSD0ERG7D9Rbd0jhHQkBcvQ+3 EIIkNq2eGW+vNmo9wKoh1f4POq8MsWFWSLfjoKG8QUIRhJY1MaiWkYXZ4pHfF56crxMe UQGjmP0VaYlBx9RUeK00kJu4zOc+xhhefjLo7LSd7YgY2sSJVvpwCxmlZTZ9FxP0Ny5K 5/YA== X-Forwarded-Encrypted: i=1; AJvYcCW1JzStL8gQn/FKyGXQ8be55bfqF0SLjdAjZ3Qtnt06Y/IaYDi/oNy9XQFgjS8F7e5udT49RYoEUnvja4w=@vger.kernel.org X-Gm-Message-State: AOJu0YznhxlxsXY5oxTdq+p/wze3fUfvbkjtEGTcNPeAq+QaDhWMc4Y/ x8SC6kwVNrWh84AWYpbVNJxgThr5ghsBlLWHLunD1Vlo5jKrhL9FvRJAApxXJSM= X-Gm-Gg: ASbGnctZz57Erzcg520NkqDLx9DEtZuwOAC4j/ssw0VB0b4dp/PUIQLXlhXqf++KkiL x/6E5oxptw/f6eJgdyuL91yqzOXfeirCO+mBTt1NCc3AGIpWCN6rAdWaRU6ol4SUw10I3W1Nj8T WUY7u0MRp0szfCb2oSPAr3HsgWLU5QhWweE/t2BZh6m7DPCT/mz3S7rVUGWTq6v3DfKyPgLGJVU 4frj58Y519dQKVe/I4ajzwbreTPRJtZrUIQA4GNUFIVtg4Sh/80PpmSgRETqe8tLycp7wCwvdPg oQ== X-Google-Smtp-Source: AGHT+IHfsTNBsjv0bUq65kgG9hxJHF1KnAgYhU8hlG8rshYiEPh2IPMtkj25JK/GiuQVbqe7HXA/wQ== X-Received: by 2002:a17:902:f70f:b0:211:8404:a957 with SMTP id d9443c01a7336-219e70c01a2mr271220915ad.41.1735051215184; Tue, 24 Dec 2024 06:40:15 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.40.11 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:40:14 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 11/13] mm, swap: introduce a helper for retrieving cluster from offset Date: Tue, 24 Dec 2024 22:38:09 +0800 Message-ID: <20241224143811.33462-12-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 It's a common operation to retrieve the cluster info from offset, introduce a helper for this. Suggested-by: Chris Li Signed-off-by: Kairui Song --- mm/swapfile.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index ac170acf55a7..0445a2db8492 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -424,6 +424,12 @@ static inline unsigned int cluster_index(struct swap_i= nfo_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) { @@ -435,7 +441,7 @@ static inline struct swap_cluster_info *lock_cluster(st= ruct swap_info_struct *si { struct swap_cluster_info *ci; =20 - ci =3D &si->cluster_info[offset / SWAPFILE_CLUSTER]; + ci =3D offset_to_cluster(si, offset); spin_lock(&ci->lock); =20 return ci; @@ -1473,10 +1479,10 @@ static void swap_entry_range_free(struct swap_info_= struct *si, swp_entry_t entry unsigned char *map_end =3D map + nr_pages; struct swap_cluster_info *ci; =20 - /* It should never free entries across different clusters */ - VM_BUG_ON((offset / SWAPFILE_CLUSTER) !=3D ((offset + nr_pages - 1) / SWA= PFILE_CLUSTER)); - ci =3D lock_cluster(si, offset); + + /* It should never free entries across different clusters */ + VM_BUG_ON(ci !=3D offset_to_cluster(si, offset + nr_pages - 1)); VM_BUG_ON(cluster_is_free(ci)); VM_BUG_ON(ci->count < nr_pages); =20 --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f176.google.com (mail-pl1-f176.google.com [209.85.214.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 A07661D935C for ; Tue, 24 Dec 2024 14:40:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.176 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051221; cv=none; b=IHSQNPVp5OCUfob3Dxz4lwSrTS3+4bfHzOS/LrMEg7Ur9inpJs1k2NkYFZxjuCT/0S7C0NMxKY+pTtui0xobz1EaP+2q9vKwnsW8ao+VtU0bqZ8DuvWX80bBb0lkYS9WzKLO0p/BHM4oIosWTvgmuwrmJ5rGZp1D4bnToJuamwQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051221; c=relaxed/simple; bh=GXi1K4qbSYhcgDmKK/QQKfoYN6tSZtpESJP+JqqBRBQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=NlIlkEGraH3bSLB3D8C2fWzldt3Rn/B4uwHo1eo8mDL0A6PVC8XWUz1vXiIxCmQNcBWX8OLG7Z23/aFQWnpKEDzN7Fm8QRQPDAv3wP2neqtMsxFL2y4kRBforJa1LZd/RIGrqtBzAAHtiI+R3L4eMWjP3v5QIgWmDb8hzejEseE= 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=Dw4VbIgU; arc=none smtp.client-ip=209.85.214.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="Dw4VbIgU" Received: by mail-pl1-f176.google.com with SMTP id d9443c01a7336-2166f1e589cso62915035ad.3 for ; Tue, 24 Dec 2024 06:40:19 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051219; x=1735656019; 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=grOS/bcMSihQT+oftYQ+fEn5xlcSkT6BHxL9XDq9XDs=; b=Dw4VbIgUZVWfW7aa0OuipQ3uOMk/2lI2XR6nEHV5SVZtPa5ms5brHRviPQfKORsHE0 pX5wYypBhqRU/BUptGK700k5xFFJXOFFhXkBZgFblk3oWjG8lyDLLtywrUg7/7KjHQPr G031bXBW8ues4m8KEHxkUBJtdz808rlvs/VwISDPEuctKHaM5JI4e7kD7cxsX2gnRjS0 h9/9Hb05i6ImL7oVdbIv03rTgjEoNOc5O7GuUnZK4jif4RzEt5zW5m277RBYv2O8GiWT sl6kn1h6TqPezUDX61uyBXSTaNOHB9DkVCHjFxPnIjsrfmBzgUeebREK2Z/Dxs7iqFnz 5uCg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051219; x=1735656019; 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=grOS/bcMSihQT+oftYQ+fEn5xlcSkT6BHxL9XDq9XDs=; b=kh6O1oakwAWuiBExixD5INqfmRAAdBPXc/VdxGcFjtS65hhlB+7FDau3dmnxWeUPQS 3qC/smjwQDfaAm5EPCyssi6Ws9XU6aXsHHY8IDyyXiC6VEdMgz/jPYeSlNLtwaRdJ4GW LiGCu/7nbkJiprqyPQnD5tJLGXS+WwRXMmsOpDur/Mst5jjyn+TyebGB0zTlqwlw1EPu R6jZV5U024XZEU6Qtb7DEgjvgP4EtxiXn+oOQCVcdz8RMihahGta+8cZm9q9K/5DrTwi IGk171T9Zo4sgBZyJ9ijwN2p5+4hMdMDTEhJ7CsMiOfc/Eec4+xz0B3KyZuKbQ0IVcHK BZhQ== X-Forwarded-Encrypted: i=1; AJvYcCVcv65Dz0JCOtxvpUiI1dzxf6u977ICET/r/IE8G96FlrnNUCk+m68ptkvii3M7Zim2fyhwEprrAEJpL/0=@vger.kernel.org X-Gm-Message-State: AOJu0YzUz5IWnJgT598xMyHXITv0tSN5RhvhEscmNdS+Xmpyz7JOaBpC 0XvOlbwc0X2N3BT6zT7DBiIXi+HNcp9nDPZuqf6iuMfJ48zZiuvA X-Gm-Gg: ASbGncvjNuoCaMxuypATmvYum4MKOW0bveuQQ7V4R2j92+aXSoXvt4InaAGRlyPpxqQ LAVmZDibyJUfBP5khruZIUQAQLG2322dBEb2sic2ECgL+oMpRxs1uogt0i7v8PdDARNTDABqGnZ 6ZA1+VBoR7rt8E7BnZj23W6KTHoIyBFmvbOZuJj4OuFzwBf38A4ynGVNwUZFphjxvCIOCImDV8K UkO4oXbuIsb7f1kHYCofoksXOH367aw3J19zsRUi8VpP1g8/HNy5NU87Xqb1hCX1dB+h/yR4Xh6 lg== X-Google-Smtp-Source: AGHT+IGc1mwapEXAYQJNjva8I5Jy3JbCFO3+Cko8mZMiFwBQtMcFjYL1OETSaeprQYaypdgO4WqVRg== X-Received: by 2002:a17:903:120d:b0:216:5af7:5a8e with SMTP id d9443c01a7336-219e6ebdc17mr247308385ad.26.1735051218961; Tue, 24 Dec 2024 06:40:18 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.40.15 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:40:18 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 12/13] mm, swap: use a global swap cluster for non-rotation devices Date: Tue, 24 Dec 2024 22:38:10 +0800 Message-ID: <20241224143811.33462-13-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 Non-rotational devices (SSD / ZRAM) can tolerate fragmentation, so the goal of the SWAP allocator is to avoid contention for clusters. It uses a per-CPU cluster design, and each CPU will use a different cluster as much as possible. However, HDDs are very sensitive to fragmentation, contention is trivial in comparison. Therefore, we use one global cluster instead. This ensures that each order will be written to the same cluster as much as possible, which helps make the I/O more continuous. This ensures that the performance of the cluster allocator is as good as that of the old allocator. Tests after this commit compared to those before this series: Tested using 'make -j32' with tinyconfig, a 1G memcg limit, and HDD swap: make -j32 with tinyconfig, using 1G memcg limit and HDD swap: Before this series: 114.44user 29.11system 39:42.90elapsed 6%CPU (0avgtext+0avgdata 157284maxre= sident)k 2901232inputs+0outputs (238877major+4227640minor)pagefaults After this commit: 113.90user 23.81system 38:11.77elapsed 6%CPU (0avgtext+0avgdata 157260maxre= sident)k 2548728inputs+0outputs (235471major+4238110minor)pagefaults Suggested-by: Chris Li Signed-off-by: Kairui Song --- include/linux/swap.h | 2 ++ mm/swapfile.c | 51 ++++++++++++++++++++++++++++++++------------ 2 files changed, 39 insertions(+), 14 deletions(-) diff --git a/include/linux/swap.h b/include/linux/swap.h index 4c1d2e69689f..b13b72645db3 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -318,6 +318,8 @@ struct swap_info_struct { unsigned int pages; /* total of usable pages of swap */ atomic_long_t inuse_pages; /* number of those currently in use */ struct percpu_cluster __percpu *percpu_cluster; /* per cpu's swap locatio= n */ + struct percpu_cluster *global_cluster; /* Use one global cluster for rota= ting device */ + spinlock_t global_cluster_lock; /* Serialize usage of global cluster */ struct rb_root swap_extent_root;/* root of the swap extent rbtree */ struct block_device *bdev; /* swap device or bdev of swap file */ struct file *swap_file; /* seldom referenced */ diff --git a/mm/swapfile.c b/mm/swapfile.c index 0445a2db8492..482c531bdd8b 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -814,7 +814,10 @@ static unsigned int alloc_swap_scan_cluster(struct swa= p_info_struct *si, out: relocate_cluster(si, ci); unlock_cluster(ci); - __this_cpu_write(si->percpu_cluster->next[order], next); + if (si->flags & SWP_SOLIDSTATE) + __this_cpu_write(si->percpu_cluster->next[order], next); + else + si->global_cluster->next[order] =3D next; return found; } =20 @@ -875,9 +878,16 @@ static unsigned long cluster_alloc_swap_entry(struct s= wap_info_struct *si, int o struct swap_cluster_info *ci; unsigned int offset, found =3D 0; =20 - /* Fast path using per CPU cluster */ - local_lock(&si->percpu_cluster->lock); - offset =3D __this_cpu_read(si->percpu_cluster->next[order]); + if (si->flags & SWP_SOLIDSTATE) { + /* Fast path using per CPU cluster */ + local_lock(&si->percpu_cluster->lock); + offset =3D __this_cpu_read(si->percpu_cluster->next[order]); + } else { + /* Serialize HDD SWAP allocation for each device. */ + spin_lock(&si->global_cluster_lock); + offset =3D si->global_cluster->next[order]; + } + if (offset) { ci =3D lock_cluster(si, offset); /* Cluster could have been used by another order */ @@ -972,8 +982,10 @@ static unsigned long cluster_alloc_swap_entry(struct s= wap_info_struct *si, int o } } done: - local_unlock(&si->percpu_cluster->lock); - + if (si->flags & SWP_SOLIDSTATE) + local_unlock(&si->percpu_cluster->lock); + else + spin_unlock(&si->global_cluster_lock); return found; } =20 @@ -2774,6 +2786,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, special= file) mutex_unlock(&swapon_mutex); free_percpu(p->percpu_cluster); p->percpu_cluster =3D NULL; + kfree(p->global_cluster); + p->global_cluster =3D NULL; vfree(swap_map); kvfree(zeromap); kvfree(cluster_info); @@ -3179,17 +3193,24 @@ static struct swap_cluster_info *setup_clusters(str= uct swap_info_struct *si, for (i =3D 0; i < nr_clusters; i++) spin_lock_init(&cluster_info[i].lock); =20 - si->percpu_cluster =3D alloc_percpu(struct percpu_cluster); - if (!si->percpu_cluster) - goto err_free; + if (si->flags & SWP_SOLIDSTATE) { + si->percpu_cluster =3D alloc_percpu(struct percpu_cluster); + if (!si->percpu_cluster) + goto err_free; =20 - for_each_possible_cpu(cpu) { - struct percpu_cluster *cluster; + for_each_possible_cpu(cpu) { + struct percpu_cluster *cluster; =20 - cluster =3D per_cpu_ptr(si->percpu_cluster, cpu); + cluster =3D per_cpu_ptr(si->percpu_cluster, cpu); + for (i =3D 0; i < SWAP_NR_ORDERS; i++) + cluster->next[i] =3D SWAP_ENTRY_INVALID; + local_lock_init(&cluster->lock); + } + } else { + si->global_cluster =3D kmalloc(sizeof(*si->global_cluster), GFP_KERNEL); for (i =3D 0; i < SWAP_NR_ORDERS; i++) - cluster->next[i] =3D SWAP_ENTRY_INVALID; - local_lock_init(&cluster->lock); + si->global_cluster->next[i] =3D SWAP_ENTRY_INVALID; + spin_lock_init(&si->global_cluster_lock); } =20 /* @@ -3463,6 +3484,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialf= ile, int, swap_flags) bad_swap: free_percpu(si->percpu_cluster); si->percpu_cluster =3D NULL; + kfree(si->global_cluster); + si->global_cluster =3D NULL; inode =3D NULL; destroy_swap_extents(si); swap_cgroup_swapoff(si->type); --=20 2.47.1 From nobody Sat Feb 7 18:21:03 2026 Received: from mail-pl1-f169.google.com (mail-pl1-f169.google.com [209.85.214.169]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 992081DE3A8 for ; Tue, 24 Dec 2024 14:40:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.169 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051225; cv=none; b=AnNr6UCpVmRwZSuBCtjrjqzINsAajjCCBmLGpFgGhf7Bmn0l38g7tUfiXbY2bMkWnp2vdNM3CLl6cwwHuH/ttgDSvtjs9dwF6VsBRDlsoVHskjciFdFw6rcFTwnPb2UcOBdcf4JqkOUFgJ0EmsmsQCYuqJrQ5kYbxG8dyXC5wnw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1735051225; c=relaxed/simple; bh=y0kROfDcyNId0PVUxTp96RcjOH4fXODlJHU0slceqhU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=QHKz9M6NADmbM4jYX2vvESulSUug75oeXc0xsanjo7UZVncgrpoL+dD1qPKxOVUVfpM/y6j8kcozUuoDWGuQi4HnurRCjlvfUb5t5O3m0o55/IQQv4L9JFDH+SgMWCnPIC10qRkaXFdsWB5FwkO6kaXkJ/O6HXtG80AWsPlV1tU= 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=d4tm+s10; arc=none smtp.client-ip=209.85.214.169 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="d4tm+s10" Received: by mail-pl1-f169.google.com with SMTP id d9443c01a7336-21634338cfdso74757095ad.2 for ; Tue, 24 Dec 2024 06:40:23 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1735051223; x=1735656023; 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=oGCoWj+d4yQp+yoZIDEe8P3zgKNWoImSkpotl3PB1J8=; b=d4tm+s10AZsJYl4acGc4xk2a6ix+z/2SLVPsMdepBF/GJPp0fRvbR8TJsgSRRDhDFI P1gcAIj18RQjmXoxAm+DZ+xKIDHlwD1O9NqMyEESuExv5zXIiMeDvGxLtqn6MKmreJmW VsXu5gxmsIPbxENcVsC0fZBPQq3KGaSD5SncWupZCYmGze8Jsm+vbBAAMYJlfFt0LgP4 0yVGquMPebf5M6WCENxUlQf8rzQ+8zRQjx3zSFr4QdF0q83fSp5hauKgVifoLJRVzHFD IKsTz6s9hygi/mbPTooPb2ajZRTuUGqIVQ7S+r3y7mlK+MU55GDHK8TLIiBU4biShJ5F vlrg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1735051223; x=1735656023; 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=oGCoWj+d4yQp+yoZIDEe8P3zgKNWoImSkpotl3PB1J8=; b=eyKO928IjkdO3ZgltjhhIBUjYT+R6naparfAXgC79accB77/qZEADV27f/Ao7uVYkf ojulLOwA2btCQh8YyLSsPhu6UHQjCFVWFbksd04oRoq7bsAbeKEzhIYv/+RzZlsJ7i58 o+BFYrBxLLX4MV7TPIv78QmDZ8y8g2RMS7Vg2L2ilUs45VJEBuCcmKEzfulCGdR+c3zC ZUDYX2H8nXOLP9cG8v46ZJ1Zoqc2VruLJmwSA3kYmtDfafwlwBXeJPLsFk7ph7V+/OPr ttITMxgm5p/uNaSxmDltPt9WLOJrHY9djOGSTwsh6ZVf1eQGih//0EPmGjCMBTnlVur+ DaNQ== X-Forwarded-Encrypted: i=1; AJvYcCW3hP50t8DVseLoGB3riR3YY19bCE2sp2mF3AKYjnlNQuubdihxkUjBuZ8xnQxPujb4n8Pn6XyzXtiA/1c=@vger.kernel.org X-Gm-Message-State: AOJu0YzUM8FwhLpW4T+zr4OaTorQ9vPNaSy2XQ4wmdGwialuBjLxYhH/ KM1VoC8i8Z8T6yu6RmG0E66JF7pnTV6x5pGub2Haa38a7TUf1FXe X-Gm-Gg: ASbGncvXSZkVuVjSPWfuj4d+QuNRjgbZcWJh64Imt1JraVXlC7r1jCHgwX9NgU8NgR5 lpZzEqf9ZOjWE2hzzsDat3ZHXAKNDPFsQ5PwT9Y2nLAYidwqWNGM5mt/4iHYEc1pBOZIsVJluJR TgbWRaewSNFwOVs8OBk0YZFkzhKwnwH5dVahc5QWLSBIWRagSgJ5KwmJwOmgMwy37r+j/tackFk 998Nxx7o46D+vamnJtSMJP5Ir1045GUmnWuWAfk+eBIUMtMOksvvaTjLTQzXw+fEzAzuMSsgEzu 4A== X-Google-Smtp-Source: AGHT+IGAPgVHp5vUFJh+SSN/uYjKj3b0hRrsN2QqzC9V+t4vENg01vQU53MJCWTYsvcbffhDkXP5bA== X-Received: by 2002:a17:902:d4c9:b0:215:6f9b:e447 with SMTP id d9443c01a7336-219e6ebf228mr175354085ad.30.1735051222881; Tue, 24 Dec 2024 06:40:22 -0800 (PST) Received: from KASONG-MC4.tencent.com ([115.171.41.189]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cdec1sm90598735ad.136.2024.12.24.06.40.19 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 24 Dec 2024 06:40:22 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , Chris Li , Barry Song , Ryan Roberts , Hugh Dickins , Yosry Ahmed , "Huang, Ying" , Nhat Pham , Johannes Weiner , Kalesh Singh , linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v2 13/13] mm, swap_slots: remove slot cache for freeing path Date: Tue, 24 Dec 2024 22:38:11 +0800 Message-ID: <20241224143811.33462-14-ryncsn@gmail.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241224143811.33462-1-ryncsn@gmail.com> References: <20241224143811.33462-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 slot cache for freeing path is mostly for reducing the overhead of si->lock. As we have basically eliminated the si->lock usage for freeing path, it can be removed. This helps simplify the code, and avoids swap entries from being hold in cache upon freeing. The delayed freeing of entries have been causing trouble for further optimizations for zswap [1] and in theory will also cause more fragmentation, and extra overhead. Test with build linux kernel showed both performance and fragmentation is better without the cache: tiem make -j96 / 768M memcg, 4K pages, 10G ZRAM, avg of 4 test run:: Before: Sys time: 36047.78, Real time: 472.43 After: (-7.6% sys time, -7.3% real time) Sys time: 33314.76, Real time: 437.67 time make -j96 / 1152M memcg, 64K mTHP, 10G ZRAM, avg of 4 test run: Before: Sys time: 46859.04, Real time: 562.63 hugepages-64kB/stats/swpout: 1783392 hugepages-64kB/stats/swpout_fallback: 240875 After: (-23.3% sys time, -21.3% real time) Sys time: 35958.87, Real time: 442.69 hugepages-64kB/stats/swpout: 1866267 hugepages-64kB/stats/swpout_fallback: 158330 Sequential SWAP should be also slightly faster, tests didn't show a measurable difference though, at least no regression: Swapin 4G zero page on ZRAM (time in us): Before (avg. 1923756) 1912391 1927023 1927957 1916527 1918263 1914284 1934753 1940813 1921791 After (avg. 1922290): 1919101 1925743 1916810 1917007 1923930 1935152 1917403 1923549 1921913 Link: https://lore.kernel.org/all/CAMgjq7ACohT_uerSz8E_994ZZCv709Zor+43hdme= sW_59W1BWw@mail.gmail.com/[1] Suggested-by: Chris Li Signed-off-by: Kairui Song --- include/linux/swap_slots.h | 3 -- mm/swap_slots.c | 78 +++++---------------------------- mm/swapfile.c | 89 +++++++++++++++----------------------- 3 files changed, 44 insertions(+), 126 deletions(-) diff --git a/include/linux/swap_slots.h b/include/linux/swap_slots.h index 15adfb8c813a..840aec3523b2 100644 --- a/include/linux/swap_slots.h +++ b/include/linux/swap_slots.h @@ -16,15 +16,12 @@ struct swap_slots_cache { swp_entry_t *slots; int nr; int cur; - spinlock_t free_lock; /* protects slots_ret, n_ret */ - swp_entry_t *slots_ret; int n_ret; }; =20 void disable_swap_slots_cache_lock(void); void reenable_swap_slots_cache_unlock(void); void enable_swap_slots_cache(void); -void free_swap_slot(swp_entry_t entry); =20 extern bool swap_slot_cache_enabled; =20 diff --git a/mm/swap_slots.c b/mm/swap_slots.c index 13ab3b771409..9c7c171df7ba 100644 --- a/mm/swap_slots.c +++ b/mm/swap_slots.c @@ -43,17 +43,15 @@ static DEFINE_MUTEX(swap_slots_cache_mutex); /* Serialize swap slots cache enable/disable operations */ static DEFINE_MUTEX(swap_slots_cache_enable_mutex); =20 -static void __drain_swap_slots_cache(unsigned int type); +static void __drain_swap_slots_cache(void); =20 #define use_swap_slot_cache (swap_slot_cache_active && swap_slot_cache_ena= bled) -#define SLOTS_CACHE 0x1 -#define SLOTS_CACHE_RET 0x2 =20 static void deactivate_swap_slots_cache(void) { mutex_lock(&swap_slots_cache_mutex); swap_slot_cache_active =3D false; - __drain_swap_slots_cache(SLOTS_CACHE|SLOTS_CACHE_RET); + __drain_swap_slots_cache(); mutex_unlock(&swap_slots_cache_mutex); } =20 @@ -72,7 +70,7 @@ void disable_swap_slots_cache_lock(void) if (swap_slot_cache_initialized) { /* serialize with cpu hotplug operations */ cpus_read_lock(); - __drain_swap_slots_cache(SLOTS_CACHE|SLOTS_CACHE_RET); + __drain_swap_slots_cache(); cpus_read_unlock(); } } @@ -113,7 +111,7 @@ static bool check_cache_active(void) static int alloc_swap_slot_cache(unsigned int cpu) { struct swap_slots_cache *cache; - swp_entry_t *slots, *slots_ret; + swp_entry_t *slots; =20 /* * Do allocation outside swap_slots_cache_mutex @@ -125,28 +123,19 @@ static int alloc_swap_slot_cache(unsigned int cpu) if (!slots) return -ENOMEM; =20 - slots_ret =3D kvcalloc(SWAP_SLOTS_CACHE_SIZE, sizeof(swp_entry_t), - GFP_KERNEL); - if (!slots_ret) { - kvfree(slots); - return -ENOMEM; - } - mutex_lock(&swap_slots_cache_mutex); cache =3D &per_cpu(swp_slots, cpu); - if (cache->slots || cache->slots_ret) { + if (cache->slots) { /* cache already allocated */ mutex_unlock(&swap_slots_cache_mutex); =20 kvfree(slots); - kvfree(slots_ret); =20 return 0; } =20 if (!cache->lock_initialized) { mutex_init(&cache->alloc_lock); - spin_lock_init(&cache->free_lock); cache->lock_initialized =3D true; } cache->nr =3D 0; @@ -160,19 +149,16 @@ static int alloc_swap_slot_cache(unsigned int cpu) */ mb(); cache->slots =3D slots; - cache->slots_ret =3D slots_ret; mutex_unlock(&swap_slots_cache_mutex); return 0; } =20 -static void drain_slots_cache_cpu(unsigned int cpu, unsigned int type, - bool free_slots) +static void drain_slots_cache_cpu(unsigned int cpu, bool free_slots) { struct swap_slots_cache *cache; - swp_entry_t *slots =3D NULL; =20 cache =3D &per_cpu(swp_slots, cpu); - if ((type & SLOTS_CACHE) && cache->slots) { + if (cache->slots) { mutex_lock(&cache->alloc_lock); swapcache_free_entries(cache->slots + cache->cur, cache->nr); cache->cur =3D 0; @@ -183,20 +169,9 @@ static void drain_slots_cache_cpu(unsigned int cpu, un= signed int type, } mutex_unlock(&cache->alloc_lock); } - if ((type & SLOTS_CACHE_RET) && cache->slots_ret) { - spin_lock_irq(&cache->free_lock); - swapcache_free_entries(cache->slots_ret, cache->n_ret); - cache->n_ret =3D 0; - if (free_slots && cache->slots_ret) { - slots =3D cache->slots_ret; - cache->slots_ret =3D NULL; - } - spin_unlock_irq(&cache->free_lock); - kvfree(slots); - } } =20 -static void __drain_swap_slots_cache(unsigned int type) +static void __drain_swap_slots_cache(void) { unsigned int cpu; =20 @@ -224,13 +199,13 @@ static void __drain_swap_slots_cache(unsigned int typ= e) * There are no slots on such cpu that need to be drained. */ for_each_online_cpu(cpu) - drain_slots_cache_cpu(cpu, type, false); + drain_slots_cache_cpu(cpu, false); } =20 static int free_slot_cache(unsigned int cpu) { mutex_lock(&swap_slots_cache_mutex); - drain_slots_cache_cpu(cpu, SLOTS_CACHE | SLOTS_CACHE_RET, true); + drain_slots_cache_cpu(cpu, true); mutex_unlock(&swap_slots_cache_mutex); return 0; } @@ -269,39 +244,6 @@ static int refill_swap_slots_cache(struct swap_slots_c= ache *cache) return cache->nr; } =20 -void free_swap_slot(swp_entry_t entry) -{ - struct swap_slots_cache *cache; - - /* Large folio swap slot is not covered. */ - zswap_invalidate(entry); - - cache =3D raw_cpu_ptr(&swp_slots); - if (likely(use_swap_slot_cache && cache->slots_ret)) { - spin_lock_irq(&cache->free_lock); - /* Swap slots cache may be deactivated before acquiring lock */ - if (!use_swap_slot_cache || !cache->slots_ret) { - spin_unlock_irq(&cache->free_lock); - goto direct_free; - } - if (cache->n_ret >=3D SWAP_SLOTS_CACHE_SIZE) { - /* - * Return slots to global pool. - * The current swap_map value is SWAP_HAS_CACHE. - * Set it to 0 to indicate it is available for - * allocation in global pool - */ - swapcache_free_entries(cache->slots_ret, cache->n_ret); - cache->n_ret =3D 0; - } - cache->slots_ret[cache->n_ret++] =3D entry; - spin_unlock_irq(&cache->free_lock); - } else { -direct_free: - swapcache_free_entries(&entry, 1); - } -} - swp_entry_t folio_alloc_swap(struct folio *folio) { swp_entry_t entry; diff --git a/mm/swapfile.c b/mm/swapfile.c index 482c531bdd8b..c5b5a3cd2a92 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -53,14 +53,15 @@ static bool swap_count_continued(struct swap_info_struct *, pgoff_t, unsigned char); static void free_swap_count_continuations(struct swap_info_struct *); -static void swap_entry_range_free(struct swap_info_struct *si, swp_entry_t= entry, - unsigned int nr_pages); +static void swap_entry_range_free(struct swap_info_struct *si, + struct swap_cluster_info *ci, + swp_entry_t entry, unsigned int nr_pages); static void swap_range_alloc(struct swap_info_struct *si, unsigned int nr_entries); static bool folio_swapcache_freeable(struct folio *folio); static struct swap_cluster_info *lock_cluster(struct swap_info_struct *si, unsigned long offset); -static void unlock_cluster(struct swap_cluster_info *ci); +static inline void unlock_cluster(struct swap_cluster_info *ci); =20 static DEFINE_SPINLOCK(swap_lock); static unsigned int nr_swapfiles; @@ -261,10 +262,9 @@ static int __try_to_reclaim_swap(struct swap_info_stru= ct *si, folio_ref_sub(folio, nr_pages); folio_set_dirty(folio); =20 - /* Only sinple page folio can be backed by zswap */ - if (nr_pages =3D=3D 1) - zswap_invalidate(entry); - swap_entry_range_free(si, entry, nr_pages); + ci =3D lock_cluster(si, offset); + swap_entry_range_free(si, ci, entry, nr_pages); + unlock_cluster(ci); ret =3D nr_pages; out_unlock: folio_unlock(folio); @@ -1121,8 +1121,10 @@ static void swap_range_free(struct swap_info_struct = *si, unsigned long offset, * Use atomic clear_bit operations only on zeromap instead of non-atomic * bitmap_clear to prevent adjacent bits corruption due to simultaneous w= rites. */ - for (i =3D 0; i < nr_entries; i++) + for (i =3D 0; i < nr_entries; i++) { clear_bit(offset + i, si->zeromap); + zswap_invalidate(swp_entry(si->type, offset + i)); + } =20 if (si->flags & SWP_BLKDEV) swap_slot_free_notify =3D @@ -1427,9 +1429,9 @@ static unsigned char __swap_entry_free(struct swap_in= fo_struct *si, =20 ci =3D lock_cluster(si, offset); usage =3D __swap_entry_free_locked(si, offset, 1); - unlock_cluster(ci); if (!usage) - free_swap_slot(entry); + swap_entry_range_free(si, ci, swp_entry(si->type, offset), 1); + unlock_cluster(ci); =20 return usage; } @@ -1457,13 +1459,10 @@ static bool __swap_entries_free(struct swap_info_st= ruct *si, } for (i =3D 0; i < nr; i++) WRITE_ONCE(si->swap_map[offset + i], SWAP_HAS_CACHE); + if (!has_cache) + swap_entry_range_free(si, ci, entry, nr); unlock_cluster(ci); =20 - if (!has_cache) { - for (i =3D 0; i < nr; i++) - zswap_invalidate(swp_entry(si->type, offset + i)); - swap_entry_range_free(si, entry, nr); - } return has_cache; =20 fallback: @@ -1483,15 +1482,13 @@ static bool __swap_entries_free(struct swap_info_st= ruct *si, * Drop the last HAS_CACHE flag of swap entries, caller have to * ensure all entries belong to the same cgroup. */ -static void swap_entry_range_free(struct swap_info_struct *si, swp_entry_t= entry, - unsigned int nr_pages) +static void swap_entry_range_free(struct swap_info_struct *si, + struct swap_cluster_info *ci, + swp_entry_t entry, unsigned int nr_pages) { unsigned long offset =3D swp_offset(entry); unsigned char *map =3D si->swap_map + offset; unsigned char *map_end =3D map + nr_pages; - struct swap_cluster_info *ci; - - ci =3D lock_cluster(si, offset); =20 /* It should never free entries across different clusters */ VM_BUG_ON(ci !=3D offset_to_cluster(si, offset + nr_pages - 1)); @@ -1511,7 +1508,6 @@ static void swap_entry_range_free(struct swap_info_st= ruct *si, swp_entry_t entry free_cluster(si, ci); else partial_free_cluster(si, ci); - unlock_cluster(ci); } =20 static void cluster_swap_free_nr(struct swap_info_struct *si, @@ -1519,28 +1515,13 @@ static void cluster_swap_free_nr(struct swap_info_s= truct *si, unsigned char usage) { struct swap_cluster_info *ci; - DECLARE_BITMAP(to_free, BITS_PER_LONG) =3D { 0 }; - int i, nr; + unsigned long end =3D offset + nr_pages; =20 ci =3D lock_cluster(si, offset); - while (nr_pages) { - nr =3D min(BITS_PER_LONG, nr_pages); - for (i =3D 0; i < nr; i++) { - if (!__swap_entry_free_locked(si, offset + i, usage)) - bitmap_set(to_free, i, 1); - } - if (!bitmap_empty(to_free, BITS_PER_LONG)) { - unlock_cluster(ci); - for_each_set_bit(i, to_free, BITS_PER_LONG) - free_swap_slot(swp_entry(si->type, offset + i)); - if (nr =3D=3D nr_pages) - return; - bitmap_clear(to_free, 0, BITS_PER_LONG); - ci =3D lock_cluster(si, offset); - } - offset +=3D nr; - nr_pages -=3D nr; - } + do { + if (!__swap_entry_free_locked(si, offset, usage)) + swap_entry_range_free(si, ci, swp_entry(si->type, offset), 1); + } while (++offset < end); unlock_cluster(ci); } =20 @@ -1581,18 +1562,12 @@ void put_swap_folio(struct folio *folio, swp_entry_= t entry) return; =20 ci =3D lock_cluster(si, offset); - if (size > 1 && swap_is_has_cache(si, offset, size)) { - unlock_cluster(ci); - swap_entry_range_free(si, entry, size); - return; - } - for (int i =3D 0; i < size; i++, entry.val++) { - if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) { - unlock_cluster(ci); - free_swap_slot(entry); - if (i =3D=3D size - 1) - return; - lock_cluster(si, offset); + if (swap_is_has_cache(si, offset, size)) + swap_entry_range_free(si, ci, entry, size); + else { + for (int i =3D 0; i < size; i++, entry.val++) { + if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) + swap_entry_range_free(si, ci, entry, 1); } } unlock_cluster(ci); @@ -1601,6 +1576,7 @@ void put_swap_folio(struct folio *folio, swp_entry_t = entry) void swapcache_free_entries(swp_entry_t *entries, int n) { int i; + struct swap_cluster_info *ci; struct swap_info_struct *si =3D NULL; =20 if (n <=3D 0) @@ -1608,8 +1584,11 @@ void swapcache_free_entries(swp_entry_t *entries, in= t n) =20 for (i =3D 0; i < n; ++i) { si =3D _swap_info_get(entries[i]); - if (si) - swap_entry_range_free(si, entries[i], 1); + if (si) { + ci =3D lock_cluster(si, swp_offset(entries[i])); + swap_entry_range_free(si, ci, entries[i], 1); + unlock_cluster(ci); + } } } =20 --=20 2.47.1