From patchwork Mon Feb 19 08:20:40 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Kairui Song X-Patchwork-Id: 13562325 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 51953C48BC3 for ; Mon, 19 Feb 2024 08:21:05 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B81D38D0003; Mon, 19 Feb 2024 03:21:04 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id B323D8D0001; Mon, 19 Feb 2024 03:21:04 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9D25F8D0003; Mon, 19 Feb 2024 03:21:04 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id 8EE138D0001 for ; Mon, 19 Feb 2024 03:21:04 -0500 (EST) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 148341C01F7 for ; Mon, 19 Feb 2024 08:21:04 +0000 (UTC) X-FDA: 81807858048.02.95F5E97 Received: from mail-pg1-f182.google.com (mail-pg1-f182.google.com [209.85.215.182]) by imf24.hostedemail.com (Postfix) with ESMTP id 53CD0180005 for ; Mon, 19 Feb 2024 08:21:02 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=gmail.com header.s=20230601 header.b=UF1vr0ch; spf=pass (imf24.hostedemail.com: domain of ryncsn@gmail.com designates 209.85.215.182 as permitted sender) smtp.mailfrom=ryncsn@gmail.com; dmarc=pass (policy=none) header.from=gmail.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1708330862; h=from:from:sender:reply-to:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:references:dkim-signature; bh=JChNLde82L5m9AVzKziuQHuDxbxpj+2i5hnJOoXu0tI=; b=oDC54cSvyPwVy8YzO+ex4PB2etuHm87CbOOT8O2X47yDePTiP0VQbY2RcIf8PYSvsAKY/l MBd5A8T0TKB6PILtb6YOWSrThavMXXiFMOmVvWb0iFpT3f0zPmhWlZnIBP+P9wZYrbZd5S rwQI4NN1ygcl/CYBmm+zj1NkfThowN0= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1708330862; a=rsa-sha256; cv=none; b=kRuzmTNceIsxDaCK0T3A78wo/KGxDC4zgFYAb7QfcKQwAMwi3JzW73AD3D+B6sgJgwWm9a ik0/3vFOuIk42dpxy5xpcRqqoWwIYuZiMNewl9VS+rTIPYe0INI3rtsgNgJEWaK9FF2Rdu uV2xPk+N5uBXgV8IM0QoqeQOuuJkewk= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=gmail.com header.s=20230601 header.b=UF1vr0ch; spf=pass (imf24.hostedemail.com: domain of ryncsn@gmail.com designates 209.85.215.182 as permitted sender) smtp.mailfrom=ryncsn@gmail.com; dmarc=pass (policy=none) header.from=gmail.com Received: by mail-pg1-f182.google.com with SMTP id 41be03b00d2f7-5c6bd3100fcso1927178a12.3 for ; Mon, 19 Feb 2024 00:21:02 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1708330860; x=1708935660; darn=kvack.org; h=content-transfer-encoding:mime-version:reply-to:message-id:date :subject:cc:to:from:from:to:cc:subject:date:message-id:reply-to; bh=JChNLde82L5m9AVzKziuQHuDxbxpj+2i5hnJOoXu0tI=; b=UF1vr0ch2qXJVam3bDbzYE3fmIrl9gYzdl5CcT1AM6BBAg4BkPQXH0AMKh2Ks2+V9l vqlGYGCCwYJF5ZJU4cHr288PLZ6hwE0Qg5oSMiVRCP1GmHzo4W04EYzV2m8HFURMw3AG d2nT9KyUK3Ma/j0n6Bywxi3vyZlBdoJcdw0rPfF/4GPdtyx/EJ8LJJAQAKKZ3GJ/Hc2Q HDWmViSJDweP7yDos4LL284nnJ8yq1T+W6TyA6feneRcA4dS9HKCDg4EDuAjpRvmP1+z 7+Y8nq7FgG77j0nE5pWhvwZmGQWMCtB9AHNjzquHDptArmPhHpj4KJ9jg6/NmWacxui3 QcGg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1708330860; x=1708935660; h=content-transfer-encoding:mime-version:reply-to:message-id:date :subject:cc:to:from:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to; bh=JChNLde82L5m9AVzKziuQHuDxbxpj+2i5hnJOoXu0tI=; b=LjEHc80k0qOox/usWjJzCB5fCZXN/mYeR8HvK+rLJJCcTGuc05SVjewHM1zGSCu7rO 9nQN4JNkbnY0gRQvxf/C/WUMhj3i2pn6mJ7yAMohd0IkjIv2XuktBlCvosp/u1A6aJCz 2i1OHNdUVfBmPysJGdoVG186BdmozjUClxuKYZpfu0EIzfHRZ8MGlAkzUS2vyMMWwx5M nGeoiMiJEddMfI+OP7QHlJgIxkWUPwXaFNAF3zgNkZQrGGMcbdDJpdPPB/OL3LZQxPAS rADnISFh+rCazzPZhWJ0soosBKCYhSb6VmVHf6mrw/jbO8vG9c54iRi1r6MgM53sb4bX 4B1A== X-Gm-Message-State: AOJu0Yz4Ixst38cwxHveBWiG5MEcUWMEJ1dVBYeVkYx1jrvV81Ju/e6C fhG7APQTpsfBqsaJR0xk5wIDOnWEQsfT0ELUqJI+qlHRNQh9uHiyZuc72JuY/etlftH8 X-Google-Smtp-Source: AGHT+IFUzxl7M6z2ToajWeg4ujLZ5c7nVGQiaEFJostNyF9dytQWaQsSchxz4PUlEMzJihWTpC6nRg== X-Received: by 2002:a05:6a20:49b0:b0:19e:c34a:6fb2 with SMTP id fs48-20020a056a2049b000b0019ec34a6fb2mr7443677pzb.20.1708330860040; Mon, 19 Feb 2024 00:21:00 -0800 (PST) Received: from KASONG-MB2.tencent.com ([43.132.141.24]) by smtp.gmail.com with ESMTPSA id cp15-20020a17090afb8f00b0029929839db8sm4674849pjb.14.2024.02.19.00.20.55 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Mon, 19 Feb 2024 00:20:59 -0800 (PST) From: Kairui Song To: linux-mm@kvack.org Cc: Andrew Morton , "Huang, Ying" , Chris Li , Minchan Kim , Barry Song , Yu Zhao , SeongJae Park , David Hildenbrand , Hugh Dickins , Johannes Weiner , Matthew Wilcox , Michal Hocko , Yosry Ahmed , Aaron Lu , stable@vger.kernel.org, linux-kernel@vger.kernel.org, Kairui Song Subject: [PATCH v4] mm/swap: fix race when skipping swapcache Date: Mon, 19 Feb 2024 16:20:40 +0800 Message-ID: <20240219082040.7495-1-ryncsn@gmail.com> X-Mailer: git-send-email 2.43.0 Reply-To: Kairui Song MIME-Version: 1.0 X-Rspamd-Queue-Id: 53CD0180005 X-Rspam-User: X-Stat-Signature: 65g46hhiqrbxjd4is6sftgdscuqbag5u X-Rspamd-Server: rspam03 X-HE-Tag: 1708330862-393225 X-HE-Meta: U2FsdGVkX190CFVy7x8tSMgxTvDDg/UNMxHn4lhzdWfYvk2VD2wu+StWFNmO1mm5Z4LCLpHiIGF/Zc/UrHtx3nm27J80GoF+Q72JdOaomwALrP7dqmpjYwpqF9IaCHA71FSS2y6ixfvpbrpCjyTeiqapB58RGLZUlpOlcyql9ZYOyHG7gtalORUOGmGkvBv0Zj5FgL5A6DxrBtTW8I8NLbCMx8Y0Zse3E7KY7y4oy5Xqg65lOwI6IPCPClhRPXgC/SLikQImsimfpXPlddy9PodwioouGNImq8ns26v5o1avDctMldiFpNFpmkiZKo4xrzXIwxZrA2KjqbG6WYSlSx1me8sipjRZOKJ38alJGOr/XMt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KlKeExDh8W/wHFzgZahQq1GeOBj+qS0ZrdFTufKU/t05CTc2wMhEK61GJqnSpvbfgKleXnw3oFZ4Ly6gHskM6jXirnY+s78iW7rWMB4aebLI/SRYe57RwCRib2hceYwQkQmyWHw4H/f/s3HPoPzeYuS4HaSImpcExxfroAUqDj/HSLd8aI505UYZiP4mnXfBL2Ed148kJsu4duq+FbJWELefPR+YUloz/9jzUHDejcIhM7ngk3ty3wlAiDICtAWkwVObKsr1f0fah22wGPdQ+RuumoTPWkCKxAoPxxRlzzfk2H1K9s1ixwNsiKJIiWwD1x+Nf X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: From: Kairui Song When skipping swapcache for SWP_SYNCHRONOUS_IO, if two or more threads swapin the same entry at the same time, they get different pages (A, B). Before one thread (T0) finishes the swapin and installs page (A) to the PTE, another thread (T1) could finish swapin of page (B), swap_free the entry, then swap out the possibly modified page reusing the same entry. It breaks the pte_same check in (T0) because PTE value is unchanged, causing ABA problem. Thread (T0) will install a stalled page (A) into the PTE and cause data corruption. One possible callstack is like this: CPU0 CPU1 ---- ---- do_swap_page() do_swap_page() with same entry swap_read_folio() <- read to page A swap_read_folio() <- read to page B ... set_pte_at() swap_free() <- entry is free pte_same() <- Check pass, PTE seems unchanged, but page A is stalled! swap_free() <- page B content lost! set_pte_at() <- staled page A installed! And besides, for ZRAM, swap_free() allows the swap device to discard the entry content, so even if page (B) is not modified, if swap_read_folio() on CPU0 happens later than swap_free() on CPU1, it may also cause data loss. To fix this, reuse swapcache_prepare which will pin the swap entry using the cache flag, and allow only one thread to swap it in, also prevent any parallel code from putting the entry in the cache. Release the pin after PT unlocked. Racers just loop and wait since it's a rare and very short event. A schedule_timeout_uninterruptible(1) call is added to avoid repeated page faults wasting too much CPU, causing livelock or adding too much noise to perf statistics. A similar livelock issue was described in commit 029c4628b2eb ("mm: swap: get rid of livelock in swapin readahead") Reproducer: This race issue can be triggered easily using a well constructed reproducer and patched brd (with a delay in read path) [1]: With latest 6.8 mainline, race caused data loss can be observed easily: $ gcc -g -lpthread test-thread-swap-race.c && ./a.out Polulating 32MB of memory region... Keep swapping out... Starting round 0... Spawning 65536 workers... 32746 workers spawned, wait for done... Round 0: Error on 0x5aa00, expected 32746, got 32743, 3 data loss! Round 0: Error on 0x395200, expected 32746, got 32743, 3 data loss! Round 0: Error on 0x3fd000, expected 32746, got 32737, 9 data loss! Round 0 Failed, 15 data loss! This reproducer spawns multiple threads sharing the same memory region using a small swap device. Every two threads updates mapped pages one by one in opposite direction trying to create a race, with one dedicated thread keep swapping out the data out using madvise. The reproducer created a reproduce rate of about once every 5 minutes, so the race should be totally possible in production. After this patch, I ran the reproducer for over a few hundred rounds and no data loss observed. Performance overhead is minimal, microbenchmark swapin 10G from 32G zram: Before: 10934698 us After: 11157121 us Cached: 13155355 us (Dropping SWP_SYNCHRONOUS_IO flag) Fixes: 0bcac06f27d7 ("mm, swap: skip swapcache for swapin of synchronous device") Link: https://github.com/ryncsn/emm-test-project/tree/master/swap-stress-race [1] Reported-by: "Huang, Ying" Closes: https://lore.kernel.org/lkml/87bk92gqpx.fsf_-_@yhuang6-desk2.ccr.corp.intel.com/ Signed-off-by: Kairui Song Cc: stable@vger.kernel.org Reviewed-by: "Huang, Ying" Acked-by: David Hildenbrand Acked-by: Chris Li Signed-off-by: Barry Song --- V3: https://lore.kernel.org/all/20240216095105.14502-1-ryncsn@gmail.com/ Update from V3: - Use schedule_timeout_uninterruptible(1) for now instead of schedule() to prevent the busy faulting task holds CPU and livelocks [Huang, Ying] V2: https://lore.kernel.org/all/20240206182559.32264-1-ryncsn@gmail.com/ Update from V2: - Add a schedule() if raced to prevent repeated page faults wasting CPU and add noise to perf statistics. - Use a bool to state the special case instead of reusing existing variables fixing error handling [Minchan Kim]. V1: https://lore.kernel.org/all/20240205110959.4021-1-ryncsn@gmail.com/ Update from V1: - Add some words on ZRAM case, it will discard swap content on swap_free so the race window is a bit different but cure is the same. [Barry Song] - Update comments make it cleaner [Huang, Ying] - Add a function place holder to fix CONFIG_SWAP=n built [SeongJae Park] - Update the commit message and summary, refer to SWP_SYNCHRONOUS_IO instead of "direct swapin path" [Yu Zhao] - Update commit message. - Collect Review and Acks. include/linux/swap.h | 5 +++++ mm/memory.c | 20 ++++++++++++++++++++ mm/swap.h | 5 +++++ mm/swapfile.c | 13 +++++++++++++ 4 files changed, 43 insertions(+) diff --git a/include/linux/swap.h b/include/linux/swap.h index 4db00ddad261..8d28f6091a32 100644 --- a/include/linux/swap.h +++ b/include/linux/swap.h @@ -549,6 +549,11 @@ static inline int swap_duplicate(swp_entry_t swp) return 0; } +static inline int swapcache_prepare(swp_entry_t swp) +{ + return 0; +} + static inline void swap_free(swp_entry_t swp) { } diff --git a/mm/memory.c b/mm/memory.c index 7e1f4849463a..a99f5e7be9a5 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -3799,6 +3799,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) struct page *page; struct swap_info_struct *si = NULL; rmap_t rmap_flags = RMAP_NONE; + bool need_clear_cache = false; bool exclusive = false; swp_entry_t entry; pte_t pte; @@ -3867,6 +3868,20 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) if (!folio) { if (data_race(si->flags & SWP_SYNCHRONOUS_IO) && __swap_count(entry) == 1) { + /* + * Prevent parallel swapin from proceeding with + * the cache flag. Otherwise, another thread may + * finish swapin first, free the entry, and swapout + * reusing the same entry. It's undetectable as + * pte_same() returns true due to entry reuse. + */ + if (swapcache_prepare(entry)) { + /* Relax a bit to prevent rapid repeated page faults */ + schedule_timeout_uninterruptible(1); + goto out; + } + need_clear_cache = true; + /* skip swapcache */ folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, vmf->address, false); @@ -4117,6 +4132,9 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) if (vmf->pte) pte_unmap_unlock(vmf->pte, vmf->ptl); out: + /* Clear the swap cache pin for direct swapin after PTL unlock */ + if (need_clear_cache) + swapcache_clear(si, entry); if (si) put_swap_device(si); return ret; @@ -4131,6 +4149,8 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) folio_unlock(swapcache); folio_put(swapcache); } + if (need_clear_cache) + swapcache_clear(si, entry); if (si) put_swap_device(si); return ret; diff --git a/mm/swap.h b/mm/swap.h index 758c46ca671e..fc2f6ade7f80 100644 --- a/mm/swap.h +++ b/mm/swap.h @@ -41,6 +41,7 @@ void __delete_from_swap_cache(struct folio *folio, void delete_from_swap_cache(struct folio *folio); void clear_shadow_from_swap_cache(int type, unsigned long begin, unsigned long end); +void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry); struct folio *swap_cache_get_folio(swp_entry_t entry, struct vm_area_struct *vma, unsigned long addr); struct folio *filemap_get_incore_folio(struct address_space *mapping, @@ -97,6 +98,10 @@ static inline int swap_writepage(struct page *p, struct writeback_control *wbc) return 0; } +static inline void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry) +{ +} + static inline struct folio *swap_cache_get_folio(swp_entry_t entry, struct vm_area_struct *vma, unsigned long addr) { diff --git a/mm/swapfile.c b/mm/swapfile.c index 556ff7347d5f..746aa9da5302 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -3365,6 +3365,19 @@ int swapcache_prepare(swp_entry_t entry) return __swap_duplicate(entry, SWAP_HAS_CACHE); } +void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry) +{ + struct swap_cluster_info *ci; + unsigned long offset = swp_offset(entry); + unsigned char usage; + + ci = lock_cluster_or_swap_info(si, offset); + usage = __swap_entry_free_locked(si, offset, SWAP_HAS_CACHE); + unlock_cluster_or_swap_info(si, ci); + if (!usage) + free_swap_slot(entry); +} + struct swap_info_struct *swp_swap_info(swp_entry_t entry) { return swap_type_to_swap_info(swp_type(entry));