mm: read the page cache without folio references
Subsystems (13)
Kiryl Shutsemau (Meta)
reviewercover mm: read the page cache without folio references
Small reads of one file from many CPUs all take and drop a reference on the same folio, and its refcount bounces between the CPUs. This series lets filemap_read() and shmem copy from the page cache without taking a reference. It is Linus' RFC [1], reworked: a folio that such a reader may copy from is freed only after an RCU grace period.
Only the folios that reads keep coming back to get the flag,PG_rcu_free: those that folio_mark_accessed() finds as accessed as the LRU records. Streaming reads and data that never gets hot are not deferred, so the memory held back stays small and most frees are not touched.
1 PG_rcu_free and the deferred free (64-bit only)
2-3 splice and fuse no longer reuse page cache folios that a
lockless reader may still copy from
4-7 NR_FREE_RCU_PAGES; an expedited grace period when a CPU's
deferred frees pile up and memory runs short; the waiting pages are freed before the allocator, alloc_contig_range() or memory offline give up
8 memory_failure() and soft offline deal with such pages
9-11 filemap_read() marks a folio accessed in one place and sets
PG_rcu_free on the folios that reads keep coming back to
12 the folios of an inode being evicted are freed at once 13 f_ra.prev_pos is written only when it changes 14 filemap_read() copies small folios without a reference 15 ... and large folios, with one more lookup per folio 16-17 shmem does the same 18 a debugfs switch to turn the reads off
Numbers: 64-vCPU KVM guest on a Threadripper 7975WX (Zen 4), 2G, no debug options; base is v7.3-rc7.
With the default mitigations, every read on this machine pays ~400 ns at the user/kernel boundary (TSA ~170 ns, SRSO ~230 ns): a single thread does ~1.8M reads/s. With mitigations=off it does 7.1-8.8M, and the 64-thread gain on ext4 grows from 4.5x to 13x. Linus measured 7.4-7.8M for one thread and 13.3M -> 304M for 64 threads on a Threadripper 3970X [1]. Rows without "mit=off" use the default mitigations.
16-byte pread() at offset 0, each thread with its own fd, M reads/s:
base this series
ext4, 64 threads 15.0-15.7 68.9-70.1
ext4, 64 threads, mit=off 17.2 217-220
tmpfs, 64 threads 1.6-1.7 71-72
tmpfs, 64 threads, mit=off 1.8-1.9 230-239
XFS, 64 threads 11.3-11.4 20.4-20.5
block dev, 64 threads 14.7 28.8-28.9
1 thread, any of them 1.6-1.9 1.7-2.0 The mit=off rows are from an earlier version with the same small-read path. Base tmpfs takes the folio lock on every read: 64 threads read as fast as one. XFS and the block device take i_rwsem shared on every read (XFS_IOLOCK_SHARED, inode_lock_shared() in blkdev_read_iter()), and its count bounces in place of the refcount.
64 threads reading 64K at offset 0 of one file, one large folio, k MiB/s:
base this series
huge tmpfs 96-100 1370-1390
ext4 756-775 1355-1373Large sequential reads of a 256M file: single-thread within ~1% of base, 16 threads at base.
Next to a process that touches 1400M in a loop: no OOM kill. A load that drops 1G of hot data with FADV_DONTNEED every round runs between 9% below and 1% above base, which itself spans 63-75k MiB/s there. A load that keeps refaulting loses 4-6%, as Linus' RFC does.
Open:
- Patch 12 relies on mapping_exiting() meaning that no file holds the inode open. f2fs called truncate_inode_pages_final() on open inodes for atomic writes; a fix is on its way [2].
- Patch 17 drops the folio lock from tmpfs reads. shmem_get_folio() held it only for the lookup, so a read was never atomic against a write or a hole punch; now a read also does not wait for one that holds the lock, as filemap_read() does not. I believe this is safe, but would like Hugh to double check.
- A deferred folio is uncharged from its memcg before it waits, as every page cache folio is. For a grace period it counts towards no cgroup.
- A migrated flagged folio is freed after a grace period, so a pageblock that compaction just emptied is free only then. defrag_mode leans on free pageblocks; not measured yet.
- The flag is a page flag, 64-bit only. On large configs it costs MGLRU one refs bit.
- On writably mapped files, architectures that implement flush_dcache_page() take the slow path.
- filemap_mark_hot() still tests uptodate. Willy pointed out that a filesystem clearing it under a reader is a filesystem bug; the test is cheap.
The series is also at:
https://git.kernel.org/pub/scm/linux/kernel/git/kas/linux.git rcu-free/rfc-v1
[1] https://lore.kernel.org/all/CAHk-=wjLjgfwgSZ1RDk4YdNFcV0ntosMO5AmBoHD76Zb3HFY7Q@mail.gmail.com/
[2] https://lore.kernel.org/all/[email protected]/
Kiryl Shutsemau (Meta) (11):
fuse: don't move a folio with PG_rcu_free into a fuse file
mm: count the pages waiting for a grace period
mm: free the pages waiting for a grace period before OOM
mm: free the pages waiting for a grace period before isolation fails mm/memory-failure: handle folios with PG_rcu_free mm/filemap: don't defer the free of folios of an inode being evicted mm/filemap: store the end of a read in f_ra only when it changes mm/filemap: read large folios without folio references mm/shmem: count accesses to a folio the way filemap_read() does mm/shmem: read without folio references
mm/filemap: add a debugfs switch for lockless page cache reads
Linus Torvalds (7):
mm: free PG_rcu_free folios only after an RCU grace period
splice: don't steal page cache folios
mm: expedite the grace period when a CPU has many deferred frees
mm: have folio_mark_accessed() return whether the folio is hot mm/filemap: mark a folio accessed in one place in filemap_read() mm/filemap: set PG_rcu_free on the folios that reads keep coming back
to
mm/filemap: read from the page cache without folio references
fs/fuse/dev.c | 4 + fs/splice.c | 51 ----- include/linux/mmzone.h | 1 + include/linux/page-flags.h | 24 +++ include/linux/pagemap.h | 12 ++ include/linux/swap.h | 2 +- include/linux/vm_event_item.h | 2 + include/trace/events/mmflags.h | 7 + mm/Kconfig | 15 ++ mm/filemap.c | 337 +++++++++++++++++++++++++++++++-- mm/folio.c | 46 +++-- mm/huge_memory.c | 1 + mm/internal.h | 3 + mm/memory-failure.c | 28 +++ mm/memory_hotplug.c | 7 + mm/page_alloc.c | 284 ++++++++++++++++++++++++++- mm/page_alloc.h | 1 + mm/shmem.c | 22 ++- mm/show_mem.c | 9 +- mm/vmstat.c | 6 + 20 files changed, 770 insertions(+), 92 deletions(-)
base-commit: c03c1a14507dfaf8b856c2608f9ac216021fc222
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 1/18 mm: free PG_rcu_free folios only after an RCU grace period
From: Linus Torvalds <[email protected]>
Reading a page cache folio without taking a reference would keep CPUs that read the same file from bouncing its refcount. But without a reference the folio can be freed, and its memory reused, while the reader copies from it.
Add PG_rcu_free: the free of a folio with the flag waits for an RCU grace period. A reader that saw the flag under rcu_read_lock(), and then still found the folio where it looked, can read it until rcu_read_unlock(). A split copies the flag, as such a reader may still be reading the new folios.
The folios wait on per-CPU lists, one grace period in flight per CPU:call_rcu() per folio would queue a callback for every folio of a truncated file. A work, which can reschedule, frees each batch. Reclaim depends on these frees, so the workqueue is WQ_MEM_RECLAIM.
The flag is 64-bit only (CONFIG_PAGE_RCU_FREE): page flags are scarce on 32-bit, and the contention this avoids is a problem of large machines.
pgfree_rcu in /proc/vmstat counts the deferred pages. Nothing sets the flag yet.
[kas: rework for flagging at read time, 64-bit only, shorter comments
and changelog]
--- include/linux/page-flags.h | 21 +++++++ include/linux/vm_event_item.h | 1 + include/trace/events/mmflags.h | 7 +++ mm/Kconfig | 12 ++++ mm/huge_memory.c | 1 + mm/memory-failure.c | 4 ++ mm/page_alloc.c | 105 +++++++++++++++++++++++++++++++++ mm/vmstat.c | 1 + 8 files changed, 152 insertions(+)
include/linux/page-flags.h +21 -0
@@ -111,6 +111,9 @@ enum pageflags { PG_swapbacked,/* Page is backed by RAM/swap */ PG_unevictable,/* Page is "unevictable" */ PG_dropbehind,/* drop pages on IO completion */ +#ifdef CONFIG_PAGE_RCU_FREE + PG_rcu_free,/* free only after an RCU grace period */ +#endif #ifdef CONFIG_MMU PG_mlocked, /* Page is vma mlocked */ #endif
@@ -602,6 +605,24 @@ FOLIO_FLAG(dropbehind, FOLIO_HEAD_PAGE) FOLIO_TEST_CLEAR_FLAG(dropbehind, FOLIO_HEAD_PAGE)__FOLIO_SET_FLAG (dropbehind,FOLIO_HEAD_PAGE ) +/* +* A lockless lookup that sees PG_rcu_free and then still finds the folio +* where it looked may read it until rcu_read_unlock(). Set under a +* reference, cleared only by the free. Not for hugetlb or +* free_pages_nolock(). + */ +#ifdef CONFIG_PAGE_RCU_FREE +FOLIO_TEST_FLAG(rcu_free, FOLIO_HEAD_PAGE) + FOLIO_TEST_SET_FLAG(rcu_free, FOLIO_HEAD_PAGE) + __FOLIO_CLEAR_FLAG(rcu_free, FOLIO_HEAD_PAGE) +#define __PG_RCU_FREE (1UL << PG_rcu_free) +#else +FOLIO_TEST_FLAG_FALSE(rcu_free) + FOLIO_TEST_SET_FLAG_FALSE(rcu_free) + __FOLIO_CLEAR_FLAG_NOOP(rcu_free) +#define __PG_RCU_FREE 0 +#endif +#ifdef CONFIG_HIGHMEM /* * Must use a macro here due to header dependency issues. page_zone() is not
include/linux/vm_event_item.h +1 -0
@@ -36,6 +36,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT, FOR_ALL_ZONES(ALLOCSTALL) FOR_ALL_ZONES(PGSCAN_SKIP) PGFREE, PGACTIVATE, PGDEACTIVATE, PGLAZYFREE, + PGFREE_RCU, PGFAULT, PGMAJFAULT, PGLAZYFREED, PGREUSE,
include/trace/events/mmflags.h +7 -0
@@ -117,6 +117,12 @@ TRACE_DEFINE_ENUM(___GFP_LAST_BIT);#define IF_HAVE_PG_IDLE (_name)#endif +#ifdef CONFIG_PAGE_RCU_FREE +#define IF_HAVE_PG_RCU_FREE (_name) ,{1UL << PG_##_name, __stringify(_name)} +#else +#define IF_HAVE_PG_RCU_FREE (_name) +#endif +#ifdef CONFIG_ARCH_USES_PG_ARCH_2 #define IF_HAVE_PG_ARCH_2 (_name) ,{1UL << PG_##_name, __stringify(_name)}#else
@@ -152,6 +158,7 @@ TRACE_DEFINE_ENUM(___GFP_LAST_BIT);DEF_PAGEFLAG_NAME (swapbacked), \ DEF_PAGEFLAG_NAME(unevictable), \ DEF_PAGEFLAG_NAME(dropbehind) \ +IF_HAVE_PG_RCU_FREE(rcu_free) \ IF_HAVE_PG_MLOCK(mlocked) \ IF_HAVE_PG_HWPOISON(hwpoison) \ IF_HAVE_PG_IDLE(idle) \
mm/Kconfig +12 -0
@@ -718,6 +718,18 @@ config PCP_BATCH_SCALE_MAX latency. This option sets the upper limit of scale factor to limit the maximum latency. +config PAGE_RCU_FREE + def_bool 64BIT + help + Reads from the page cache can copy from folios that are read + again and again without taking a reference on them, so small + reads of one file from many CPUs do not contend on the folio's + reference count. The cost is that memory freed from such + folios becomes reusable only after an RCU grace period. + + 64-bit only: it takes a page flag, and those are scarce on + 32-bit. + config PHYS_ADDR_T_64BIT def_bool 64BIT
mm/huge_memory.c +1 -0
@@ -3743,6 +3743,7 @@ static void __split_folio_to_order(struct folio *folio, int old_order,#endif (1L << PG_dirty) | (1L << PG_dropbehind) | + __PG_RCU_FREE | LRU_GEN_MASK | LRU_REFS_MASK)); new_folio->mapping = folio->mapping;
mm/memory-failure.c +4 -0
@@ -211,6 +211,10 @@ static bool page_handle_poison(struct page *page, bool hugepage_or_freepage, booreturn false; } +/* The free of a hwpoisoned page is not deferred: wait for readers */ +if (release &&folio_test_rcu_free (page_folio (page))) +synchronize_rcu (); +SetPageHWPoison (page);if (release)put_page (page);
mm/page_alloc.c +105 -0
123 lines not on this page · raw message
mm/vmstat.c +1 -0
@@ -1343,6 +1343,7 @@ const char * const vmstat_text[] = { [I(PGACTIVATE)] = "pgactivate", [I(PGDEACTIVATE)] = "pgdeactivate", [I(PGLAZYFREE)] = "pglazyfree", + [I(PGFREE_RCU)] = "pgfree_rcu", [I(PGFAULT)] = "pgfault", [I(PGMAJFAULT)] = "pgmajfault",
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 2/18 splice: don't steal page cache folios
In reply to Kiryl Shutsemau (Meta)From: Linus Torvalds <[email protected]>
PG_rcu_free holds back the reuse of a folio's memory until a grace period after the folio is freed. A stolen page cache pipe buffer is reused without being freed: remove_mapping() takes the folio out of the page cache and the caller keeps it. fuse_try_move_folio() puts it into a fuse file, where writes change it under a reader that found it before the steal.
Drop ->try_steal from page_cache_pipe_buf_ops. fuse_try_move_folio() and virtio_console's pipe_to_sg() then copy, as they already do when stealing fails. SPLICE_F_MOVE from the page cache into a fuse file or a virtio console now copies.
--- fs/splice.c | 51 --------------------------------------------------- 1 file changed, 51 deletions(-)
fs/splice.c +0 -51
@@ -55,56 +55,6 @@ static noinline void pipe_clear_nowait(struct file *file) }while (!try_cmpxchg (&file->f_mode, &fmode, fmode & ~FMODE_NOWAIT )); } -/* -* Attempt to steal a page from a pipe buffer. This should perhaps go into -* a vm helper function, it's already simplified quite a bit by the -* addition of remove_mapping(). If success is returned, the caller may -* attempt to reuse this page for another destination. -*/ -static bool page_cache_pipe_buf_try_steal (struct pipe_inode_info *pipe, -struct pipe_buffer *buf) -{ -struct folio *folio =page_folio (buf->page); -struct address_space *mapping; - -folio_lock (folio); - - mapping =folio_mapping (folio); -if (mapping) { -WARN_ON (!folio_test_uptodate (folio)); - -/* -* At least for ext2 with nobh option, we need to wait on -* writeback completing on this folio, since we'll remove it -* from the pagecache. Otherwise truncate wont wait on the -* folio, allowing the disk blocks to be reused by someone else -* before we actually wrote our data to them. fs corruption -* ensues. -*/ -folio_wait_writeback (folio); - -if (!filemap_release_folio (folio,GFP_KERNEL )) - goto out_unlock; - -/* -* If we succeeded in removing the mapping, set LRU flag -* and return good. -*/ -if (remove_mapping (mapping, folio)) { - buf->flags |=PIPE_BUF_FLAG_LRU ; -return true; - } - } - -/* -* Raced with truncate or failed to remove folio from current -* address space, unlock and return failure. -*/ -out_unlock: -folio_unlock (folio); -return false; -} -static void page_cache_pipe_buf_release (struct pipe_inode_info *pipe,struct pipe_buffer *buf) {
@@ -155,7 +105,6 @@ static int page_cache_pipe_buf_confirm(struct pipe_inode_info *pipe,const struct pipe_buf_operations page_cache_pipe_buf_ops = { .confirm = page_cache_pipe_buf_confirm, .release = page_cache_pipe_buf_release, - .try_steal = page_cache_pipe_buf_try_steal, .get = generic_pipe_buf_get, };
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 3/18 fuse: don't move a folio with PG_rcu_free into a fuse file
In reply to Kiryl Shutsemau (Meta)fuse_try_move_folio() takes the folio of a pipe buffer and puts it into a fuse file, where writes change it. A folio with PG_rcu_free may still be copied by a lockless page cache read that found it before it left the page cache.
Such a folio reaches fuse when a mapped file page is gifted with vmsplice(SPLICE_F_GIFT) and its file is then truncated. fuse_check_folio() refuses it only because the flag is not among those it allows, and with a dump_page().
Copy such a folio instead, as fuse does whenever it cannot take one.
--- fs/fuse/dev.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/fuse/dev.c +4 -0
@@ -1152,6 +1152,10 @@ static int fuse_try_move_folio(struct fuse_copy_state *cs, struct folio **foliop newfolio =page_folio (buf->page); +/* A lockless page cache read may still be copying from it */ +if (folio_test_rcu_free (newfolio)) + goto out_fallback_unlock; +folio_clear_uptodate (newfolio);folio_clear_mappedtodisk (newfolio);
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 4/18 mm: count the pages waiting for a grace period
In reply to Kiryl Shutsemau (Meta)Deferred folios have refcount 0 and are not on the free lists, so no counter shows them. Memory that waits for a grace period is missing from the free count and from every LRU count.
Count it per zone in NR_FREE_RCU_PAGES: nr_free_rcu in /proc/vmstat, free_rcu in show_free_areas(). Preparation for freeing the waiting pages sooner when they hold back memory that is needed.
--- include/linux/mmzone.h | 1 + mm/page_alloc.c | 4 ++++ mm/show_mem.c | 9 ++++++--- mm/vmstat.c | 2 ++ 4 files changed, 13 insertions(+), 3 deletions(-)
include/linux/mmzone.h +1 -0
@@ -228,6 +228,7 @@ enum zone_stat_item {NR_ZSPAGES ,/* allocated in zsmalloc */ #endifNR_FREE_CMA_PAGES , +NR_FREE_RCU_PAGES ,/* freed, waiting for an RCU grace period */ #ifdef CONFIG_UNACCEPTED_MEMORY NR_UNACCEPTED, #endif
mm/page_alloc.c +4 -0
@@ -1348,6 +1348,8 @@ static void rcu_free_pages(struct list_head *list)folio_batch_init (&fbatch);list_for_each_entry_safe (folio, next, list, lru) { +mod_zone_page_state (folio_zone (folio),NR_FREE_RCU_PAGES , + -folio_nr_pages (folio));if (!folio_batch_add (&fbatch, folio)) {free_unref_folios (&fbatch);cond_resched_tasks_rcu_qs ();
@@ -1375,9 +1377,11 @@ static void rcu_free_workfn(struct work_struct *work)static void rcu_free_defer (struct folio *folio) {struct rcu_free_pcpu *r =raw_cpu_ptr (&rcu_free_pcpu); +struct zone *zone =folio_zone (folio);unsigned long flags;spin_lock_irqsave (&r->lock, flags); +__mod_zone_page_state (zone,NR_FREE_RCU_PAGES ,folio_nr_pages (folio));list_add_tail (&folio->lru, &r->pending);rcu_free_start (r);spin_unlock_irqrestore (&r->lock, flags);
mm/show_mem.c +6 -3
@@ -204,7 +204,7 @@ static void show_free_areas(unsigned int filter, const nodemask_t *nodemask," mapped:%lu shmem:%lu pagetables:%lu\n" " sec_pagetables:%lu bounce:%lu\n" " kernel_misc_reclaimable:%lu\n" -" free:%lu free_pcp:%lu free_cma:%lu\n" , +" free:%lu free_pcp:%lu free_cma:%lu free_rcu:%lu\n" ,global_node_page_state (NR_ACTIVE_ANON ),global_node_page_state (NR_INACTIVE_ANON ), global_node_page_state(NR_ISOLATED_ANON),
@@ -224,7 +224,8 @@ static void show_free_areas(unsigned int filter, const nodemask_t *nodemask,global_node_page_state (NR_KERNEL_MISC_RECLAIMABLE ),global_zone_page_state (NR_FREE_PAGES ), free_pcp, - global_zone_page_state(NR_FREE_CMA_PAGES)); +global_zone_page_state (NR_FREE_CMA_PAGES ), + global_zone_page_state(NR_FREE_RCU_PAGES));for_each_online_pgdat (pgdat) {if (show_mem_node_skip (filter, pgdat->node_id, nodemask))
@@ -325,6 +326,7 @@ static void show_free_areas(unsigned int filter, const nodemask_t *nodemask," free_pcp:%lukB" " local_pcp:%lukB" " free_cma:%lukB" +" free_rcu:%lukB" "\n" , zone->name, K(zone_page_state(zone, NR_FREE_PAGES)),
@@ -351,7 +353,8 @@ static void show_free_areas(unsigned int filter, const nodemask_t *nodemask,0UL ,K (free_pcp),K ((unsigned long )this_cpu_read (zone->per_cpu_pageset->count)), - K(zone_page_state(zone, NR_FREE_CMA_PAGES))); +K (zone_page_state (zone,NR_FREE_CMA_PAGES )), + K(zone_page_state(zone, NR_FREE_RCU_PAGES)));printk ("lowmem_reserve[]:" );for (i =0 ; i <MAX_NR_ZONES ; i++)printk (KERN_CONT " %ld" , zone->lowmem_reserve[i]);
mm/vmstat.c +2 -0
@@ -1212,6 +1212,7 @@ const char * const vmstat_text[] = { [I(NR_ZSPAGES)] = "nr_zspages", #endif [I(NR_FREE_CMA_PAGES)] = "nr_free_cma", + [I (NR_FREE_RCU_PAGES )] ="nr_free_rcu" , #ifdef CONFIG_UNACCEPTED_MEMORY [I(NR_UNACCEPTED)] = "nr_unaccepted", #endif
@@ -2023,6 +2024,7 @@ static int vmstat_refresh(const struct ctl_table *table, int write,switch (i) {case NR_ZONE_WRITE_PENDING :case NR_FREE_CMA_PAGES : +case NR_FREE_RCU_PAGES :continue ; } val =atomic_long_read (&vm_zone_stat[i]);
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 5/18 mm: expedite the grace period when a CPU has many deferred frees
In reply to Kiryl Shutsemau (Meta)From: Linus Torvalds <[email protected]>
A deferred folio waits one to two grace periods on its CPU's list, where the page allocator cannot use it. A CPU that frees many flagged folios at once, for example when a file is truncated, can hold a lot of memory there.
When more than 4 MiB is pending on a CPU, a work takes both of the CPU's lists and frees them after an expedited grace period. That grace period starts after the take, so it covers every reader that found one of the folios. The task that frees them does not wait.
An expedited grace period interrupts every CPU, so keep it for when the memory matters. That is when the zone is below its high watermark, or when the pages waiting in it are more than an eighth of its free pages. The watermark alone comes too late for a bulk free. A truncate or fadvise(POSIX_FADV_DONTNEED) of a hot range defers all of it while the zone still has memory. When the readers that refill the range then run short, nothing is freed that would check again.
With rcu_normal, as on PREEMPT_RT, the expedited grace period is a normal one.
pgfree_rcu_expedite in /proc/vmstat counts the expedite runs that freed something.
[kas: take both lists, expedite only when the memory matters, rewrote
the changelog]
--- include/linux/vm_event_item.h | 2 +- mm/page_alloc.c | 61 ++++++++++++++++++++++++++++++++++- mm/vmstat.c | 1 + 3 files changed, 62 insertions(+), 2 deletions(-)
include/linux/vm_event_item.h +1 -1
@@ -36,7 +36,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT, FOR_ALL_ZONES(ALLOCSTALL) FOR_ALL_ZONES(PGSCAN_SKIP) PGFREE, PGACTIVATE, PGDEACTIVATE, PGLAZYFREE, - PGFREE_RCU, + PGFREE_RCU, PGFREE_RCU_EXPEDITE, PGFAULT, PGMAJFAULT, PGLAZYFREED, PGREUSE,
mm/page_alloc.c +60 -1
119 lines not on this page · raw message
mm/vmstat.c +1 -0
@@ -1345,6 +1345,7 @@ const char * const vmstat_text[] = { [I(PGDEACTIVATE)] = "pgdeactivate", [I(PGLAZYFREE)] = "pglazyfree", [I(PGFREE_RCU)] = "pgfree_rcu", + [I(PGFREE_RCU_EXPEDITE)] = "pgfree_rcu_expedite", [I(PGFAULT)] = "pgfault", [I(PGMAJFAULT)] = "pgmajfault",
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 6/18 mm: free the pages waiting for a grace period before OOM
In reply to Kiryl Shutsemau (Meta)When reclaim fails, should_reclaim_retry() looks only at free and reclaimable pages. It can hand the allocation to the OOM killer while enough memory is about to come back from the pages that wait for a grace period.
Before should_reclaim_retry() gives up, free the waiting pages if they would bring an eligible zone above its min watermark, and retry. That costs an expedited grace period, which is cheap next to the OOM killer. The retries are bounded per no-progress streak, so a drain that does not help still ends in an OOM kill.
pgfree_rcu_drain in /proc/vmstat counts the drains that freed something.
--- include/linux/vm_event_item.h | 2 +- mm/page_alloc.c | 88 +++++++++++++++++++++++++++++++++-- mm/vmstat.c | 1 + 3 files changed, 86 insertions(+), 5 deletions(-)
include/linux/vm_event_item.h +1 -1
@@ -36,7 +36,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT, FOR_ALL_ZONES(ALLOCSTALL) FOR_ALL_ZONES(PGSCAN_SKIP) PGFREE, PGACTIVATE, PGDEACTIVATE, PGLAZYFREE, - PGFREE_RCU, PGFREE_RCU_EXPEDITE, + PGFREE_RCU, PGFREE_RCU_EXPEDITE, PGFREE_RCU_DRAIN, PGFAULT, PGMAJFAULT, PGLAZYFREED, PGREUSE,
mm/page_alloc.c +84 -4
144 lines not on this page · raw message
mm/vmstat.c +1 -0
@@ -1346,6 +1346,7 @@ const char * const vmstat_text[] = { [I(PGLAZYFREE)] = "pglazyfree", [I(PGFREE_RCU)] = "pgfree_rcu", [I(PGFREE_RCU_EXPEDITE)] = "pgfree_rcu_expedite", + [I(PGFREE_RCU_DRAIN)] = "pgfree_rcu_drain", [I(PGFAULT)] = "pgfault", [I(PGMAJFAULT)] = "pgmajfault",
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH 06/18] mm: free the pages waiting for a grace period before OOM
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] mm: rcu_free_drain() fails to wait for in-flight RCU free workers - [High] mm: rcu_free_wait()…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] mm: rcu_free_drain() fails to wait for in-flight RCU free workers
- [High] mm: rcu_free_wait() passes high order to __zone_watermark_ok()
- [High] mm: should_reclaim_retry() splits reclaimable and RCU-waiting pages
- [High] mm: rcu_free_drain() leaves freed pages on PCP lists instead of buddy --
commit 7de2bde642756023a3c02e6554282a28f501cd38
Author: Kiryl Shutsemau (Meta) <[email protected]>
mm: free the pages waiting for a grace period before OOM
This commit adds rcu_free_wait() and rcu_free_drain() to should_reclaim_retry() so that pages deferred for an RCU grace period are drained via an expedited grace period before giving up and invoking the OOM killer. It also introduces the PGFREE_RCU_DRAIN vmstat event to count drains that freed pages.
Quoted 20 lines
mm/page_alloc.c +12
-0@@ -1445,6 +1445,29 @@ static void rcu_free_defer(struct folio *folio)queue_work (rcu_free_wq, &r->expedite); } +/* +* Free what every CPU's lists hold. A concurrent drain holds the lock +* until it has freed what it took. +*/ +static void rcu_free_drain (void ) +{ +static DEFINE_MUTEX (lock); +LIST_HEAD (list); +int cpu; + +mutex_lock (&lock); +for_each_possible_cpu (cpu) {
mm/page_alloc.c static void rcu_free_defer(struct folio *folio) · line 1469
Quoted 10 lines
mm/page_alloc.c +10
-0+struct rcu_free_pcpu *r =per_cpu_ptr (&rcu_free_pcpu, cpu); + +spin_lock_irq (&r->lock); +rcu_free_take (r, &list); +spin_unlock_irq (&r->lock); + } +if (rcu_free_flush (&list)) +count_vm_event (PGFREE_RCU_DRAIN ); +mutex_unlock (&lock); +}
[Severity: High]
What happens if rcu_free_expedite_workfn() or rcu_free_workfn() has already spliced the folios off r->batch and r->pending before rcu_free_drain() runs?
In rcu_free_expedite_workfn(), the worker takes the per-CPU lists into a local list and drops r->lock before blocking in synchronize_rcu_expedited():
mm/page_alloc.c:rcu_free_expedite_workfn() {
spin_lock_irq(&r->lock);
rcu_free_take(r, &list);
spin_unlock_irq(&r->lock);
if (rcu_free_flush(&list))
count_vm_event(PGFREE_RCU_EXPEDITE);
}Similarly, rcu_free_workfn() splices r->batch into a local list under r->lock before calling rcu_free_pages(), and NR_FREE_RCU_PAGES is only decremented inside rcu_free_pages() as each folio is freed.
Because neither worker acquires the mutex in rcu_free_drain(), a task entering rcu_free_wait() -> rcu_free_drain() while a worker is in flight sees elevated NR_FREE_RCU_PAGES, finds r->batch and r->pending empty, and returns immediately from rcu_free_flush(&list) without waiting. Once *no_progress_loops > MAX_RECLAIM_RETRIES, should_reclaim_retry() also jumps to out: and skips cond_resched().
Can __alloc_pages_slowpath() then spin through all MAX_RECLAIM_RETRIES iterations of rcu_free_waits while the worker is still in synchronize_rcu_expedited() and trigger a premature OOM kill?
[Severity: High]
Also, when rcu_free_drain() calls rcu_free_flush(&list) -> rcu_free_pages() -> free_unref_folios(), folios with pcp_allowed_order(order) are freed via free_frozen_page_commit() onto the local CPU's PCP list rather than directly into the zone's buddy free_area (and NR_FREE_PAGES is only updated when pages move from PCP to buddy).
When __alloc_pages_slowpath() jumps back to retry:, get_page_from_freelist() checks zone_watermark_fast() using NR_FREE_PAGES before reaching rmqueue(), and when __alloc_pages_direct_reclaim() sees *did_some_progress == 0, it jumps to out: without calling drain_all_pages(NULL):
mm/page_alloc.c:__alloc_pages_direct_reclaim() {
*did_some_progress = __perform_reclaim(gfp_mask, reclaim_order, ac);
if (unlikely(!(*did_some_progress)))
goto out;
...
drain_all_pages(NULL);out:
}
If the pages freed by rcu_free_drain() stay on the PCP list and do not increase NR_FREE_PAGES above min_wmark_pages(zone), won't the subsequent retry fail the watermark check in get_page_from_freelist() and proceed to __alloc_pages_may_oom() with those pages still stranded on PCP?
Quoted 35 lines
mm/page_alloc.c +28
-0+static void __init rcu_free_init (void ) {int cpu;@@ -4792,6 +4815,52 @@ bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)return !!__gfp_pfmemalloc_flags (gfp_mask); } +/* +* Reclaim is about to give up: if the pages waiting for a grace period +* would bring an eligible zone above its min watermark, free them and +* retry. Not for a dying task, which frees memory by exiting. +*/ +static bool rcu_free_wait (gfp_t gfp_mask,unsigned int order, +struct alloc_context *ac,int alloc_flags, +int *rcu_free_waits) +{ +struct zone *zone; +struct zoneref *z; + +if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE )) +return false; +if (tsk_is_oom_victim (current) ||fatal_signal_pending (current)) +return false; +if (*rcu_free_waits >=MAX_RECLAIM_RETRIES || + order >PAGE_ALLOC_COSTLY_ORDER ) +return false; + +for_each_zone_zonelist_nodemask (zone, z, ac->zonelist, + ac->highest_zoneidx, ac->nodemask) { +unsigned long waiting, available; + +if (cpusets_enabled () && (alloc_flags &ALLOC_CPUSET ) && + !__cpuset_zone_allowed (zone, gfp_mask)) +continue ;
mm/page_alloc.c bool gfp_pfmemalloc_allowed(gfp_t gfp_mask) · line 4854
Quoted 10 lines
mm/page_alloc.c +10
-0+ + waiting =zone_page_state_snapshot (zone,NR_FREE_RCU_PAGES ); +if (!waiting) +continue ; + + available = waiting + +zone_page_state_snapshot (zone,NR_FREE_PAGES ); +if (__zone_watermark_ok (zone, order,min_wmark_pages (zone), + ac->highest_zoneidx, alloc_flags, + available)) {
[Severity: High]
For non-costly high-order allocations (1 <= order <= PAGE_ALLOC_COSTLY_ORDER), does passing order to __zone_watermark_ok() here prevent rcu_free_drain() from being called when z->free_area[o >= order] is currently empty?
In __zone_watermark_ok(), the free_pages argument (available) is only checked against min + z->lowmem_reserve[highest_zoneidx], after which order > 0 requires an existing free block in z->free_area[o >= order]:
mm/page_alloc.c:__zone_watermark_ok() {
if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
return false;
/* If this is an order-0 request then the watermark is fine */
if (!order)
return true;
/* For a high-order request, check at least one suitable page is free */
for (o = order; o < NR_PAGE_ORDERS; o++) {
struct free_area *area = &z->free_area[o];
...
}Because the pages in NR_FREE_RCU_PAGES have not been freed into z->free_area yet, won't __zone_watermark_ok() return false before rcu_free_drain() has a chance to free them?
[Severity: High]
Also, should available in should_reclaim_retry() and rcu_free_wait() account for zone_reclaimable_pages(zone) and NR_FREE_RCU_PAGES together?
When direct reclaim frees folios marked with PG_rcu_free, __free_pages_prepare() diverts them to rcu_free_defer(), moving those pages out of zone_reclaimable_pages(zone) and into NR_FREE_RCU_PAGES rather than NR_FREE_PAGES.
In should_reclaim_retry(), the loop checks:
available = reclaimable = zone_reclaimable_pages(zone); available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
and if that fails, rcu_free_wait() checks:
available = waiting + zone_page_state_snapshot(zone, NR_FREE_PAGES);
If the pages needed to reach min_wmark_pages(zone) are split between remaining reclaimable pages on the LRU and already-reclaimed pages waiting in NR_FREE_RCU_PAGES, won't both checks fail individually and cause should_reclaim_retry() to return false while reclaim is still making progress?
Quoted 8 lines
mm/page_alloc.c +8
-0+ (*rcu_free_waits)++; +rcu_free_drain (); +return true; + } + } + +return false; +}
[ ... ]
Quoted 1 line
dari
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 7/18 mm: free the pages waiting for a grace period before isolation fails
In reply to Kiryl Shutsemau (Meta)alloc_contig_range() and offline_pages() migrate the folios out of a range and then check with test_pages_isolated() that every page is free. A migrated folio that had PG_rcu_free waits for a grace period after its free, so the check fails. alloc_contig_range() returns -EBUSY, and a CMA or gigantic page allocation can fail; offline_pages() retries until the grace period ends.
When the check fails and the zone has pages waiting, free them first. alloc_contig_range() then finds the start of the free range again, as the freed folio can merge with a free buddy below it. offline_pages() does so only after a pass that migrated folios: an offline stuck on a busy page would otherwise start an expedited grace period on every retry.
--- mm/memory_hotplug.c | 7 +++++++ mm/page_alloc.c | 28 +++++++++++++++++++++++++++- mm/page_alloc.h | 1 + 3 files changed, 35 insertions(+), 1 deletion(-)
mm/memory_hotplug.c +7 -0
@@ -1967,6 +1967,7 @@ int offline_pages(unsigned long start_pfn, unsigned long nr_pages, .nid = NUMA_NO_NODE, };unsigned long flags; +bool migrated;char *reason;int ret;unsigned long normal_pages =0 ;
@@ -2050,6 +2051,7 @@ int offline_pages(unsigned long start_pfn, unsigned long nr_pages, do { pfn = start_pfn; + migrated = false; do { /* * Historically we always checked for any signal and
@@ -2071,6 +2073,7 @@ int offline_pages(unsigned long start_pfn, unsigned long nr_pages,* out */ do_migrate_range (pfn, end_pfn); + migrated = true; } }while (!ret);
@@ -2092,6 +2095,10 @@ int offline_pages(unsigned long start_pfn, unsigned long nr_pages, ret =test_pages_isolated (start_pfn, end_pfn,PB_ISOLATE_MODE_MEM_OFFLINE ); +/* What this pass migrated can wait for a grace period */ +if (ret && migrated && +zone_page_state_snapshot (zone,NR_FREE_RCU_PAGES )) +rcu_free_sync (); }while (ret);
mm/page_alloc.c +27 -1
@@ -1468,6 +1468,23 @@ static void rcu_free_drain(void)mutex_unlock (&lock); } +/* Free every waiting folio, including those a work took off the lists */ +void rcu_free_sync (void ) +{ +int cpu; + +if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE )) +return ; + +rcu_free_drain (); +for_each_possible_cpu (cpu) { +struct rcu_free_pcpu *r =per_cpu_ptr (&rcu_free_pcpu, cpu); + +flush_work (&r->rwork.work); +flush_work (&r->expedite); + } +} +static void __init rcu_free_init (void ) {int cpu;
@@ -7632,7 +7649,16 @@ int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end, outer_start =find_large_buddy (start);/* Make sure the range is really isolated. */ -if (test_pages_isolated (outer_start, end, mode)) { + ret =test_pages_isolated (outer_start, end, mode); +if (ret &&zone_page_state_snapshot (cc.zone,NR_FREE_RCU_PAGES )) { +rcu_free_sync (); + +/* A freed folio can merge with a free buddy below start */ + outer_start =find_large_buddy (start); + ret =test_pages_isolated (outer_start, end, mode); + } + +if (ret) { ret = -EBUSY ; goto done; }
mm/page_alloc.h +1 -0
@@ -235,6 +235,7 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, int nid,alloc_hooks (__alloc_frozen_pages_noprof(__VA_ARGS__ )) void free_frozen_pages(struct page *page, unsigned int order);void free_unref_folios (struct folio_batch *fbatch); +void rcu_free_sync (void );#ifdef CONFIG_NUMA struct page *alloc_frozen_pages_noprof (gfp_t ,unsigned int order);
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH 07/18] mm: free the pages waiting for a grace period before isolation fails
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm: premature NR_FREE_RCU_PAGES decrement in rcu_free_pages() skips sync --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm: premature NR_FREE_RCU_PAGES decrement in rcu_free_pages() skips sync --
commit 173a808c17014ff8171f1ae96f92027767d39401
Author: Kiryl Shutsemau (Meta) <[email protected]>
mm: free the pages waiting for a grace period before isolation fails
This commit introduces rcu_free_sync() to drain and flush pages waiting for an RCU grace period when test_pages_isolated() fails in alloc_contig_range() and offline_pages().
Quoted 4 lines
mm/memory_hotplug.c +0
-0
[ ... ]
Quoted 42 lines
mm/memory_hotplug.c +4
-0@@ -2092,6 +2095,10 @@ int offline_pages(unsigned long start_pfn, unsigned long nr_pages, ret =test_pages_isolated (start_pfn, end_pfn,PB_ISOLATE_MODE_MEM_OFFLINE ); +/* What this pass migrated can wait for a grace period */ +if (ret && migrated && +zone_page_state_snapshot (zone,NR_FREE_RCU_PAGES )) +rcu_free_sync (); }while (ret);mm/page_alloc.c +17
-0@@ -1468,6 +1468,23 @@ static void rcu_free_drain(void)mutex_unlock (&lock); } +/* Free every waiting folio, including those a work took off the lists */ +void rcu_free_sync (void ) +{ +int cpu; + +if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE )) +return ; + +rcu_free_drain (); +for_each_possible_cpu (cpu) { +struct rcu_free_pcpu *r =per_cpu_ptr (&rcu_free_pcpu, cpu); + +flush_work (&r->rwork.work); +flush_work (&r->expedite); + } +} +static void __init rcu_free_init (void ) {int cpu;@@ -7632,7 +7649,16 @@ int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end, outer_start =find_large_buddy (start);
mm/page_alloc.c int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end, · line 7659
Quoted 10 lines
mm/page_alloc.c +8
-1/* Make sure the range is really isolated. */ -if (test_pages_isolated (outer_start, end, mode)) { + ret =test_pages_isolated (outer_start, end, mode); +if (ret &&zone_page_state_snapshot (cc.zone,NR_FREE_RCU_PAGES )) { +rcu_free_sync (); + +/* A freed folio can merge with a free buddy below start */ + outer_start =find_large_buddy (start); + ret =test_pages_isolated (outer_start, end, mode); + }
[Severity: Medium]
Can gating rcu_free_sync() on zone_page_state_snapshot(..., NR_FREE_RCU_PAGES) miss folios that a worker or concurrent drain is actively freeing in rcu_free_pages()?
rcu_free_sync() flushes r->rwork.work and r->expedite (in addition to acquiring the drain mutex in rcu_free_drain()) so that it waits for folios already taken off the per-CPU lists by a worker.
However, in rcu_free_pages(), NR_FREE_RCU_PAGES is decremented as each folio is added to fbatch, before free_unref_folios(&fbatch) prepares the pages and returns them to the buddy allocator:
mm/page_alloc.c:rcu_free_pages() {
...
list_for_each_entry_safe(folio, next, list, lru) {
nr += folio_nr_pages(folio);
mod_zone_page_state(folio_zone(folio), NR_FREE_RCU_PAGES,
-folio_nr_pages(folio));
if (!folio_batch_add(&fbatch, folio)) {
free_unref_folios(&fbatch);
cond_resched_tasks_rcu_qs();
}
}
if (folio_batch_count(&fbatch))
free_unref_folios(&fbatch);
...
}If rcu_free_pages() has decremented NR_FREE_RCU_PAGES to 0 for the last waiting folios in the zone and is still executing free_unref_folios(&fbatch), those pages are not yet PageBuddy in the buddy allocator when test_pages_isolated() checks them, while zone_page_state_snapshot() already reads 0.
When that happens, wouldn't alloc_contig_frozen_range_noprof() skip rcu_free_sync() and return -EBUSY, and wouldn't offline_pages() skip rcu_free_sync() on the pass where migrated is true (before resetting migrated to false on the next pass)?
[ ... ]
mm/page_alloc.c int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end, · line 7664
Quoted 5 lines
mm/page_alloc.c +0
-0if (ret) { ret = -EBUSY ; goto done; }
[ ... ]
—
🤖 Generated by janitor_bot (expert review) Single-turn review. Let the author decide how to proceed. Reply with feedback if anything looks off.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 8/18 mm/memory-failure: handle folios with PG_rcu_free
In reply to Kiryl Shutsemau (Meta)A page whose free waits for an RCU grace period has refcount 0 and is neither on the LRU nor in the buddy allocator. memory_failure() and soft_offline_page() cannot handle such a page: get_any_page() retries a few times and gives up. Soft offline of the page fails, and a hard error is ignored. If the page is part of a large folio, the folio is later freed with the poisoned page in it, and that page can be handed out again.
Free the waiting pages first when the page looks like one of them. memory_failure() has to do it before it sets PG_hwpoison. The free of a poisoned order-0 page drops the page instead of returning it to the buddy allocator, so a later drain would still leave the error ignored.
A folio with PG_rcu_free that is still in use may be copied by a reader that holds no reference. When memory_failure() succeeds, its caller can unmap the page from the direct map under such a reader. Wait for a grace period before returning success. By then the page has left the page cache, or is an order-0 folio with PG_hwpoison, which a reader that starts after the grace period has to check.
Wait at the end, not right after setting PG_hwpoison. A large folio is split later, and until the new folios are in the page cache, a reader can still copy the poisoned page as part of the large one.
Both callers hold mf_mutex and can wait for the grace period.
--- mm/memory-failure.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+)
mm/memory-failure.c +24 -0
@@ -1565,6 +1565,21 @@ static int get_hwpoison_page(struct page *p, unsigned long flags)return ret; } +/* A page waiting for a grace period is not in the buddy yet: free it */ +static void mf_free_rcu_pages (struct page *p) +{ +if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE )) +return ; +if (page_count (p)) +return ; +if (!zone_page_state_snapshot (page_zone (p),NR_FREE_RCU_PAGES )) +return ; +if (is_free_buddy_page (p)) +return ; + +rcu_free_sync (); +} +/* * The caller must guarantee the folio isn't large folio, except hugetlb. * try_to_unmap() can't handle it.
@@ -2440,6 +2455,7 @@ int memory_failure(unsigned long pfn, int flags)if (res != -ENOENT ) goto unlock_mutex; +mf_free_rcu_pages (p);if (TestSetPageHWPoison (p)) { res = -EHWPOISON ;if (flags &MF_ACTION_REQUIRED )
@@ -2612,6 +2628,13 @@ int memory_failure(unsigned long pfn, int flags) identify_page_state: res =identify_page_state (pfn, p, page_flags); +/* +* The caller may unmap the page once this returns 0. Lockless +* readers that started before the page got PG_hwpoison, or before a +* split left it in a folio of its own, may still be copying it. +*/ +if (!res &&folio_test_rcu_free (folio)) +synchronize_rcu ();mutex_unlock (&mf_mutex);return res; unlock_page:
@@ -3003,6 +3026,7 @@ int soft_offline_page(unsigned long pfn, int flags) retry:get_online_mems (); +mf_free_rcu_pages (page); ret =get_hwpoison_page (page, flags |MF_SOFT_OFFLINE );put_online_mems ();
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH 08/18] mm/memory-failure: handle folios with PG_rcu_free
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] mm: PG_rcu_free folios freed in get_any_page() are not drained on retry - [High] mm…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] mm: PG_rcu_free folios freed in get_any_page() are not drained on retry
- [High] mm: mf_free_rcu_pages() skips rcu_free_sync() during rcu_free_pages()
- [High] mm/memory-failure: missing synchronize_rcu() when kill_accessing_process() returns 0 --
commit 0752670541e1c89c99d63ab6b10ada844735c05b
Author: Kiryl Shutsemau (Meta) <[email protected]>
mm/memory-failure: handle folios with PG_rcu_free
This commit updates memory_failure() and soft_offline_page() to handle folios with PG_rcu_free by draining pages waiting for an RCU grace period before attempting to grab the page, and waiting for a grace period before returning success from memory_failure().
Quoted 7 lines
mm/memory-failure.c +0
-0@@ -1565,6 +1565,21 @@ static int get_hwpoison_page(struct page *p, unsigned long flags)return ret; }
mm/memory-failure.c static int get_hwpoison_page(struct page *p, unsigned long flags) · line 1576
Quoted 10 lines
mm/memory-failure.c +9
-0+/* A page waiting for a grace period is not in the buddy yet: free it */ +static void mf_free_rcu_pages (struct page *p) +{ +if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE )) +return ; +if (page_count (p)) +return ; +if (!zone_page_state_snapshot (page_zone (p),NR_FREE_RCU_PAGES )) +return ;
[Severity: High]
Can checking NR_FREE_RCU_PAGES here cause mf_free_rcu_pages() to skip rcu_free_sync() while a target folio is still in the middle of being freed?
In mm/page_alloc.c:rcu_free_pages(), NR_FREE_RCU_PAGES is decremented before free_unref_folios() runs __free_pages_prepare() and returns the folios to the buddy allocator:
mm/page_alloc.c:rcu_free_pages() {
list_for_each_entry_safe(folio, next, list, lru) {
nr += folio_nr_pages(folio);
mod_zone_page_state(folio_zone(folio), NR_FREE_RCU_PAGES,
-folio_nr_pages(folio));
if (!folio_batch_add(&fbatch, folio)) {
free_unref_folios(&fbatch);
cond_resched_tasks_rcu_qs();
}
}
if (folio_batch_count(&fbatch))
free_unref_folios(&fbatch);
}Similarly, in folios_put_refs(), folio->_refcount is decremented to 0 before __page_cache_release() and mem_cgroup_uncharge_folios() run, prior to rcu_free_defer() incrementing NR_FREE_RCU_PAGES.
If the last RCU-freed folios in the zone are in either window when mf_free_rcu_pages() runs on another CPU, page_count(p) is 0, is_free_buddy_page(p) is false, and NR_FREE_RCU_PAGES is 0. That causes mf_free_rcu_pages() to return early without calling rcu_free_sync() (which otherwise waits on rcu_free_drain() and flushes r->rwork.work and r->expedite).
In memory_failure(), TestSetPageHWPoison(p) then sets PG_hwpoison before free_unref_folios() runs __free_pages_prepare(). For an order-0 folio, __free_pages_prepare() sees PageHWPoison(page) && !order and drops the page instead of placing it in the buddy allocator, causing get_hwpoison_page() to see !is_free_buddy_page(p) and ignore the error (MF_IGNORED). For a large folio entering rcu_free_defer() after page_count(p) became 0, it is queued on rcu_free_pcpu with PG_hwpoison set and later freed back to the buddy allocator.
Quoted 10 lines
mm/memory-failure.c +6
-0+if (is_free_buddy_page (p)) +return ; + +rcu_free_sync (); +} +/* * The caller must guarantee the folio isn't large folio, except hugetlb. * try_to_unmap() can't handle it.
mm/memory-failure.c int memory_failure(unsigned long pfn, int flags) · line 2459
Quoted 5 lines
mm/memory-failure.c +1
-0@@ -2440,6 +2455,7 @@ int memory_failure(unsigned long pfn, int flags)if (res != -ENOENT ) goto unlock_mutex; +mf_free_rcu_pages (p);if (TestSetPageHWPoison (p)) {
[Severity: High]
What happens if a folio with PG_rcu_free still has a reference when mf_free_rcu_pages() runs (so page_count(p) > 0 returns early), and its last reference is dropped inside get_hwpoison_page() -> get_any_page()?
Inside get_any_page(), the last reference on a PG_rcu_free folio can drop to 0 in a few ways:
1. When MF_COUNT_INCREASED is set (for example via madvise_inject_error()), page_count(p) >= 1 during mf_free_rcu_pages(). If the page is not immediately HWPoisonHandlable() (such as !PageLRU(p) because it was truncated while in a per-CPU lru_add batch), get_any_page() calls put_page(p) and shake_page(p) and jumps to try_again.
2. Without MF_COUNT_INCREASED, if a truncated PG_rcu_free folio is still in a per-CPU folio_batch, __get_hwpoison_page() returns -EBUSY and get_any_page() calls shake_page(p) -> lru_add_drain_all(), which frees the folio.
3. A concurrent task drops the last reference on the folio after mf_free_rcu_pages() checked page_count(p), causing __get_hwpoison_page() to return 0 and get_any_page() to retry:
mm/memory-failure.c:get_any_page() {
} else if (!PageHuge(p) && !is_free_buddy_page(p)) {
/* We raced with put_page, retry. */
if (pass++ < GET_PAGE_MAX_RETRY_NUM)
goto try_again;
ret = -EIO;
}
}When the folio is freed during any of those paths, __free_pages_prepare() checks:
mm/page_alloc.c:__free_pages_prepare() {
if (unlikely(folio_test_rcu_free(folio)) &&
!(PageHWPoison(page) && !order)) {
VM_WARN_ON_ONCE(fpi_flags & FPI_NOLOCK);
__folio_clear_rcu_free(folio);
count_vm_events(PGFREE_RCU, 1 << order);\n rcu_free_defer(folio);
return false;
}
}Because neither get_any_page() nor shake_page() drains RCU-freed pages on retry, a large folio in memory_failure() (or any PG_rcu_free folio in soft_offline_page()) is deferred via rcu_free_defer(), causing all retries in get_any_page() to see page_count(p) == 0 and !is_free_buddy_page(p) and fail with -EIO. In memory_failure(), PG_hwpoison is already set on p, so when the RCU grace period later expires, the large folio is freed into the buddy allocator with the poisoned subpage still inside it. And for an order-0 folio in memory_failure() freed after TestSetPageHWPoison(p), __free_pages_prepare() skips rcu_free_defer() and drops the page without putting it in the buddy allocator, so get_any_page() also fails with -EIO (MF_IGNORED).
Quoted 5 lines
mm/memory-failure.c +0
-0res = -EHWPOISON ;if (flags &MF_ACTION_REQUIRED )@@ -2612,6 +2628,13 @@ int memory_failure(unsigned long pfn, int flags) identify_page_state:
mm/memory-failure.c int memory_failure(unsigned long pfn, int flags) · line 2639
Quoted 10 lines
mm/memory-failure.c +7
-0res =identify_page_state (pfn, p, page_flags); +/* +* The caller may unmap the page once this returns 0. Lockless +* readers that started before the page got PG_hwpoison, or before a +* split left it in a folio of its own, may still be copying it. +*/ +if (!res &&folio_test_rcu_free (folio)) +synchronize_rcu ();mutex_unlock (&mf_mutex);return res;
[Severity: High]
Can memory_failure() return 0 without calling synchronize_rcu() when a second memory_failure() call hits the TestSetPageHWPoison(p) path?
Consider a lockless RCU reader in filemap_read_rcu_batch() that checks folio_contain_hwpoisoned_page(folio) before PG_hwpoison is set and begins copying from the page via the direct map in filemap_read_rcu_copy().
1. A first memory_failure() call (for instance from a background scrubber or UCNA) sets PG_hwpoison via TestSetPageHWPoison(p). In hwpoison_user_mappings() -> unmap_poisoned_folio(), because the page-cache folio is clean, TTU_HWPOISON is cleared and user PTEs are unmapped to pte_none without installing hwpoison swap entries. If me_pagecache_clean() then returns MF_FAILED (e.g. due to a transient extra refcount in has_extra_refcount() or truncate_error_folio() failing), identify_page_state() returns -EBUSY, so !res is false and memory_failure() unlocks mf_mutex without calling synchronize_rcu().
2. A racing Action Required MCE on the same PFN calls memory_failure(pfn, MF_ACTION_REQUIRED). TestSetPageHWPoison(p) returns true and calls:
mm/memory-failure.c:memory_failure() {
if (TestSetPageHWPoison(p)) {
res = -EHWPOISON;
if (flags & MF_ACTION_REQUIRED)
res = kill_accessing_process(current, pfn, flags);
if (flags & MF_COUNT_INCREASED)
put_page(p);
action_result(pfn, MF_MSG_ALREADY_POISONED, MF_FAILED);
goto unlock_mutex;
}
}Because the clean user PTEs were already unmapped without hwpoison swap entries, walk_page_range() in kill_accessing_process() finds no matching PTE in current->mm and returns 0. memory_failure() then jumps to unlock_mutex and returns 0 without waiting for an RCU grace period, allowing the caller (such as kill_me_maybe() -> set_mce_nospec(pfn)) to unmap the page from the kernel direct map while the lockless RCU reader is still copying from it.
[ ... ]
Quoted 4 lines
Signature · 2 lines
-- 2.51.2
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 9/18 mm: have folio_mark_accessed() return whether the folio is hot
In reply to Kiryl Shutsemau (Meta)From: Linus Torvalds <[email protected]>
Each call of folio_mark_accessed() moves a folio one step up what the LRU records of its accesses. Once the folio is at the top, the call leaves it as it was: the folio is as hot as the LRU can tell.
Return whether the call found the folio there. On the classic LRU that is active, referenced and not idle. On the multi-gen LRU it is PG_referenced, all the refs bits and PG_workingset, which lru_gen_inc_refs() now reports.
An unevictable folio counts as hot once it is referenced, and on the multi-gen LRU from the first call: it stays in memory in any case. A dropbehind folio is not hot: it is dropped after the read.
No caller uses the value yet. Preparation for reading the folios that it calls hot without a folio reference.
--- include/linux/swap.h | 2 +- mm/folio.c | 46 ++++++++++++++++++++++++++++++-------------- 2 files changed, 33 insertions(+), 15 deletions(-)
include/linux/swap.h +1 -1
@@ -295,7 +295,7 @@ extern unsigned long totalreserve_pages;/* linux/mm/folio.c */ void folio_add_lru (struct folio *folio); -void folio_mark_accessed (struct folio *folio); +bool folio_mark_accessed (struct folio *folio);void lru_add_drain_all (void );enum lru_cache_drained {
mm/folio.c +32 -14
98 lines not on this page · raw message
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 10/18 mm/filemap: mark a folio accessed in one place in filemap_read()
In reply to Kiryl Shutsemau (Meta)From: Linus Torvalds <[email protected]>
filemap_read() calls folio_mark_accessed() in two places. Before the copy loop it marks the first folio of the batch, unless the previous read through the file ended in that folio. In the loop it marks every later folio.
The test made for the first folio also says "mark" for every later one. The loop gets to a later folio only after the folio before it was copied to its end, so last_pos is at the later folio's first byte and pos_same_folio() is false.
Do both in one helper, filemap_read_accessed(), called for each folio in the loop. For the first folio the call moves below the test of end_offset against the folio's start, which is false for it: the folio holds ki_pos, and end_offset is beyond ki_pos.
No change in behaviour intended. Preparation for deciding in the helper which folios are worth reading without a reference.
--- mm/filemap.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-)
mm/filemap.c +15 -10
@@ -2759,6 +2759,20 @@ static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio)return (pos1 >> shift == pos2 >> shift); } +/* +* filemap_read() is about to copy from @folio at @pos. @last_pos is where +* the previous read of this open file ended, or how far this one has got. +* +* Reading on in the folio that the last read ended in is not another access +* to it: a folio read in small pieces is marked accessed once. +*/ +static void filemap_read_accessed (struct folio *folio,loff_t pos, +loff_t last_pos) +{ +if (!pos_same_folio (pos, last_pos -1 , folio)) +folio_mark_accessed (folio); +} +static void filemap_end_dropbehind_read (struct folio *folio) {if (!folio_test_dropbehind (folio))
@@ -2844,14 +2858,6 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,*/ writably_mapped =mapping_writably_mapped (mapping); -/* -* When a read accesses the same folio several times, only -* mark it as accessed the first time. -*/ -if (!pos_same_folio (iocb->ki_pos, last_pos -1 , - fbatch.folios[0 ])) -folio_mark_accessed (fbatch.folios[0 ]); -for (i =0 ; i <folio_batch_count (&fbatch); i++) {struct folio *folio = fbatch.folios[i];size_t fsize =folio_size (folio);
@@ -2862,8 +2868,7 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,if (end_offset <folio_pos (folio))break ; -if (i >0 ) -folio_mark_accessed (folio); +filemap_read_accessed (folio, iocb->ki_pos, last_pos);/* * If users can be writing to this folio using arbitrary * virtual addresses, take care of potential aliasing
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 11/18 mm/filemap: set PG_rcu_free on the folios that reads keep coming back to
In reply to Kiryl Shutsemau (Meta)From: Linus Torvalds <[email protected]>
A folio with PG_rcu_free can be read without a reference, but its memory is held back for a grace period after it is freed. That trade is worth making only for folios that readers look up again and again. Flagging every page cache folio would also delay the free of streaming reads, truncated files and reclaimed cold data, which no reader comes back to.
Set the flag in filemap_read(), under the read's reference, when the folio turns out to be hot:
- folio_mark_accessed() finds it as accessed as the LRU records, or
- the read goes back to bytes that the previous read through the same open file has just read.
filemap_read() does not mark accessed the folio that the previous read ended in, so re-reads through one open file do not make a folio hotter. The second test is for that folio.
Leave alone a folio whose next read needs a reference anyway: not uptodate, readahead or dropbehind. Leave alone unevictable folios too. folio_mark_accessed() calls them hot after at most one access, so every ramfs folio that is read would get the flag. An initramfs deleted at switch_root would then have the free of all its folios deferred.
AS_RCU_READ records that an inode has had a folio flagged, so that a lockless read can skip the inodes that never had one.
pgfree_rcu_mark in /proc/vmstat counts the pages that get the flag.
[kas: count the marks, AS_RCU_READ, 64-bit only, shorter comment,
rewrote the changelog]
--- include/linux/pagemap.h | 12 +++++++++++ include/linux/vm_event_item.h | 1 + mm/filemap.c | 40 +++++++++++++++++++++++++++++++++-- mm/vmstat.c | 1 + 4 files changed, 52 insertions(+), 2 deletions(-)
include/linux/pagemap.h +12 -0
@@ -210,6 +210,7 @@ enum mapping_flags {AS_WRITEBACK_MAY_DEADLOCK_ON_RECLAIM =9 ,AS_KERNEL_FILE =10 ,/* mapping for a fake kernel file that shouldn't account usage to user cgroups */ +AS_RCU_READ =11 ,/* a folio has had PG_rcu_free */ /* Bits 16-25 are used for FOLIO_ORDER */ AS_FOLIO_ORDER_BITS =5 , AS_FOLIO_ORDER_MIN = 16,
@@ -269,6 +270,17 @@ static inline bool mapping_unevictable(const struct address_space *mapping)return mapping &&test_bit (AS_UNEVICTABLE , &mapping->flags); } +static inline void mapping_set_rcu_read (struct address_space *mapping) +{ +if (!test_bit (AS_RCU_READ , &mapping->flags)) +set_bit (AS_RCU_READ , &mapping->flags); +} + +static inline bool mapping_rcu_read (const struct address_space *mapping) +{ +return test_bit (AS_RCU_READ , &mapping->flags); +} +static inline void mapping_set_exiting (struct address_space *mapping) {set_bit (AS_EXITING , &mapping->flags);
include/linux/vm_event_item.h +1 -0
@@ -37,6 +37,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,FOR_ALL_ZONES (PGSCAN_SKIP)PGFREE ,PGACTIVATE ,PGDEACTIVATE ,PGLAZYFREE ,PGFREE_RCU ,PGFREE_RCU_EXPEDITE ,PGFREE_RCU_DRAIN , +PGFREE_RCU_MARK ,PGFAULT ,PGMAJFAULT ,PGLAZYFREED , PGREUSE,
mm/filemap.c +38 -2
@@ -2759,18 +2759,54 @@ static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio)return (pos1 >> shift == pos2 >> shift); } +/* +* Reads keep coming back to @folio: free it only after an RCU grace period +* from now on. Not if its next read needs a reference anyway. Not if it +* is unevictable: folio_mark_accessed() calls such a folio hot after at +* most one access, so every ramfs folio that is read would get the flag. +*/ +static void filemap_mark_hot (struct folio *folio) +{ +struct address_space *mapping; + +if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE )) +return ; +if (folio_test_rcu_free (folio) || !folio_test_uptodate (folio) || +folio_test_readahead (folio) ||folio_test_dropbehind (folio) || +folio_test_unevictable (folio)) +return ; +if (folio_test_set_rcu_free (folio)) +return ; + +count_vm_events (PGFREE_RCU_MARK ,folio_nr_pages (folio)); +/* NULL if the folio was truncated meanwhile */ + mapping =READ_ONCE (folio->mapping); +if (mapping) +mapping_set_rcu_read (mapping); +} +/* * filemap_read() is about to copy from @folio at @pos. @last_pos is where * the previous read of this open file ended, or how far this one has got. * * Reading on in the folio that the last read ended in is not another access * to it: a folio read in small pieces is marked accessed once. +* +* The folio is hot when folio_mark_accessed() finds it as accessed as the +* LRU records, or when this open file goes back to data that it has just +* read. */ static void filemap_read_accessed (struct folio *folio,loff_t pos,loff_t last_pos) { -if (!pos_same_folio (pos, last_pos -1 , folio)) -folio_mark_accessed (folio); +bool hot; + +if (pos_same_folio (pos, last_pos -1 , folio)) + hot = pos < last_pos; +else + hot =folio_mark_accessed (folio); +if (hot) +filemap_mark_hot (folio); }static void filemap_end_dropbehind_read (struct folio *folio)
mm/vmstat.c +1 -0
@@ -1347,6 +1347,7 @@ const char * const vmstat_text[] = { [I(PGFREE_RCU)] = "pgfree_rcu", [I(PGFREE_RCU_EXPEDITE)] = "pgfree_rcu_expedite", [I(PGFREE_RCU_DRAIN)] = "pgfree_rcu_drain", + [I(PGFREE_RCU_MARK)] = "pgfree_rcu_mark", [I(PGFAULT)] = "pgfault", [I(PGMAJFAULT)] = "pgmajfault",
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 12/18 mm/filemap: don't defer the free of folios of an inode being evicted
In reply to Kiryl Shutsemau (Meta)A hot folio keeps PG_rcu_free until it is freed. Deleting a file that was read a lot, or evicting its inode under memory pressure or at umount, then defers the free of all of its hot folios.
No lockless reader can be in the page cache of an inode being evicted:
the read holds the file open, and the open file holds the inode. Clear the flag when the final truncate removes the folio, which mapping_exiting() tells apart. A truncate of a file that may still be open keeps the deferral.
--- include/linux/page-flags.h | 5 ++++- mm/filemap.c | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-)
include/linux/page-flags.h +4 -1
@@ -608,17 +608,20 @@ FOLIO_FLAG(dropbehind, FOLIO_HEAD_PAGE)/* * A lockless lookup that sees PG_rcu_free and then still finds the folio * where it looked may read it until rcu_read_unlock(). Set under a -* reference, cleared only by the free. Not for hugetlb or +* reference. Cleared by the free, or when the folio's inode is evicted: +* no lockless lookup can reach it then. Not for hugetlb or * free_pages_nolock(). */ #ifdef CONFIG_PAGE_RCU_FREE FOLIO_TEST_FLAG(rcu_free, FOLIO_HEAD_PAGE) FOLIO_TEST_SET_FLAG(rcu_free, FOLIO_HEAD_PAGE) + FOLIO_CLEAR_FLAG(rcu_free, FOLIO_HEAD_PAGE) __FOLIO_CLEAR_FLAG(rcu_free, FOLIO_HEAD_PAGE)#define __PG_RCU_FREE (1UL << PG_rcu_free)#else FOLIO_TEST_FLAG_FALSE(rcu_free) FOLIO_TEST_SET_FLAG_FALSE(rcu_free) + FOLIO_CLEAR_FLAG_NOOP(rcu_free) __FOLIO_CLEAR_FLAG_NOOP(rcu_free)#define __PG_RCU_FREE 0#endif
mm/filemap.c +6 -0
@@ -138,6 +138,9 @@ static void page_cache_delete(struct address_space *mapping, nr =folio_nr_pages (folio);VM_BUG_ON_FOLIO (!folio_test_locked (folio), folio); +/* No lockless reader can be in an evicted inode */ +if (folio_test_rcu_free (folio) &&mapping_exiting (mapping)) +folio_clear_rcu_free (folio);xas_store (&xas, shadow);xas_init_marks (&xas);
@@ -306,6 +309,9 @@ static void page_cache_delete_batch(struct address_space *mapping, }WARN_ON_ONCE (!folio_test_locked (folio)); +/* No lockless reader can be in an evicted inode */ +if (folio_test_rcu_free (folio) &&mapping_exiting (mapping)) +folio_clear_rcu_free (folio); folio->mapping =NULL ;/* Leave folio->index set: truncation lookup relies on it */
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH 12/18] mm/filemap: don't defer the free of folios of an inode being evicted
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] mm/filemap: premature PG_rcu_free clear on live inodes with AS_EXITING --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] mm/filemap: premature PG_rcu_free clear on live inodes with AS_EXITING --
commit 47ca48a16967ca2b270af7537211abb87d17221b
Author: Kiryl Shutsemau (Meta) <[email protected]>
mm/filemap: don't defer the free of folios of an inode being evicted
This commit clears PG_rcu_free on folios in page_cache_delete() and page_cache_delete_batch() when mapping_exiting() is set, avoiding RCU-deferred freeing during inode eviction.
Quoted 15 lines
mm/filemap.c +3
-0@@ -138,6 +138,9 @@ static void page_cache_delete(struct address_space *mapping, nr =folio_nr_pages (folio);VM_BUG_ON_FOLIO (!folio_test_locked (folio), folio); +/* No lockless reader can be in an evicted inode */ +if (folio_test_rcu_free (folio) &&mapping_exiting (mapping)) +folio_clear_rcu_free (folio);xas_store (&xas, shadow);xas_init_marks (&xas);
mm/filemap.c static void page_cache_delete_batch(struct address_space *mapping, · line 314
Quoted 6 lines
mm/filemap.c +3
-0@@ -306,6 +309,9 @@ static void page_cache_delete_batch(struct address_space *mapping, }WARN_ON_ONCE (!folio_test_locked (folio)); +/* No lockless reader can be in an evicted inode */ +if (folio_test_rcu_free (folio) &&mapping_exiting (mapping)) +folio_clear_rcu_free (folio);
[Severity: Critical]
Can clearing PG_rcu_free when mapping_exiting(mapping) is set cause a use-after-free if truncate_inode_pages_final() is called on a live, open file?
In mm/truncate.c, truncate_inode_pages_final() unconditionally sets AS_EXITING via mapping_set_exiting():
mm/truncate.c:truncate_inode_pages_final() {
mapping_set_exiting(mapping);
if (!mapping_empty(mapping)) {
xa_lock_irq(&mapping->i_pages);
xa_unlock_irq(&mapping->i_pages);
}
truncate_inode_pages(mapping, 0);
...
}However, f2fs calls truncate_inode_pages_final() on live, open regular files during atomic write operations, such as when starting an atomic replace via ioctl(F2FS_IOC_START_ATOMIC_REPLACE):
fs/f2fs/file.c:f2fs_ioc_start_atomic_write() {
...
if (truncate) {
set_inode_flag(inode, FI_ATOMIC_REPLACE);
truncate_inode_pages_final(inode->i_mapping);
f2fs_i_size_write(inode, 0);
isize = 0;
}
...
}and when aborting an atomic write:
fs/f2fs/segment.c:f2fs_abort_atomic_write() {
...
if (clean)
truncate_inode_pages_final(inode->i_mapping);
...
}Buffered reads in f2fs call f2fs_file_read_iter() -> filemap_read() without holding inode_lock() or fi->i_gc_rwsem, which marks folios with PG_rcu_free via filemap_mark_hot() and copies from them locklessly under rcu_read_lock().
Furthermore, because AS_EXITING is never cleared once set, mapping_exiting(inode->i_mapping) remains true for the rest of the live inode's lifetime in cache. During both the atomic-write truncate_inode_pages_final() calls and any subsequent truncate(), hole punch, fadvise(POSIX_FADV_DONTNEED) invalidation, or page reclaim on that open file, page_cache_delete() and page_cache_delete_batch() will clear PG_rcu_free on hot folios.
When the last reference to those folios is dropped, wouldn't __free_pages_prepare() skip rcu_free_defer() and return the pages immediately to the buddy allocator while concurrent lockless readers in filemap_read() are still copying from them under rcu_read_lock()?
Quoted 3 lines
mm/filemap.c +0
-0folio->mapping =NULL ;/* Leave folio->index set: truncation lookup relies on it */
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 13/18 mm/filemap: store the end of a read in f_ra only when it changes
In reply to Kiryl Shutsemau (Meta)filemap_read() writes the end of every read to file->f_ra.prev_pos. Threads that read through one open file all write that cache line, on every read. The value often stays the same, as for reads that start at the same offset each time.
Store it only when it changes.
--- mm/filemap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
mm/filemap.c +3 -1
@@ -2941,7 +2941,9 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter, }while (iov_iter_count (iter) && iocb->ki_pos < isize && !error);file_accessed (filp); - ra->prev_pos = last_pos; +/* Readers sharing the file would bounce the line for nothing */ +if (ra->prev_pos != last_pos) + ra->prev_pos = last_pos;return already_read ? already_read : error; }EXPORT_SYMBOL_GPL (filemap_read);
Signature · 1 line
2.54.0
Re: [RFC PATCH 13/18] mm/filemap: store the end of a read in f_ra only when it changes
Quoted 5 lines · Kiryl Shutsemau (Meta)
filemap_read()writes the end of every read tofile->f_ra.prev_pos. Threads that read through one open file all write that cache line, on every read. The value often stays the same, as for reads that start at the same offset each time.
This seems silly. That "often stays the same" is only true for the pointless benchmark, no?
I don't think it's ever true in any real load.
Linus
Kiryl Shutsemau
reviewerRe: [RFC PATCH 13/18] mm/filemap: store the end of a read in f_ra only when it changes
Quoted 11 lines · Linus Torvalds
Quoted 5 lines · Kiryl Shutsemau (Meta)
filemap_read()writes the end of every read tofile->f_ra.prev_pos. Threads that read through one open file all write that cache line, on every read. The value often stays the same, as for reads that start at the same offset each time.This seems silly. That "often stays the same" is only true for the pointless benchmark, no?
I don't think it's ever true in any real load.
Right. The patch is bogus, not only the commit message.
It is worse than useless: for random reads prev_pos changes every time, so the compare reads the shared line and then writes it anyway. Bisecting a RocksDB slowdown led here: with patches 1-12 it runs at base speed, this one costs 4-5% at 16-64 threads.
The store itself does matter in a real load. RocksDB threads pread() through one fd per SST file, opened with POSIX_FADV_RANDOM. With the folio refcount gone, the prev_pos store on that shared struct file is what they fight over next.
For an FMODE_RANDOM file nothing reads prev_pos but filemap_read()
itself: readahead is forced and returns before looking at it. Skipping the store there takes a small hot table at 64 threads from 10.7M to 14.1M Gets/s, against 12.5M with the series as posted.
I will replace this patch with that.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 14/18 mm/filemap: read from the page cache without folio references
In reply to Kiryl Shutsemau (Meta)From: Linus Torvalds <[email protected]>
Small reads of one file from many CPUs all take and drop a reference on the same folio, and its refcount bounces between the CPUs.
Before taking a reference, copy what can be copied under rcu_read_lock() from folios with PG_rcu_free, with page faults disabled. A flagged folio is not reused before rcu_read_unlock(), so a folio still in its slot after the flag test is this file's page until then. A folio that leaves the page cache during the copy reads as the file did when it left. Read i_size between the flag and the second look at the slot: a write that extends the file fills the slot before it moves i_size.
Leave to the slow path a folio that is not uptodate, needs readahead or dropbehind, is not hot, or has a poisoned page. Leave large folios there too: looking one up for every page is slower than one reference for all of its pages. Copy at most 512 KiB per rcu_read_lock() section, and skip files that never had a folio flagged or that are writably mapped where flush_dcache_folio() is needed.
[kas: i_size before the second look at the slot, poisoned folio check,
large folios left to the slow path, 512 KiB sections, shorter comments and changelog]
--- mm/filemap.c | 169 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+)
mm/filemap.c +169 -0
@@ -2827,6 +2827,165 @@ static void filemap_end_dropbehind_read(struct folio *folio) } } +/* +* Whether filemap_read_rcu_batch() can copy from @folio, or has to leave it +* to the slow path, which holds a reference for readahead, dropbehind and +* folio_mark_accessed(), and deals with poisoned pages. @last_index is the +* page the previous copy ended in. +*/ +static bool filemap_read_rcu_can_copy (struct folio *folio,pgoff_t index, +pgoff_t last_index) +{ +if (!folio_test_uptodate (folio)) +return false; +if (folio_test_readahead (folio) ||folio_test_dropbehind (folio)) +return false; +/* memory_failure() waits only for readers that got past this */ +if (folio_contain_hwpoisoned_page (folio)) +return false; +/* One reference covers all of a large folio's pages */ +if (folio_test_large (folio)) +return false; + +/* +* The slow path does not call folio_mark_accessed() on the folio that +* the previous read ended in, so copying from it skips nothing. The +* folio's size can change without a reference: compare pages instead. +*/ +if (index == last_index) +return true; + +/* Otherwise only if folio_mark_accessed() would leave it as it is */ +if (lru_gen_enabled ()) { +unsigned long all =LRU_REFS_FLAGS |BIT (PG_workingset); + +return folio_test_unevictable (folio) || + (READ_ONCE (folio->flags.f) & all) == all; + } +return folio_test_referenced (folio) && !folio_test_idle (folio) && + (folio_test_active (folio) ||folio_test_unevictable (folio)); +} + +/* +* Return the folio at @pos if it is this file's page until rcu_read_unlock(), +* and read i_size into @isize. A folio with PG_rcu_free is freed only after +* an RCU grace period. Without a reference, the folio that xas_load() +* returned can be freed and its memory reused as another folio before the +* flag is tested, so look at the slot again after the flag. +*/ +static struct folio *filemap_read_rcu_lookup (struct xa_state *xas, +struct inode *inode,loff_t pos,loff_t *isize) +{ +struct folio *folio; + +xas_set (xas, pos >>PAGE_SHIFT ); + folio =xas_load (xas); +if (xas_retry (xas, folio) || !folio ||xa_is_value (folio)) +return NULL ; + +/* Not folio_test_rcu_free(): it may not be a folio any more */ +if (!(READ_ONCE (folio->flags.f) & __PG_RCU_FREE)) +return NULL ; +/* Read i_size and slot after the flag: it implies uptodate */ +smp_rmb (); + *isize =i_size_read (inode); +if (pos >= *isize) +return NULL ; +/* i_size_read() is an acquire; a write fills the slot first */ +if (xas_reload (xas) != folio) +return NULL ; +/* Read the rest of the folio only once the slot holds it */ +smp_rmb (); +return folio; +} + +/* Bytes one RCU read section copies at most: it holds up grace periods */ +#define FILEMAP_RCU_READ_MAX SZ_512K + +/* +* Copy from folios with PG_rcu_free without taking references, at most +* FILEMAP_RCU_READ_MAX bytes under one rcu_read_lock(). Return true if that +* much was copied and the read is not done. *last_index is the page the +* previous copy ended in, set as the slow path sets last_pos. +*/ +static bool filemap_read_rcu_batch (struct kiocb *iocb,struct iov_iter *iter, +pgoff_t *last_index,size_t *copied) +{ +struct address_space *mapping = iocb->ki_filp->f_mapping; +struct inode *inode = mapping->host; +XA_STATE (xas, &mapping->i_pages,0 ); +size_t budget =FILEMAP_RCU_READ_MAX ; +bool more = false; + +/* flush_dcache_folio() is not known to be safe without a reference */ +if (ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE && +mapping_writably_mapped (mapping)) +return false; + +/* A user fault cannot sleep in the RCU read section: it ends the copy */ +rcu_read_lock (); +pagefault_disable (); +while (iov_iter_count (iter)) { +loff_t pos = iocb->ki_pos; +pgoff_t index = pos >>PAGE_SHIFT ; +size_t offset =offset_in_page (pos); +struct folio *folio; +size_t bytes, n; +loff_t isize; + +if (!budget) { + more = true; +break ; + } + folio =filemap_read_rcu_lookup (&xas, inode, pos, &isize); +if (!folio) +break ; +if (!filemap_read_rcu_can_copy (folio, index, *last_index)) +break ; + + bytes =min_t (loff_t, isize - pos,iov_iter_count (iter)); + bytes =min3 (bytes, budget,PAGE_SIZE - offset); +/* Not _nofault(): its usercopy check reads the folio's order */ + n =copy_page_to_iter (folio_page (folio, index - folio->index), + offset, bytes, iter); + *copied += n; + iocb->ki_pos += n; + budget -= n; +if (n) + *last_index = (pos + n -1 ) >>PAGE_SHIFT ; +if (n < bytes) +break ; + } +pagefault_enable (); +rcu_read_unlock (); + +return more; +} + +/* +* Copy from the page cache without folio references, in batches, and +* return how much was copied. The slow path reads the rest. +*/ +static size_t filemap_read_rcu (struct kiocb *iocb,struct iov_iter *iter, +loff_t last_pos) +{ +/* The page the previous read ended in; ULONG_MAX if none */ +pgoff_t last_index = (last_pos -1 ) >>PAGE_SHIFT ; +size_t copied =0 ; + +/* Not on an inode that never had a folio flagged */ +if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE ) || + !mapping_rcu_read (iocb->ki_filp->f_mapping)) +return 0 ; + +while (filemap_read_rcu_batch (iocb, iter, &last_index, &copied)) { +if (fatal_signal_pending (current)) +break ; +cond_resched (); + } +return copied; +} +/** * filemap_read - Read data from the page cache. * @iocb: The iocb to read.
@@ -2852,6 +3011,7 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,bool writably_mapped;loff_t isize, end_offset;loff_t last_pos = ra->prev_pos; +size_t fast_read;if (unlikely (iocb->ki_pos <0 ))return -EINVAL ;
@@ -2863,6 +3023,14 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,iov_iter_truncate (iter, inode->i_sb->s_maxbytes - iocb->ki_pos);folio_batch_init (&fbatch); + fast_read =filemap_read_rcu (iocb, iter, last_pos); +if (fast_read) { + already_read += fast_read; + last_pos = iocb->ki_pos; +if (!iov_iter_count (iter)) + goto out; + } + do { cond_resched();
@@ -2940,6 +3108,7 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,folio_batch_init (&fbatch); }while (iov_iter_count (iter) && iocb->ki_pos < isize && !error); +out:file_accessed (filp);/* Readers sharing the file would bounce the line for nothing */ if (ra->prev_pos != last_pos)
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH 14/18] mm/filemap: read from the page cache without folio references
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Critical] mm/filemap: race with folio split in filemap_read_rcu_can_copy() - [Critical] mm/filemap…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Critical] mm/filemap: race with folio split in filemap_read_rcu_can_copy()
- [Critical] mm/filemap: use-after-free in filemap_read_rcu() when AS_EXITING is set on live inode
- [High] mm/filemap: ABA race in filemap_read_rcu_lookup() via folio_clear_rcu_free() --
commit 9b6ffbf436977a22ceda82d50abf0d37c589cc75
Author: Linus Torvalds <[email protected]>
mm/filemap: read from the page cache without folio references
This commit adds a fast path to filemap_read() that copies from hot page cache folios marked with PG_rcu_free under rcu_read_lock() without taking folio references. Folios that are not uptodate, need readahead or dropbehind, are not hot, have a poisoned page, or are large are left to the slow path.
Quoted 17 lines
mm/filemap.c +9
-0@@ -2827,6 +2827,165 @@ static void filemap_end_dropbehind_read(struct folio *folio) } } +/* +* Whether filemap_read_rcu_batch() can copy from @folio, or has to leave it +* to the slow path, which holds a reference for readahead, dropbehind and +* folio_mark_accessed(), and deals with poisoned pages. @last_index is the +* page the previous copy ended in. +*/ +static bool filemap_read_rcu_can_copy (struct folio *folio,pgoff_t index, +pgoff_t last_index) +{
mm/filemap.c static void filemap_end_dropbehind_read(struct folio *folio) · line 2848
Quoted 10 lines
mm/filemap.c +10
-0+if (!folio_test_uptodate (folio)) +return false; +if (folio_test_readahead (folio) ||folio_test_dropbehind (folio)) +return false; +/* memory_failure() waits only for readers that got past this */ +if (folio_contain_hwpoisoned_page (folio)) +return false; +/* One reference covers all of a large folio's pages */ +if (folio_test_large (folio)) +return false;
[Severity: Critical]
Can filemap_read_rcu_can_copy() race with a concurrent split of a large folio to order-0?
filemap_mark_hot() sets PG_rcu_free on hot page-cache folios without excluding large folios, and __split_folio_to_order() preserves __PG_RCU_FREE. Because filemap_read_rcu_lookup() does not take a folio reference or check for a frozen refcount, __folio_freeze_and_split_unmapped() can freeze and split a large folio while filemap_read_rcu_batch() operates on it under rcu_read_lock().
In __split_unmapped_folio(), xas_split() populates all split XArray slots with the original head folio until the post-split loop in __folio_freeze_and_split_unmapped() overwrites each tail slot via __xa_store(), so xas_load() and xas_reload() at index > folio->index continue to return the original head folio across __split_folio_to_order():
mm/huge_memory.c:__split_folio_to_order() {
...
folio_clear_has_hwpoisoned(folio);
...
if (new_order)
folio_set_order(folio, new_order);
else
ClearPageCompound(&folio->page);
}This appears to cause two issues:
1. folio_contain_hwpoisoned_page(folio) evaluates:
folio_test_large(folio) && folio_test_has_hwpoisoned(folio)
where folio_test_has_hwpoisoned() calls const_folio_flags(folio, 1):
include/linux/page-flags.h:const_folio_flags() {
...
VM_BUG_ON_PGFLAGS(page->compound_info & 1, page);
VM_BUG_ON_PGFLAGS(n > 0 && !test_bit(PG_head, &page->flags.f), page);
return &page[n].flags.f;
}If ClearPageCompound() clears PG_head between folio_test_large(folio) and const_folio_flags(folio, 1), won't VM_BUG_ON_PGFLAGS fire (or, when CONFIG_DEBUG_VM_PGFLAGS is disabled, read page[1].flags.f where PG_has_hwpoisoned aliases PG_active on the newly split order-0 folio)?
2. When reading at index > folio->index, if __split_folio_to_order() clears PG_has_hwpoisoned and PG_head before filemap_read_rcu_can_copy() runs, both folio_contain_hwpoisoned_page(folio) and folio_test_large(folio) inspect subpage 0 and return false. filemap_read_rcu_batch() then calls:
copy_page_to_iter(folio_page(folio, index - folio->index),
offset, bytes, iter);which copies from the newly split order-0 folio at index without checking its flags. In particular, if memory_failure() poisoned that tail page via SetPageHWPoison() and split the large folio via try_to_split_thp_page(), PG_hwpoison is only set on that subpage while PG_has_hwpoisoned and PG_head are cleared on folio, allowing copy_page_to_iter() to read from the poisoned page.
Note that the later commit in this series ("mm/filemap: read large folios without folio references") removes the folio_test_large(folio) check from filemap_read_rcu_can_copy() and does not avoid these races.
[ ... ]
Quoted 11 lines
mm/filemap.c +11
-0+static struct folio *filemap_read_rcu_lookup (struct xa_state *xas, +struct inode *inode,loff_t pos,loff_t *isize) +{ +struct folio *folio; + +xas_set (xas, pos >>PAGE_SHIFT ); + folio =xas_load (xas); +if (xas_retry (xas, folio) || !folio ||xa_is_value (folio)) +return NULL ; + +/* Not folio_test_rcu_free(): it may not be a folio any more */
mm/filemap.c static void filemap_end_dropbehind_read(struct folio *folio) · line 2896
Quoted 10 lines
mm/filemap.c +10
-0+if (!(READ_ONCE (folio->flags.f) & __PG_RCU_FREE)) +return NULL ; +/* Read i_size and slot after the flag: it implies uptodate */ +smp_rmb (); + *isize =i_size_read (inode); +if (pos >= *isize) +return NULL ; +/* i_size_read() is an acquire; a write fills the slot first */ +if (xas_reload (xas) != folio) +return NULL ;
[Severity: High]
Can folio_clear_rcu_free() during inode eviction allow an ABA race on folio in filemap_read_rcu_lookup()?
In page_cache_delete() and page_cache_delete_batch(), PG_rcu_free is cleared when mapping_exiting(mapping) is true:
mm/filemap.c:page_cache_delete() {
...
/* No lockless reader can be in an evicted inode */
if (folio_test_rcu_free(folio) && mapping_exiting(mapping))
folio_clear_rcu_free(folio);
}Consider a lockless reader in filemap_read_rcu_lookup() on an open file (inode A):
1. xas_load(xas) returns folio F from inode A, where F does not have PG_rcu_free set.
2. F is removed from inode A and freed immediately (since PG_rcu_free is not set).
3. F is reallocated for another file (inode B), added to inode B's page cache, and marked with PG_rcu_free by filemap_mark_hot().
4. The reader on inode A checks READ_ONCE(folio->flags.f) & __PG_RCU_FREE and sees __PG_RCU_FREE set.
5. Inode B is evicted; truncate_inode_pages_final() sets AS_EXITING and page_cache_delete() / page_cache_delete_batch() calls folio_clear_rcu_free(F), freeing F immediately without an RCU grace period.
6. F is allocated again and inserted back into inode A at the same XArray slot without PG_rcu_free set.
7. The reader on inode A sees xas_reload(xas) == F and returns F.
At that point, filemap_read_rcu_batch() accesses F in filemap_read_rcu_can_copy() and copy_page_to_iter() without a reference and without PG_rcu_free set on F, so a subsequent removal from inode A can free and reuse F while the reader is still copying from it.
Quoted 44 lines
mm/filemap.c +44
-0+/* Read the rest of the folio only once the slot holds it */ +smp_rmb (); +return folio; +} + +/* Bytes one RCU read section copies at most: it holds up grace periods */ +#define FILEMAP_RCU_READ_MAX SZ_512K + +/* +* Copy from folios with PG_rcu_free without taking references, at most +* FILEMAP_RCU_READ_MAX bytes under one rcu_read_lock(). Return true if that +* much was copied and the read is not done. *last_index is the page the +* previous copy ended in, set as the slow path sets last_pos. +*/ +static bool filemap_read_rcu_batch (struct kiocb *iocb,struct iov_iter *iter, +pgoff_t *last_index,size_t *copied) +{ +struct address_space *mapping = iocb->ki_filp->f_mapping; +struct inode *inode = mapping->host; +XA_STATE (xas, &mapping->i_pages,0 ); +size_t budget =FILEMAP_RCU_READ_MAX ; +bool more = false; + +/* flush_dcache_folio() is not known to be safe without a reference */ +if (ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE && +mapping_writably_mapped (mapping)) +return false; + +/* A user fault cannot sleep in the RCU read section: it ends the copy */ +rcu_read_lock (); +pagefault_disable (); +while (iov_iter_count (iter)) { +loff_t pos = iocb->ki_pos; +pgoff_t index = pos >>PAGE_SHIFT ; +size_t offset =offset_in_page (pos); +struct folio *folio; +size_t bytes, n; +loff_t isize; + +if (!budget) { + more = true; +break ; + } + folio =filemap_read_rcu_lookup (&xas, inode, pos, &isize);
mm/filemap.c static void filemap_end_dropbehind_read(struct folio *folio) · line 2950
Quoted 10 lines
mm/filemap.c +10
-0+if (!folio) +break ; +if (!filemap_read_rcu_can_copy (folio, index, *last_index)) +break ; + + bytes =min_t (loff_t, isize - pos,iov_iter_count (iter)); + bytes =min3 (bytes, budget,PAGE_SIZE - offset); +/* Not _nofault(): its usercopy check reads the folio's order */ + n =copy_page_to_iter (folio_page (folio, index - folio->index), + offset, bytes, iter);
[Severity: Critical]
What prevents a use-after-free here when truncate_inode_pages_final() is called on a live inode?
page_cache_delete() and page_cache_delete_batch() assume that mapping_exiting(mapping) is only set during final inode eviction when no readers can be active, and clear PG_rcu_free so the folio is freed immediately without waiting for an RCU grace period.
However, f2fs calls truncate_inode_pages_final() on live open files during atomic write operations:
fs/f2fs/file.c:f2fs_ioc_start_atomic_write() {
...
if (truncate) {
set_inode_flag(inode, FI_ATOMIC_REPLACE);
truncate_inode_pages_final(inode->i_mapping);
f2fs_i_size_write(inode, 0);
isize = 0;
}
...
}and in f2fs_abort_atomic_write():
fs/f2fs/segment.c:f2fs_abort_atomic_write() {
...
if (clean)
truncate_inode_pages_final(inode->i_mapping);
...
}When f2fs_file_read_iter() -> filemap_read() -> filemap_read_rcu() -> filemap_read_rcu_batch() runs concurrently with f2fs_ioc_start_atomic_write() or f2fs_abort_atomic_write(), truncate_inode_pages_final() sets AS_EXITING (before i_size is zeroed in the start_atomic_write case) and truncates the mapping's folios. page_cache_delete() / page_cache_delete_batch() sees mapping_exiting() and clears PG_rcu_free, freeing the folios immediately while filemap_read_rcu_batch() is copying from them under rcu_read_lock().
Additionally, because AS_EXITING is never cleared on the live inode's mapping, any folios subsequently added and marked with PG_rcu_free by filemap_mark_hot() will also have PG_rcu_free cleared on any later truncate, hole punch, or reclaim while lockless readers are copying from them.
[ ... ]
Quoted 3 lines
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 15/18 mm/filemap: read large folios without folio references
In reply to Kiryl Shutsemau (Meta)A large folio is in all the slots of its range or in none. Once the slot of the last page to copy holds it too, the pages in between are this folio's: copy them after one lookup. The folio's size is read without a reference and only picks the page to check; a split after the check copies PG_rcu_free to the new folios.
Copy page by page with _copy_to_iter(): the hardened usercopy check of copy_to_iter() reads the folio's order, which a split can change.
--- mm/filemap.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 7 deletions(-)
mm/filemap.c +57 -7
@@ -2843,9 +2843,6 @@ static bool filemap_read_rcu_can_copy(struct folio *folio, pgoff_t index,/* memory_failure() waits only for readers that got past this */ if (folio_contain_hwpoisoned_page (folio))return false; -/* One reference covers all of a large folio's pages */ -if (folio_test_large (folio)) -return false;/* * The slow path does not call folio_mark_accessed() on the folio that
@@ -2899,6 +2896,60 @@ static struct folio *filemap_read_rcu_lookup(struct xa_state *xas,return folio; } +/* +* How much of @bytes, starting @offset into page @index, can be copied from +* @folio. A folio is in all the slots of its range or in none: when the slot +* of the last page holds it too, so do the slots in between, and the pages +* are this folio's. +*/ +static size_t filemap_read_rcu_size (struct xa_state *xas,struct folio *folio, +pgoff_t index,size_t offset,size_t bytes) +{ +pgoff_t end = index +DIV_ROUND_UP (offset + bytes,PAGE_SIZE ); +pgoff_t next; + +if (end - index >1 &&folio_test_large (folio)) { +/* Read without a reference: it only picks the page to check */ + next =folio_next_index (folio); +if (next > index && next < end) + end = next; +xas_set (xas, end -1 ); +/* A split after this copies PG_rcu_free to the new folios */ +if (xas_load (xas) == folio) +return min (bytes, (end - index) *PAGE_SIZE - offset); + } +return min (bytes,PAGE_SIZE - offset); +} + +/* +* Copy @bytes from @folio, starting @offset into its page at @index. Page +* by page, as copy_page_to_iter() does, without its checks for each call. +* Not copy_to_iter(): its usercopy check reads the folio's order, which a +* split can change. +*/ +static size_t filemap_read_rcu_copy (struct folio *folio,pgoff_t index, +size_t offset,size_t bytes,struct iov_iter *iter) +{ +struct page *page =folio_page (folio, index - folio->index); +size_t n =0 ; + +while (n < bytes) { +size_t len =min (bytes - n,PAGE_SIZE - offset); +size_t done; +void *kaddr; + + kaddr =kmap_local_page (page); + done =_copy_to_iter (kaddr + offset, len, iter); +kunmap_local (kaddr); + n += done; +if (done < len) +break ; + offset =0 ; + page++; + } +return n; +} +/* Bytes one RCU read section copies at most: it holds up grace periods */ #define FILEMAP_RCU_READ_MAX SZ_512K
@@ -2944,10 +2995,9 @@ static bool filemap_read_rcu_batch(struct kiocb *iocb, struct iov_iter *iter,break ; bytes =min_t (loff_t, isize - pos,iov_iter_count (iter)); - bytes =min3 (bytes, budget,PAGE_SIZE - offset); -/* Not _nofault(): its usercopy check reads the folio's order */ - n =copy_page_to_iter (folio_page (folio, index - folio->index), - offset, bytes, iter); + bytes =filemap_read_rcu_size (&xas, folio, index, offset, +min (bytes, budget)); + n =filemap_read_rcu_copy (folio, index, offset, bytes, iter); *copied += n; iocb->ki_pos += n; budget -= n;
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH 15/18] mm/filemap: read large folios without folio references
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] mm: race with folio split in filemap_read_rcu_can_copy() and copy - [High] mm: lockless…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] mm: race with folio split in filemap_read_rcu_can_copy() and copy
- [High] mm: lockless folio_next_index() in filemap_read_rcu_size() races with split --
commit 8d224bff99d361b93bdbc49e7fbdbc8d57975349
Author: Kiryl Shutsemau (Meta) <[email protected]>
mm/filemap: read large folios without folio references
This commit extends lockless RCU page cache reads to support large folios without taking a folio reference. It checks whether the last page to be copied still belongs to the same folio in the XArray and copies the pages one by one with _copy_to_iter().
mm/filemap.c static bool filemap_read_rcu_can_copy(struct folio *folio, pgoff_t index, · line 2848
Quoted 11 lines
mm/filemap.c +0
-3@@ -2843,9 +2843,6 @@ static bool filemap_read_rcu_can_copy(struct folio *folio, pgoff_t index,/* memory_failure() waits only for readers that got past this */ if (folio_contain_hwpoisoned_page (folio))return false; -/* One reference covers all of a large folio's pages */ -if (folio_test_large (folio)) -return false;
[Severity: High]
Can removing the folio_test_large() bailout here race with a concurrent folio split to order 0 in both folio_contain_hwpoisoned_page() and the subsequent copy?
In filemap_read_rcu_can_copy(), folio_contain_hwpoisoned_page() checks folio_test_large() and then calls folio_test_has_hwpoisoned():
include/linux/page-flags.h:folio_contain_hwpoisoned_page()
return folio_test_hwpoison(folio) || (folio_test_large(folio) && folio_test_has_hwpoisoned(folio));
Because has_hwpoisoned is a FOLIO_SECOND_PAGE flag, folio_test_has_hwpoisoned() calls const_folio_flags(folio, 1):
include/linux/page-flags.h:const_folio_flags()
VM_BUG_ON_PGFLAGS(page->compound_info & 1, page); VM_BUG_ON_PGFLAGS(n > 0 && !test_bit(PG_head, &page->flags.f), page); return &page[n].flags.f;
If __split_folio_to_order() splits the folio to order 0 and executes ClearPageCompound(&folio->page) between folio_test_large() and const_folio_flags(folio, 1), won't that trigger the VM_BUG_ON_PGFLAGS() assertion?
Even with CONFIG_DEBUG_VM_PGFLAGS disabled, __split_folio_to_order() initializes page[1].flags.f for the new order-0 folio (including copying PG_active) before clearing PG_head on page[0]. Since PG_has_hwpoisoned aliases PG_active, reading page[1].flags.f on an active folio being split to order 0 will see PG_active and misinterpret it as PG_has_hwpoisoned.
Additionally, if a tail subpage is poisoned by memory_failure(), PG_hwpoison is set on that tail struct page, and splitting the folio in __folio_freeze_and_split_unmapped() -> __split_unmapped_folio() -> __split_folio_to_order() calls xas_split() (leaving old_folio in all the split XArray slots while its refcount is frozen at 0) and then executes:
mm/huge_memory.c:__split_folio_to_order()
folio_clear_has_hwpoisoned(folio); ... ClearPageCompound(&folio->page);
before __folio_freeze_and_split_unmapped() replaces old_folio in slots 1 .. nr_pages - 1 with __xa_store(). During that window, a lockless reader in filemap_read_rcu_batch() does not check refcount and can look up old_folio at a tail index (or across a range in filemap_read_rcu_size()), observe folio_contain_hwpoisoned_page(old_folio) == false because both PG_has_hwpoisoned and PG_head have been cleared on old_folio while PG_hwpoison is only on the tail page, and then copy directly from the hwpoisoned tail page in filemap_read_rcu_copy() without checking PageHWPoison(page).
Quoted 9 lines
mm/filemap.c +5
-0@@ -2899,6 +2896,60 @@ static struct folio *filemap_read_rcu_lookup(struct xa_state *xas,return folio; } +/* +* How much of @bytes, starting @offset into page @index, can be copied from +* @folio. A folio is in all the slots of its range or in none: when the slot +* of the last page holds it too, so do the slots in between, and the pages +* are this folio's.
mm/filemap.c static struct folio *filemap_read_rcu_lookup(struct xa_state *xas, · line 2913
Quoted 10 lines
mm/filemap.c +10
-0+*/ +static size_t filemap_read_rcu_size (struct xa_state *xas,struct folio *folio, +pgoff_t index,size_t offset,size_t bytes) +{ +pgoff_t end = index +DIV_ROUND_UP (offset + bytes,PAGE_SIZE ); +pgoff_t next; + +if (end - index >1 &&folio_test_large (folio)) { +/* Read without a reference: it only picks the page to check */ + next =folio_next_index (folio);
[Severity: High]
What happens if the folio is concurrently split to order 0 while folio_next_index() reads its size here without a reference?
folio_next_index() calls folio_nr_pages() -> folio_large_nr_pages(), which reads from the first tail page (folio->__page_1):
include/linux/mm.h:folio_large_nr_pages()
#ifdef NR_PAGES_IN_LARGE_FOLIO
static inline unsigned long folio_large_nr_pages(const struct folio *folio)
{
return folio->_nr_pages;
}
#else
static inline unsigned long folio_large_nr_pages(const struct folio *folio)
{
return 1L << folio_large_order(folio);
}#endif
where folio_large_order() reads folio->_flags_1 & 0xff.
In __split_folio_to_order(), when splitting to order 0, the loop at i = 1 initializes new_folio = (struct folio *)(&folio->page + 1) and writes order-0 page flags into new_folio->flags.f (aliasing folio->_flags_1) and copies folio->memcg_data into new_folio->memcg_data (aliasing folio->_nr_pages) before ClearPageCompound(&folio->page) clears PG_head.
When NR_PAGES_IN_LARGE_FOLIO is not enabled, folio->_flags_1 & 0xff can contain order-0 page flags such as PG_waiters (bit 7 = 128) or PG_head (bit 6 = 64), causing 1L << folio_large_order(folio) to perform a signed 64-bit shift out of bounds. When NR_PAGES_IN_LARGE_FOLIO is enabled, reading folio->_nr_pages races with new_folio->memcg_data being written.
[ ... ]
Quoted 13 lines
mm/filemap.c +13
-0+} + +/* +* Copy @bytes from @folio, starting @offset into its page at @index. Page +* by page, as copy_page_to_iter() does, without its checks for each call. +* Not copy_to_iter(): its usercopy check reads the folio's order, which a +* split can change. +*/ +static size_t filemap_read_rcu_copy (struct folio *folio,pgoff_t index, +size_t offset,size_t bytes,struct iov_iter *iter) +{ +struct page *page =folio_page (folio, index - folio->index); +size_t n =0 ;
[ ... ]
Quoted 19 lines
mm/filemap.c +5
-4+} +/* Bytes one RCU read section copies at most: it holds up grace periods */ #define FILEMAP_RCU_READ_MAX SZ_512K@@ -2944,10 +2995,9 @@ static bool filemap_read_rcu_batch(struct kiocb *iocb, struct iov_iter *iter,break ; bytes =min_t (loff_t, isize - pos,iov_iter_count (iter)); - bytes =min3 (bytes, budget,PAGE_SIZE - offset); -/* Not _nofault(): its usercopy check reads the folio's order */ - n =copy_page_to_iter (folio_page (folio, index - folio->index), - offset, bytes, iter); + bytes =filemap_read_rcu_size (&xas, folio, index, offset, +min (bytes, budget)); + n =filemap_read_rcu_copy (folio, index, offset, bytes, iter); *copied += n; iocb->ki_pos += n; budget -= n;
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 16/18 mm/shmem: count accesses to a folio the way filemap_read() does
In reply to Kiryl Shutsemau (Meta)shmem_file_read_iter() marks a folio accessed only when a read starts at the beginning of the folio. Small reads that start anywhere else never count, so a folio that is read over and over at one offset ages as if it were never read.
Count accesses with filemap_read_accessed(), as filemap_read() does: a read marks the folio accessed unless it goes on in the folio that the previous read through the file ended in. Reading the same bytes again through one open file counts once, as for other files, where it used to count each time it started at the beginning of the folio. The end of the previous read is kept in f_ra.prev_pos, as for other files.
This also sets PG_rcu_free on the tmpfs folios that reads keep coming back to. On a shmem folio the PG_readahead bit is PG_reclaim, and shmem does no readahead, so do not let that bit keep the flag off. A write marks a tmpfs folio accessed too, so a folio written in several pieces can get the flag on its first read.
--- mm/filemap.c | 9 +++++---- mm/internal.h | 1 + mm/shmem.c | 11 ++++++----- 3 files changed, 12 insertions(+), 9 deletions(-)
mm/filemap.c +5 -4
@@ -2778,8 +2778,10 @@ static void filemap_mark_hot(struct folio *folio)if (!IS_ENABLED (CONFIG_PAGE_RCU_FREE ))return ;if (folio_test_rcu_free (folio) || !folio_test_uptodate (folio) || -folio_test_readahead (folio) ||folio_test_dropbehind (folio) || -folio_test_unevictable (folio)) +folio_test_dropbehind (folio) ||folio_test_unevictable (folio)) +return ; +/* shmem does no readahead: there the bit is PG_reclaim */ +if (folio_test_readahead (folio) && !folio_test_swapbacked (folio))return ;if (folio_test_set_rcu_free (folio))return ;
@@ -2802,8 +2804,7 @@ static void filemap_mark_hot(struct folio *folio)* LRU records, or when this open file goes back to data that it has just * read. */ -static void filemap_read_accessed (struct folio *folio,loff_t pos, -loff_t last_pos) +void filemap_read_accessed (struct folio *folio,loff_t pos,loff_t last_pos) {bool hot;
mm/internal.h +1 -0
@@ -1248,6 +1248,7 @@ struct migration_target_control {*/ size_t splice_folio_into_pipe (struct pipe_inode_info *pipe,struct folio *folio,loff_t fpos,size_t size); +void filemap_read_accessed (struct folio *folio,loff_t pos,loff_t last_pos);static inline bool vma_is_single_threaded_private (struct vm_area_struct *vma) {
mm/shmem.c +6 -5
@@ -3309,6 +3309,7 @@ static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)struct file *file = iocb->ki_filp;struct inode *inode =file_inode (file);struct address_space *mapping = inode->i_mapping; +loff_t last_pos = file->f_ra.prev_pos;pgoff_t index;unsigned long offset;int error =0 ;
@@ -3378,11 +3379,7 @@ static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)flush_dcache_page (page); } -/* -* Mark the folio accessed if we read the beginning. -*/ -if (!offset) -folio_mark_accessed (folio); +filemap_read_accessed (folio, iocb->ki_pos, last_pos);/* * Ok, we have the page, and it's up-to-date, so * now we can copy it to user space...
@@ -3410,6 +3407,7 @@ static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to) retval += ret; iocb->ki_pos += ret; + last_pos = iocb->ki_pos;if (!iov_iter_count (to))break ;
@@ -3421,6 +3419,9 @@ static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to) }file_accessed (file); +/* Readers sharing the file would bounce the line for nothing */ +if (file->f_ra.prev_pos != last_pos) + file->f_ra.prev_pos = last_pos;return retval ? retval : error; }
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 17/18 mm/shmem: read without folio references
In reply to Kiryl Shutsemau (Meta)shmem_file_read_iter() takes a reference on every folio it reads, so small reads of one tmpfs file from many CPUs bounce the folio's refcount.
Copy with filemap_read_rcu() first, and continue with the existing loop where it stops. Holes, swap entries and fallocated folios that are not uptodate all end the copy. So does a hwpoisoned page, which shmem keeps in the page cache and reports with -EIO.
This drops the folio lock as well as the reference. shmem_get_folio() held it only for the lookup, and the copy ran after folio_unlock(), so a read was never atomic against a write or a hole punch. Now a read also does not wait for one that holds the lock, as filemap_read() does not.
shmem does no readahead, and on its folios the PG_readahead bit is PG_reclaim, which drop_caches can leave set on dirty tmpfs folios. Do not let it end the copy there.
--- mm/filemap.c | 7 ++++--- mm/internal.h | 2 ++ mm/shmem.c | 11 +++++++++-- 3 files changed, 15 insertions(+), 5 deletions(-)
mm/filemap.c +4 -3
@@ -2837,9 +2837,10 @@ static void filemap_end_dropbehind_read(struct folio *folio)static bool filemap_read_rcu_can_copy (struct folio *folio,pgoff_t index,pgoff_t last_index) { -if (!folio_test_uptodate (folio)) +if (!folio_test_uptodate (folio) ||folio_test_dropbehind (folio))return false; -if (folio_test_readahead (folio) ||folio_test_dropbehind (folio)) +/* shmem does no readahead: there the bit is PG_reclaim */ +if (folio_test_readahead (folio) && !folio_test_swapbacked (folio))return false;/* memory_failure() waits only for readers that got past this */ if (folio_contain_hwpoisoned_page (folio))
@@ -3017,7 +3018,7 @@ static bool filemap_read_rcu_batch(struct kiocb *iocb, struct iov_iter *iter,* Copy from the page cache without folio references, in batches, and * return how much was copied. The slow path reads the rest. */ -static size_t filemap_read_rcu (struct kiocb *iocb,struct iov_iter *iter, +size_t filemap_read_rcu (struct kiocb *iocb,struct iov_iter *iter,loff_t last_pos) {/* The page the previous read ended in; ULONG_MAX if none */
mm/internal.h +2 -0
@@ -1249,6 +1249,8 @@ struct migration_target_control {size_t splice_folio_into_pipe (struct pipe_inode_info *pipe,struct folio *folio,loff_t fpos,size_t size);void filemap_read_accessed (struct folio *folio,loff_t pos,loff_t last_pos); +size_t filemap_read_rcu (struct kiocb *iocb,struct iov_iter *iter, +loff_t last_pos);static inline bool vma_is_single_threaded_private (struct vm_area_struct *vma) {
mm/shmem.c +9 -2
@@ -3313,7 +3313,14 @@ static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)pgoff_t index;unsigned long offset;int error =0 ; -ssize_t retval =0 ; +ssize_t retval; + + retval =filemap_read_rcu (iocb, to, last_pos); +if (retval) { + last_pos = iocb->ki_pos; +if (!iov_iter_count (to)) + goto out; + }for (;;) {struct folio *folio =NULL ;
@@ -3417,7 +3424,7 @@ static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to) }cond_resched (); } - +out:file_accessed (file);/* Readers sharing the file would bounce the line for nothing */ if (file->f_ra.prev_pos != last_pos)
Signature · 1 line
2.54.0
Kiryl Shutsemau (Meta)
reviewerRFC PATCH 18/18 mm/filemap: add a debugfs switch for lockless page cache reads
In reply to Kiryl Shutsemau (Meta)Reading hot folios without a reference defers the free of their memory by an RCU grace period. A workload that loses on that trade, or a bug in the lockless read, has no way to turn it off: CONFIG_PAGE_RCU_FREE is on in every 64-bit kernel.
Add lockless_page_cache_read to debugfs. Writing 0 stops filemap_read() and shmem_file_read_iter() from setting PG_rcu_free and from copying without a reference. A static key keeps the test off the read path. debugfs, not a sysctl: the switch is not ABI and can go once the reads have proven themselves.
Folios that have the flag keep it, and their free stays deferred: a read that tested the key before the switch may still be copying from them.
--- mm/Kconfig | 3 +++ mm/filemap.c | 51 ++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 51 insertions(+), 3 deletions(-)
mm/Kconfig +3 -0
@@ -730,6 +730,9 @@ config PAGE_RCU_FREE 64-bit only: it takes a page flag, and those are scarce on 32-bit. + Writing 0 to lockless_page_cache_read in debugfs turns these + reads off. + config PHYS_ADDR_T_64BIT def_bool 64BIT
mm/filemap.c +48 -3
75 lines not on this page · raw message
Signature · 1 line
2.54.0
Quoted 11 lines · Kiryl Shutsemau (Meta)
Small reads of one file from many CPUs all take and drop a reference on the same folio, and its refcount bounces between the CPUs. This series lets
filemap_read()and shmem copy from the page cache without taking a reference. It is Linus' RFC [1], reworked: a folio that such a reader may copy from is freed only after an RCU grace period.Only the folios that reads keep coming back to get the flag,
PG_rcu_free: those thatfolio_mark_accessed()finds as accessed as the LRU records. Streaming reads and data that never gets hot are not deferred, so the memory held back stays small and most frees are not touched.
By applying this to hot folios only, small reads would benefit only when they contend on the refcount. That further narrows down the scope of workload that would benefit from this. Random or sequential small reads still perform the atomics on the refcount.
Looking at what Linus mentioned as "Willy reported real users having scalability issues in that area a couple of years ago in a discussion about buffereed IO scalability limits:
https://lore.kernel.org/all/[email protected]/
"
On that thread, from Willy:
Quoted 9 lines
Not artificial; this was a real customer with a real workload. I don't know how much about it I can discuss publically, but my memory of it was a system writing a log with 64 byte entries, millions of entries per second. Occasionally the system would have to go back and look at an entry in the last few seconds worth of data (so it would still be in the page cache).
This customer was quite savvy, so they actually implemented and tested the lookup-copy-lookup-again algorithm in their custom kernel, and saw a speedup from it.
https://lore.kernel.org/all/[email protected]
Again from willy, from the same thread:
Quoted 13 lines · Linus Torvalds
Quoted 12 lines
Willy - tangential side note: I looked closer at the issue that you reported (indirectly) with the small reads during heavy write activity.
Our _reading_ side is very optimized and has none of the write-side oddities that I can see, and we just have
filemap_read->filemap_get_pages -> filemap_get_read_batch -> folio_try_get_rcu()
Quoted 8 lines
Quoted 5 lines
and there is no page locking or other locking involved (assuming the page is cached and marked uptodate etc, of course).
So afaik, it really is just that *one* atomic access (and the matching page ref decrement afterwards).
Yep, that was what the customer reported on their ancient kernel, and we at least didn't make that worse ...
https://lore.kernel.org/all/[email protected]
From the discussion I'm not sure if the scenario above would benefit from this.
Maybe we should try to either 1) find a better heuristic to mark which folios should have PG_rcu_free to make it beneficial for wider range of workloads or 2) identify workload that heavly contends on the refcount of a small set of folios...
Signature · 2 lines
Cheers, Harry / Hyeonggon
Kiryl Shutsemau
reviewerQuoted 13 lines · Harry Yoo
Quoted 11 lines · Kiryl Shutsemau (Meta)
Small reads of one file from many CPUs all take and drop a reference on the same folio, and its refcount bounces between the CPUs. This series lets
filemap_read()and shmem copy from the page cache without taking a reference. It is Linus' RFC [1], reworked: a folio that such a reader may copy from is freed only after an RCU grace period.Only the folios that reads keep coming back to get the flag,
PG_rcu_free: those thatfolio_mark_accessed()finds as accessed as the LRU records. Streaming reads and data that never gets hot are not deferred, so the memory held back stays small and most frees are not touched.
Quoted 4 lines
By applying this to hot folios only, small reads would benefit only when they contend on the refcount. That further narrows down the scope of workload that would benefit from this. Random or sequential small reads still perform the atomics on the refcount.
They do, but an atomic on a cache line the CPU already owns is cheap. The cost is the line bouncing between CPUs, and that takes many reads of the same folio, which is what the hot marking looks for.
Single thread, 16-byte pread() of one page, mitigations=off: base does 7.4-7.7M reads/s, the series 7.7-8.0M. Dropping the reference saves a few percent when nothing contends. With 64 threads on the same page, base falls to 17M reads/s in total and the series does 220M.
Quoted 4 lines
Maybe we should try to either 1) find a better heuristic to mark which folios should have
PG_rcu_freeto make it beneficial for wider range of workloads or 2) identify workload that heavly contends on the refcount of a small set of folios...
Marking more is not free either.
A flagged folio goes back to the page allocator only after a grace period, so what reclaim and compaction free is not usable right away, and they have to work harder to keep up.
I am all for finding a better heuristic. But it is hard balance.
I will get back with data from real workloads.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov