mm: reliable 1GB page allocation
Subsystems (13)
cover mm: reliable 1GB page allocation
Some workloads see real performance benefits from using 1GB pages, but allocating 1GB pages has often been limited to hugetlb pages that were set aside at boot time, or using CMA to keep a fixed amount of system memory off limits to the kernel.
Neither of those are great solutions, given that modern servers tend to be large, often run multiple workloads simultaneously, and each workload wants something else.
To address that issue, this patch series divides memory not just into 2MB page blocks, but into PUD sized superpageblocks, and aggressively tries to steer unmovable, reclaimable, and highatomic allocations into those superpageblocks that have already been "tainted" by such allocations.
The goal is to leave as many 1GB superpageblocks as possible used by only movable allocations, so they can be easily defragmented for either regular PMD sized huge pages, or for PUD sized huge pages.
Various strategies are used to accomplish this goal:
- unmovable and reclaimable allocations are preferentially done from 1GB blocks that have already been "tainted" by these allocations
- kernel allocations that can be done as one higher order allocation, or a number of smaller allocations (eg. kvmalloc) will fall back to small pages, rather than taint a new 1GB block
- movable allocations are preferentially done from clean 1GB blocks, which have only free and movable memory inside, starting with the fullest of these 1GB blocks
- 2MB allocations follow the same strategy
- 1GB allocations start with the emptiest clean 1GB block
- if a 1GB block is mixed, with some movable pageblocks, some free pageblocks, and some unmovable/reclaimable pageblocks, the system has a free threshold below which only unmovable and reclaimable allocations can be done from that 1GB block
- below that threshold, no new movable allocations are allowed in that 1GB block, while new unmovable/reclaimable allocations are still allowed
- when a 1GB block is below that threshold, use the migration code to evacuate enough movable memory from the 1GB block to bring free memory in that 1GB block back to the threshold
These strategies together serve to concentrate unmovable and reclaimable allocations in as few 1GB blocks as possible, leaving as many 1GB blocks as possible available for movable allocations.
That enables both more extensive use of 2MB THPs and mTHPs, as well as reliable allocation of 1GB pages.
The above strategies also make the core page allocator more complicated, and slower. In order to avoid that issue, the series is built on top of Johannes's PCPBuddy series, which has the goal of reducing how often CPUs need to get pages from the zone free lists, instead relying on CPUs giving back pages to each other, based on page block ownership.
TODO:
- compaction "always" succeeds, with a success rate of 99.96% seen in traces; this sounds great, but it also results in compaction never being throttled, and compaction blowing out everybody's PCP through lru_add_drain() calls. This needs some sort of solution.
- replace the superpageblock name with something Matthew and David both like
- find more corner cases, and fix them
Based on e1914add2799
RFC PATCH 1/40 mm: page_alloc: replace pageblock_flags bitmap with struct pageblock_data
From: Johannes Weiner <[email protected]>
Replace the packed pageblock_flags bitmap with a per-pageblock struct containing its own flags word. This changes the storage from NR_PAGEBLOCK_BITS bits per pageblock packed into shared unsigned longs, to a dedicated unsigned long per pageblock.
The free path looks up migratetype (from pageblock flags) immediately followed by looking up pageblock ownership. Colocating them in a struct means this hot path touches one cache line instead of two.
The per-pageblock struct also eliminates all the bit-packing indexing (pfn_to_bitidx, word selection, intra-word shifts), simplifying the accessor code.
Memory overhead: 8 bytes per pageblock (one unsigned long). With 2MB pageblocks on x86_64, that's 4KB per GB -- up from ~0.5-1 bytes per pageblock with the packed bitmap, but still negligible in absolute terms.
No functional change.
--- include/linux/mmzone.h | 15 ++++---- mm/internal.h | 17 +++++++++ mm/mm_init.c | 25 +++++-------- mm/page_alloc.c | 84 +++++++----------------------------------- mm/sparse.c | 3 +- 5 files changed, 50 insertions(+), 94 deletions(-)
include/linux/mmzone.h +8 -7
@@ -1004,7 +1004,7 @@ struct zone {* Flags for a pageblock_nr_pages block. See pageblock-flags.h. * In SPARSEMEM, this map is stored in struct mem_section */ -unsigned long *pageblock_flags; +struct pageblock_data *pageblock_data;#endif /* CONFIG_SPARSEMEM */ /* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */
@@ -1957,9 +1957,6 @@ static inline bool movable_only_nodes(nodemask_t *nodes)#define PAGES_PER_SECTION (1UL << PFN_SECTION_SHIFT)#define PAGE_SECTION_MASK (~(PAGES_PER_SECTION-1)) -#define SECTION_BLOCKFLAGS_BITS \ - ((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS) -#if (MAX_PAGE_ORDER +PAGE_SHIFT ) >SECTION_SIZE_BITS #error Allocator MAX_PAGE_ORDER exceeds SECTION_SIZE#endif
@@ -1992,13 +1989,17 @@ static inline unsigned long section_nr_to_pfn(unsigned long sec)#define SUBSECTION_ALIGN_UP (pfn) ALIGN((pfn), PAGES_PER_SUBSECTION)#define SUBSECTION_ALIGN_DOWN (pfn) ((pfn) & PAGE_SUBSECTION_MASK) +struct pageblock_data { +unsigned long flags; +}; +struct mem_section_usage {struct rcu_head rcu;#ifdef CONFIG_SPARSEMEM_VMEMMAP DECLARE_BITMAP(subsection_map, SUBSECTIONS_PER_SECTION);#endif /* See declaration of similar field in struct zone */ -unsigned long pageblock_flags[0 ]; +struct pageblock_data pageblock_data[]; };struct page ;
@@ -2049,9 +2050,9 @@ extern struct mem_section **mem_section;extern struct mem_section mem_section[NR_SECTION_ROOTS ][SECTIONS_PER_ROOT ];#endif -static inline unsigned long *section_to_usemap (struct mem_section *ms) +static inline struct pageblock_data *section_to_usemap (struct mem_section *ms) { -return ms->usage->pageblock_flags; +return ms->usage->pageblock_data; }static inline struct mem_section *__nr_to_section (unsigned long nr)
mm/internal.h +17 -0
@@ -808,6 +808,23 @@ static inline struct page *find_buddy_page_pfn(struct page *page,return NULL ; } +static inline struct pageblock_data *pfn_to_pageblock (const struct page *page, +unsigned long pfn) +{ +#ifdef CONFIG_SPARSEMEM +struct mem_section *ms =__pfn_to_section (pfn); +unsigned long idx = (pfn & (PAGES_PER_SECTION -1 )) >> pageblock_order; + +return §ion_to_usemap (ms)[idx]; +#else +struct zone *zone =page_zone (page); +unsigned long idx; + + idx = (pfn -pageblock_start_pfn (zone->zone_start_pfn)) >> pageblock_order; +return &zone->pageblock_data[idx]; +#endif +} +extern struct page *__pageblock_pfn_to_page (unsigned long start_pfn,unsigned long end_pfn,struct zone *zone);
mm/mm_init.c +10 -15
@@ -1453,36 +1453,31 @@ void __meminit init_currently_empty_zone(struct zone *zone,#ifndef CONFIG_SPARSEMEM /* -* Calculate the size of the zone->pageblock_flags rounded to an unsigned long -* Start by making sure zonesize is a multiple of pageblock_order by rounding -* up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally -* round what is now in bits to nearest long in bits, then return it in -* bytes. +* Calculate the size of the zone->pageblock_data array. +* Round up the zone size to a pageblock boundary to get the +* number of pageblocks, then multiply by the struct size. */ static unsigned long __init usemap_size (unsigned long zone_start_pfn,unsigned long zonesize) { -unsigned long usemapsize; +unsigned long nr_pageblocks; zonesize += zone_start_pfn & (pageblock_nr_pages-1 ); - usemapsize =round_up (zonesize, pageblock_nr_pages); - usemapsize = usemapsize >> pageblock_order; - usemapsize *=NR_PAGEBLOCK_BITS ; - usemapsize =round_up (usemapsize,BITS_PER_LONG ); + nr_pageblocks =round_up (zonesize, pageblock_nr_pages) >> pageblock_order; -return usemapsize /BITS_PER_BYTE ; +return nr_pageblocks *sizeof (struct pageblock_data ); }static void __ref setup_usemap (struct zone *zone) {unsigned long usemapsize =usemap_size (zone->zone_start_pfn, zone->spanned_pages); - zone->pageblock_flags =NULL ; + zone->pageblock_data =NULL ;if (usemapsize) { - zone->pageblock_flags = + zone->pageblock_data =memblock_alloc_node (usemapsize,SMP_CACHE_BYTES ,zone_to_nid (zone)); -if (!zone->pageblock_flags) -panic ("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n" , +if (!zone->pageblock_data) +panic ("Failed to allocate %ld bytes for zone %s pageblock data on node %d\n" , usemapsize, zone->name,zone_to_nid (zone)); } }
mm/page_alloc.c +13 -71
146 lines not on this page · raw message
mm/sparse.c +2 -1
@@ -216,7 +216,8 @@ static void __init memblocks_present(void)static unsigned long usemap_size (void ) { -return BITS_TO_LONGS (SECTION_BLOCKFLAGS_BITS ) *sizeof (unsigned long ); +return (1UL << (PFN_SECTION_SHIFT - pageblock_order)) * +sizeof (struct pageblock_data ); }size_t mem_section_usage_size (void )
Signature · 1 line
2.54.0
RFC PATCH 2/40 mm: page_alloc: per-cpu pageblock buddy allocator
In reply to Rik van RielFrom: Johannes Weiner <[email protected]>
On large machines, zone->lock is a scaling bottleneck for page allocation. Two common patterns drive contention:
1. Affinity violations: pages are allocated on one CPU but freed on another (jemalloc, exit, reclaim). The freeing CPU's PCP drains to zone buddy, and the allocating CPU refills from zone buddy -- both under zone->lock, defeating PCP batching entirely.
2. Concurrent exits: processes tearing down large address spaces simultaneously overwhelm per-CPU PCP capacity, serializing on zone->lock for overflow.
Solution
Extend the PCP to operate on whole pageblocks with ownership tracking.
Each CPU claims pageblocks from the zone buddy and splits them locally. Pages are tagged with their owning CPU, so frees route back to the owner's PCP regardless of which CPU frees. This eliminates affinity violations: the owner CPU's PCP absorbs both allocations and frees for its blocks without touching zone->lock.
It also shortens zone->lock hold time during drain and refill cycles. Whole blocks are acquired under zone->lock and then split outside of it. Affinity routing to the owning PCP on free enables buddy merging outside the zone->lock as well; a bottom-up merge pass runs under pcp->lock on drain, freeing larger chunks under zone->lock.
PCP refill uses a four-phase approach:
Phase 0: recover owned fragments previously drained to zone buddy. Phase 1: claim whole pageblocks from zone buddy.
Phase 2: grab sub-pageblock chunks without migratetype stealing. Phase 3: traditional __rmqueue() with migratetype fallback.
Phase 0/1 pages are owned and marked PagePCPBuddy, making them eligible for PCP-level merging. Phase 2/3 pages are cached on PCP for batching only -- no ownership, no merging. However, Phase 2 still benefits from chunky zone transactions: it pulls higher-order entries from zone free lists under zone->lock and splits them on the PCP outside of it, rather than acquiring zone->lock per page.
When PCP batch sizes are small (small machines with few CPUs) or the zone is fragmented and no whole pageblocks are available, refill falls through to Phase 2/3 naturally. The allocator degrades gracefully to the original page-at-a-time behavior.
When owned blocks accumulate long-lived allocations (e.g. a mix of anonymous and file cache pages), partial block drains send the free fragments to zone buddy and remember the block, so Phase 0 can recover them on the next refill. This allows the allocator to pack new allocations next to existing ones in already-committed blocks rather than consuming fresh pageblocks, keeping fragmentation contained.
Data structures:
- per_cpu_pages: +owned_blocks list head, +PCPF_CPU_DEAD flag to gate enqueuing on offline CPUs.
- pageblock_data: +cpu (owner), +block_pfn, +cpu_node (recovery list linkage). 32 bytes per pageblock, ~16KB per GB with 2MB pageblocks.
- PagePCPBuddy page type marks pages eligible for PCP-level merging.
[[email protected]: fix ownership clearing on direct block frees]
Note (checkpatch-rationale): the two VM_BUG_ON(order > PAGE_BLOCK_MAX_ORDER) assertions in __pcp_buddy_idx() and __pcp_buddy_order() are intentional and should remain BUG()-class rather than WARN_ON_ONCE(). Their result is used as an array index into the per-CPU pageblock free lists; a violation means the caller passed an invalid order and the index would corrupt adjacent state. Both are VM_BUG_ON (compiled out unless CONFIG_DEBUG_VM=y) and follow the established mm/page_alloc.c convention for invariants on the buddy index domain (see neighbouring VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER) call sites this patch replaces).
--- include/linux/mmzone.h | 23 +- include/linux/page-flags.h | 9 + mm/debug.c | 1 + mm/page_alloc.c | 668 ++++++++++++++++++++++++++++++------- 4 files changed, 576 insertions(+), 125 deletions(-)
include/linux/mmzone.h +13 -10
@@ -802,17 +802,10 @@ enum zone_watermarks { };/* -* One per migratetype for each PAGE_ALLOC_COSTLY_ORDER. Two additional lists -* are added for THP. One PCP list is used by GPF_MOVABLE, and the other PCP list -* is used by GFP_UNMOVABLE and GFP_RECLAIMABLE. +* One per migratetype for page orders up to and including PAGE_BLOCK_MAX_ORDER. */ -#ifdef CONFIG_TRANSPARENT_HUGEPAGE -#define NR_PCP_THP 2 -#else -#define NR_PCP_THP 0 -#endif -#define NR_LOWORDER_PCP_LISTS (MIGRATE_PCPTYPES * (PAGE_ALLOC_COSTLY_ORDER + 1)) -#define NR_PCP_LISTS (NR_LOWORDER_PCP_LISTS + NR_PCP_THP) +#define NR_PCP_ORDERS (PAGE_BLOCK_MAX_ORDER + 1) +#define NR_PCP_LISTS (MIGRATE_PCPTYPES * NR_PCP_ORDERS)/* * Flags used in pcp->flags field.
@@ -825,9 +818,13 @@ enum zone_watermarks {* draining PCP for consecutive high-order pages freeing without * allocation if data cache slice of CPU is large enough. To reduce * zone lock contention and keep cache-hot pages reusing. +* +* PCPF_CPU_DEAD: CPU is offline. Don't enqueue freed pages; fall +* back to zone buddy instead. */ #define PCPF_PREV_FREE_HIGH_ORDER BIT(0)#define PCPF_FREE_HIGH_BATCH BIT(1) +#define PCPF_CPU_DEAD BIT(2)struct per_cpu_pages {spinlock_t lock;/* Protects lists field */
@@ -843,6 +840,9 @@ struct per_cpu_pages {#endif short free_count;/* consecutive free count */ +/* Pageblocks owned by this CPU, for fragment recovery */ +struct list_head owned_blocks; +/* Lists of pages, one per migrate type stored on the pcp-lists */ struct list_head lists[NR_PCP_LISTS ]; }____cacheline_aligned_in_smp ;
@@ -1991,6 +1991,9 @@ static inline unsigned long section_nr_to_pfn(unsigned long sec)struct pageblock_data {unsigned long flags; +int cpu;/* PCP ownership: owning cpu + 1, or 0 for zone-owned */ +unsigned long block_pfn;/* first PFN of pageblock */ +struct list_head cpu_node;/* per-CPU owned-blocks list */ };struct mem_section_usage {
include/linux/page-flags.h +9 -0
@@ -924,6 +924,7 @@ enum pagetype { PGTY_unaccepted =0xf7 , PGTY_large_kmalloc =0xf8 , PGTY_netpp =0xf9 , + PGTY_pcp_buddy =0xfa , PGTY_mapcount_underflow = 0xff };
@@ -992,6 +993,14 @@ static __always_inline void __ClearPage##uname(struct page *page) \*/ PAGE_TYPE_OPS (Buddy, buddy, buddy) +/* +* PagePCPBuddy() indicates that the page is free and in a per-cpu +* buddy allocator (see mm/page_alloc.c). Unlike PageBuddy() pages, +* these are not on zone free lists and must not be isolated by +* compaction or other zone-level code. + */ +PAGE_TYPE_OPS (PCPBuddy, pcp_buddy, pcp_buddy) +/* * PageOffline() indicates that the page is logically offline although the * containing section is online. (e.g. inflated in a balloon driver or
mm/debug.c +1 -0
@@ -56,6 +56,7 @@ static const char *page_type_names[] = {DEF_PAGETYPE_NAME (table),DEF_PAGETYPE_NAME (buddy),DEF_PAGETYPE_NAME (unaccepted), + DEF_PAGETYPE_NAME(pcp_buddy), };static const char *page_type_name (unsigned int page_type)
mm/page_alloc.c +553 -115
984 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 3/40 mm: page_alloc: split-path PCP free with local-trylock + remote-llist
In reply to Rik van RielThe page allocator's PCP free path needs lock-inversion protection against zone->lock. The natural form -- always take pcp->lock with spin_lock -- can deadlock because callers may hold locks (e.g. xa_lock via slab/stack_depot) that are also taken in hardirq context, and pcp->lock is acquired with IRQs enabled on the allocation side.
A coarse fix is to use spin_trylock and fall back to free_one_page() (direct zone-buddy free) on contention. That removes the inversion risk but defeats the per-CPU pageset benefits on a busy multi-CPU
system: many frees take the slow zone->lock path, and the per-CPU pcp->count visible to allocators understates real free-page availability for the remote CPU's pageset.
Replace the trylock-fallback with a per-CPU remote free list (llist) consumed by the owning CPU. Local frees still use the trylock path; remote frees push onto the target's lockless llist; the owning CPU absorbs the queued pages back onto its PCP buddy lists at the next opportunity. Result: zero lock-inversion risk, no zone->lock fallback storm, and remote frees become near-free at the freer's side.
Mechanics:
- per_cpu_pages gains struct llist_head free_llist.
- absorb_remote_frees(pcp) drains the llist into the local PCP buddy lists. Called from pcp_rmqueue_smallest(), free_pcppages_bulk(), and drain_pages_zone().
- __free_frozen_pages and free_unref_folios are split into a local path (spin_trylock on pcp->lock; on success enqueue locally) and a remote path (llist_add to the target CPU's free_llist).
- The local-side spin_trylock no longer takes irqsave: lockdep analysis showed no IRQ-context caller of the local PCP free path that is also a holder of pcp->lock; the remote-from-IRQ case routes through llist_add (NMI-safe).
- Memory hot-add lazy init: page_alloc_cpu_dead drains the dead PCP via existing drain_pages_zone (which now also drains the llist via absorb_remote_frees). For the narrow race where a remote freer raced PCPF_CPU_DEAD and pushed onto the dead PCP's llist after the drain, page_alloc_cpu_online absorbs any stranded pages.
- page_alloc_cpu_dead detaches every entry from owned_blocks via list_del_init before reinitializing the list head. A simpler INIT_LIST_HEAD-only form leaves owned PB entries with stale ->prev/->next pointing at the dead head -- they get list_del()'d later by clear_pcpblock_owner() under zone->lock, corrupting whatever now happens to be at the dead head address. A stress-test reproducer surfaced this as a list_del prev->next == prev WARN.
QEMU stress (234K worker iters + 5 hotplug cycles + 30 hugepages):
zero WARN/BUG. Bare-metal test machine ran for ~14 hours under production-style load with no list_del corruption, no WARN, no panic.
--- include/linux/mmzone.h | 9 ++ mm/page_alloc.c | 249 ++++++++++++++++++++++++++++++----------- 2 files changed, 193 insertions(+), 65 deletions(-)
include/linux/mmzone.h +9 -0
@@ -843,6 +843,15 @@ struct per_cpu_pages {/* Pageblocks owned by this CPU, for fragment recovery */ struct list_head owned_blocks; +/* +* Pages remotely freed by other CPUs into pageblocks owned by +* this CPU. Lock-free push by remote freers via llist_add(); the +* owning CPU drains and merges them into its PCP buddy lists at +* convenient moments (start of pcp_rmqueue_smallest, drain +* paths) under pcp->lock. +*/ +struct llist_head free_llist; +/* Lists of pages, one per migrate type stored on the pcp-lists */ struct list_head lists[NR_PCP_LISTS ]; }____cacheline_aligned_in_smp ;
mm/page_alloc.c +184 -65
361 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 4/40 mm: mm_init: fix zone assignment for pages in unavailable ranges
In reply to Rik van Rielinit_unavailable_range() initializes struct pages for memory holes between memblock regions. It receives a zone ID from its caller, but that zone ID is simply the last zone processed in memmap_init()'s iteration -- it does not necessarily match the zone that actually spans each PFN in the hole.
When an unavailable range straddles a zone boundary (e.g. a hole between DMA32 and Normal), all pages in the hole get tagged with the wrong zone in page->flags. Any later page_zone() call on such a page returns the wrong zone, which can cause accounting confusion or crashes when code assumes the returned zone is valid for that page.
Fix by looking up the correct zone for each PFN in the hole. This is init- only code running once at boot, so the per-page zone lookup has no performance impact.
--- mm/mm_init.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
mm/mm_init.c +19 -1
@@ -834,9 +834,27 @@ static void __init init_unavailable_range(unsigned long spfn, {unsigned long pfn;u64 pgcnt =0 ; +pg_data_t *pgdat =NODE_DATA (node); +int zid = zone;for_each_valid_pfn (pfn, spfn, epfn) { -__init_single_page (pfn_to_page (pfn), pfn, zone, node); +/* +* The caller's zone may not match the PFN when unavailable +* ranges straddle zone boundaries. Look up the correct zone +* so page->flags encodes the right zone for page_zone(). +*/ +if (!zone_spans_pfn (&pgdat->node_zones[zid], pfn)) { +int z; + +for (z =0 ; z <MAX_NR_ZONES ; z++) { +if (zone_spans_pfn (&pgdat->node_zones[z], pfn)) { + zid = z; +break ; + } + } + } + +__init_single_page (pfn_to_page (pfn), pfn, zid, node);__SetPageReserved (pfn_to_page (pfn)); pgcnt++; }
Signature · 1 line
2.54.0
RFC PATCH 5/40 mm: page_alloc: remove watermark boost mechanism
In reply to Rik van Rielwatermark_boost was introduced to react to fragmentation events at the pageblock granularity: a sub-pageblock cross-type fallback would raise the zone watermark and wake kswapd, on the theory that reclaiming some order-0 pages would reduce future fallbacks.
With superpageblocks, anti-fragmentation is enforced at 1 GiB SPB granularity, and the meaningful signals (CLEAN->TAINT events, empty SPB count) live there. Sub-pageblock fallbacks inside an already-tainted SPB do not change the fragmentation picture, and order-0 reclaim does not unmix a pageblock or surface a fresh clean SPB.
Worse, the boost is applied in try_to_claim_block() before the success path is decided. When option 1 (no UNMOVABLE/RECLAIMABLE pageblock mixing) rejects a cross-type relabel, the boost has already been applied and the next rmqueue() will wake kswapd to drain memory back to high+boost - even when free pages are tens of times the high watermark. Real workloads showed bursts of >150 wakeup_kswapd/min, all order-0, with stack traces consistently arriving from rmqueue() through the boost-cleanup path. Free memory at the time was 38x the high watermark.
Drop the mechanism entirely:
- boost_watermark() and its callsite in try_to_claim_block()
- the ZONE_BOOSTED_WATERMARK flag and its set/clear in rmqueue()
- zone->watermark_boost and the boost addend in wmark_pages()
- the __GFP_HIGH boost-bypass path in zone_watermark_fast()
- the watermark_boost_factor sysctl
- boost-aware logic in balance_pgdat() (nr_boost_reclaim, zone_boosts[], pgdat_watermark_boosted, the boost-restart goto, no-writeback for boost reclaim, the boost-only kcompactd wakeup)
--- Documentation/admin-guide/sysctl/vm.rst | 21 ----- Documentation/mm/physical_memory.rst | 13 +-- include/linux/mmzone.h | 6 +- mm/page_alloc.c | 82 +---------------- mm/show_mem.c | 2 - mm/vmscan.c | 115 ++---------------------- mm/vmstat.c | 2 - 7 files changed, 14 insertions(+), 227 deletions(-)
Documentation/admin-guide/sysctl/vm.rst +0 -21
@@ -76,7 +76,6 @@ files can be found in mm/swap.c. - user_reserve_kbytes - vfs_cache_pressure - vfs_cache_pressure_denom -- watermark_boost_factor - watermark_scale_factor - zone_reclaim_mode
@@ -1073,26 +1072,6 @@ vfs_cache_pressure_denom Defaults to 100 (minimum allowed value). Requires corresponding vfs_cache_pressure setting to take effect. -watermark_boost_factor -====================== - -This factor controls the level of reclaim when memory is being fragmented. -It defines the percentage of the high watermark of a zone that will be -reclaimed if pages of different mobility are being mixed within pageblocks. -The intent is that compaction has less work to do in the future and to -increase the success rate of future high-order allocations such as SLUB -allocations, THP and hugetlbfs pages. - -To make it sensible with respect to the watermark_scale_factor -parameter, the unit is in fractions of 10,000. The default value of -15,000 means that up to 150% of the high watermark will be reclaimed in the -event of a pageblock being mixed due to fragmentation. The level of reclaim -is determined by the number of fragmentation events that occurred in the -recent past. If this value is smaller than a pageblock then a pageblocks -worth of pages will be reclaimed (e.g. 2MB on 64-bit x86). A boost factor -of 0 will disable the feature. - - watermark_scale_factor ======================
Documentation/mm/physical_memory.rst +3 -10
@@ -394,11 +394,6 @@ General to the distance between two watermarks. The distance itself is calculated taking ``vm.watermark_scale_factor`` sysctl into account. -``watermark_boost`` - The number of pages which are used to boost watermarks to increase reclaim - pressure to reduce the likelihood of future fallbacks and wake kswapd now - as the node may be balanced overall and kswapd will not wake naturally. - ``nr_reserved_highatomic`` The number of pages which are reserved for high-order atomic allocations.
@@ -527,11 +522,9 @@ General Defined only when ``CONFIG_UNACCEPTED_MEMORY`` is enabled. ``flags`` - The zone flags. The least three bits are used and defined by - ``enum zone_flags``. ``ZONE_BOOSTED_WATERMARK`` (bit 0): zone recently boosted - watermarks. Cleared when kswapd is woken. ``ZONE_RECLAIM_ACTIVE`` (bit 1): - kswapd may be scanning the zone. ``ZONE_BELOW_HIGH`` (bit 2): zone is below - high watermark. + The zone flags. The bits are defined by ``enum zone_flags``. + ``ZONE_RECLAIM_ACTIVE`` (bit 0): kswapd may be scanning the zone. + ``ZONE_BELOW_HIGH`` (bit 1): zone is below high watermark. ``lock`` The main lock that protects the internal data structures of the page allocator
include/linux/mmzone.h +1 -5
@@ -978,7 +978,6 @@ struct zone {/* zone watermarks, access with *_wmark_pages(zone) macros */ unsigned long _watermark[NR_WMARK ]; -unsigned long watermark_boost;unsigned long nr_reserved_highatomic;unsigned long nr_free_highatomic;
@@ -1167,9 +1166,6 @@ enum pgdat_flags { };enum zone_flags { -ZONE_BOOSTED_WATERMARK ,/* zone recently boosted watermarks. -* Cleared when kswapd is woken. -*/ ZONE_RECLAIM_ACTIVE ,/* kswapd may be scanning the zone. */ ZONE_BELOW_HIGH ,/* zone is below high watermark. */ };
@@ -1177,7 +1173,7 @@ enum zone_flags {static inline unsigned long wmark_pages (const struct zone *z,enum zone_watermarks w) { -return z->_watermark[w] + z->watermark_boost; +return z->_watermark[w]; }static inline unsigned long min_wmark_pages (const struct zone *z)
mm/page_alloc.c +2 -80
124 lines not on this page · raw message
mm/show_mem.c +0 -2
@@ -302,7 +302,6 @@ static void show_free_areas(unsigned int filter, nodemask_t *nodemask, int max_zprintk (KERN_CONT "%s" " free:%lukB" -" boost:%lukB" " min:%lukB" " low:%lukB" " high:%lukB"
@@ -325,7 +324,6 @@ static void show_free_areas(unsigned int filter, nodemask_t *nodemask, int max_z"\n" , zone->name,K (zone_page_state (zone,NR_FREE_PAGES )), -K (zone->watermark_boost),K (min_wmark_pages (zone)),K (low_wmark_pages (zone)), K(high_wmark_pages(zone)),
mm/vmscan.c +8 -107
172 lines not on this page · raw message
mm/vmstat.c +0 -2
@@ -1769,7 +1769,6 @@ static void zoneinfo_show_print(struct seq_file *m, pg_data_t *pgdat, }seq_printf (m,"\n pages free %lu" -"\n boost %lu" "\n min %lu" "\n low %lu" "\n high %lu"
@@ -1779,7 +1778,6 @@ static void zoneinfo_show_print(struct seq_file *m, pg_data_t *pgdat,"\n managed %lu" "\n cma %lu" ,zone_page_state (zone,NR_FREE_PAGES ), - zone->watermark_boost,min_wmark_pages (zone),low_wmark_pages (zone), high_wmark_pages(zone),
Signature · 1 line
2.54.0
Re: [RFC PATCH 05/40] mm: page_alloc: remove watermark boost mechanism
Quoted 267 lines · On Wed, 20 May 2026 10:59:11 -0400 Rik van Riel <[email protected]> wrote:
watermark_boostwas introduced to react to fragmentation events at the pageblock granularity: a sub-pageblock cross-type fallback would raise the zone watermark and wake kswapd, on the theory that reclaiming some order-0 pages would reduce future fallbacks.With superpageblocks, anti-fragmentation is enforced at 1 GiB SPB granularity, and the meaningful signals (
CLEAN->TAINTevents, empty SPB count) live there. Sub-pageblock fallbacks inside an already-tainted SPB do not change the fragmentation picture, and order-0 reclaim does not unmix a pageblock or surface a fresh clean SPB.Worse, the boost is applied in
try_to_claim_block()before the success path is decided. When option 1 (no UNMOVABLE/RECLAIMABLE pageblock mixing) rejects a cross-type relabel, the boost has already been applied and the nextrmqueue()will wake kswapd to drain memory back to high+boost - even when free pages are tens of times the high watermark. Real workloads showed bursts of >150 wakeup_kswapd/min, all order-0, with stack traces consistently arriving fromrmqueue()through the boost-cleanup path. Free memory at the time was 38x the high watermark.Drop the mechanism entirely:
-
boost_watermark()and its callsite intry_to_claim_block()
- theZONE_BOOSTED_WATERMARKflag and its set/clear inrmqueue()
-zone->watermark_boostand the boost addend inwmark_pages()
- the__GFP_HIGHboost-bypass path inzone_watermark_fast()
- thewatermark_boost_factorsysctl
- boost-aware logic inbalance_pgdat()(nr_boost_reclaim, zone_boosts[],pgdat_watermark_boosted, the boost-restart goto, no-writeback for boost reclaim, the boost-only kcompactd wakeup)Signed-off-by Rik van Riel <[email protected]>Assisted-by Claude:claude-opus-4.7 syzkaller--- Documentation/admin-guide/sysctl/vm.rst | 21 ----- Documentation/mm/physical_memory.rst | 13 +-- include/linux/mmzone.h | 6 +- mm/page_alloc.c | 82 +---------------- mm/show_mem.c | 2 - mm/vmscan.c | 115 ++---------------------- mm/vmstat.c | 2 - 7 files changed, 14 insertions(+), 227 deletions(-)Documentation/admin-guide/sysctl/vm.rst +0
-21@@ -76,7 +76,6 @@ files can be found in mm/swap.c. - user_reserve_kbytes - vfs_cache_pressure - vfs_cache_pressure_denom -- watermark_boost_factor - watermark_scale_factor - zone_reclaim_mode@@ -1073,26 +1072,6 @@ vfs_cache_pressure_denom Defaults to 100 (minimum allowed value). Requires corresponding vfs_cache_pressure setting to take effect. -watermark_boost_factor -====================== - -This factor controls the level of reclaim when memory is being fragmented. -It defines the percentage of the high watermark of a zone that will be -reclaimed if pages of different mobility are being mixed within pageblocks. -The intent is that compaction has less work to do in the future and to -increase the success rate of future high-order allocations such as SLUB -allocations, THP and hugetlbfs pages. - -To make it sensible with respect to the watermark_scale_factor -parameter, the unit is in fractions of 10,000. The default value of -15,000 means that up to 150% of the high watermark will be reclaimed in the -event of a pageblock being mixed due to fragmentation. The level of reclaim -is determined by the number of fragmentation events that occurred in the -recent past. If this value is smaller than a pageblock then a pageblocks -worth of pages will be reclaimed (e.g. 2MB on 64-bit x86). A boost factor -of 0 will disable the feature. - - watermark_scale_factor ======================Documentation/mm/physical_memory.rst +3
-10@@ -394,11 +394,6 @@ General to the distance between two watermarks. The distance itself is calculated taking ``vm.watermark_scale_factor`` sysctl into account. -``watermark_boost`` - The number of pages which are used to boost watermarks to increase reclaim - pressure to reduce the likelihood of future fallbacks and wake kswapd now - as the node may be balanced overall and kswapd will not wake naturally. - ``nr_reserved_highatomic`` The number of pages which are reserved for high-order atomic allocations.@@ -527,11 +522,9 @@ General Defined only when ``CONFIG_UNACCEPTED_MEMORY`` is enabled. ``flags`` - The zone flags. The least three bits are used and defined by - ``enum zone_flags``. ``ZONE_BOOSTED_WATERMARK`` (bit 0): zone recently boosted - watermarks. Cleared when kswapd is woken. ``ZONE_RECLAIM_ACTIVE`` (bit 1): - kswapd may be scanning the zone. ``ZONE_BELOW_HIGH`` (bit 2): zone is below - high watermark. + The zone flags. The bits are defined by ``enum zone_flags``. + ``ZONE_RECLAIM_ACTIVE`` (bit 0): kswapd may be scanning the zone. + ``ZONE_BELOW_HIGH`` (bit 1): zone is below high watermark. ``lock`` The main lock that protects the internal data structures of the page allocatorinclude/linux/mmzone.h +1
-5@@ -978,7 +978,6 @@ struct zone {/* zone watermarks, access with *_wmark_pages(zone) macros */ unsigned long _watermark[NR_WMARK ]; -unsigned long watermark_boost;unsigned long nr_reserved_highatomic;unsigned long nr_free_highatomic;@@ -1167,9 +1166,6 @@ enum pgdat_flags { };enum zone_flags { -ZONE_BOOSTED_WATERMARK ,/* zone recently boosted watermarks. -* Cleared when kswapd is woken. -*/ ZONE_RECLAIM_ACTIVE ,/* kswapd may be scanning the zone. */ ZONE_BELOW_HIGH ,/* zone is below high watermark. */ };@@ -1177,7 +1173,7 @@ enum zone_flags {static inline unsigned long wmark_pages (const struct zone *z,enum zone_watermarks w) { -return z->_watermark[w] + z->watermark_boost; +return z->_watermark[w]; }static inline unsigned long min_wmark_pages (const struct zone *z)mm/page_alloc.c +2
-72@@ -267,7 +267,6 @@ const char * const migratetype_names[MIGRATE_TYPES] = {int min_free_kbytes =1024 ;int user_min_free_kbytes =-1 ; -static int watermark_boost_factor__read_mostly =15000 ;static int watermark_scale_factor =10 ;int defrag_mode;@@ -2340,43 +2339,6 @@ bool pageblock_unisolate_and_move_free_pages(struct zone *zone, struct page *pag#endif /* CONFIG_MEMORY_ISOLATION */ -static inline bool boost_watermark (struct zone *zone) -{ -unsigned long max_boost; - -if (!watermark_boost_factor) -return false; -/* -* Don't bother in zones that are unlikely to produce results. -* On small machines, including kdump capture kernels running -* in a small area, boosting the watermark can cause an out of -* memory situation immediately. -*/ -if ((pageblock_nr_pages *4 ) >zone_managed_pages (zone)) -return false; - - max_boost =mult_frac (zone->_watermark[WMARK_HIGH ], - watermark_boost_factor,10000 ); - -/* -* high watermark may be uninitialised if fragmentation occurs -* very early in boot so do not boost. We do not fall -* through and boost by pageblock_nr_pages as failing -* allocations that early means that reclaim is not going -* to help and it may even be impossible to reclaim the -* boosted watermark resulting in a hang. -*/ -if (!max_boost) -return false; - - max_boost =max (pageblock_nr_pages, max_boost); - - zone->watermark_boost =min (zone->watermark_boost + pageblock_nr_pages, - max_boost); - -return true; -} -/* * When we are falling back to another migratetype during allocation, should we * try to claim an entire block to satisfy further allocations, instead of @@ -2477,14 +2439,6 @@ try_to_claim_block(struct zone *zone, struct page *page,return page; } -/* -* Boost watermarks to increase reclaim pressure to reduce the -* likelihood of future fallbacks. Wake kswapd now as the node -* may be balanced overall and kswapd will not wake naturally. -*/ -if (boost_watermark (zone) && (alloc_flags &ALLOC_KSWAPD )) -set_bit (ZONE_BOOSTED_WATERMARK , &zone->flags); -/* moving whole block can fail due to zone boundary conditions */ if (!prep_move_freepages_block (zone, page, &start_pfn, &free_pages, &movable_pages))@@ -3839,13 +3793,6 @@ struct page *rmqueue(struct zone *preferred_zone, migratetype); out: -/* Separate test+clear to avoid unnecessary atomics */ -if ((alloc_flags &ALLOC_KSWAPD ) && -unlikely (test_bit (ZONE_BOOSTED_WATERMARK , &zone->flags))) { -clear_bit (ZONE_BOOSTED_WATERMARK , &zone->flags); -wakeup_kswapd (zone,0 ,0 ,zone_idx (zone)); - } -VM_BUG_ON_PAGE (page &&bad_range (zone, page), page);return page; }@@ -4123,24 +4070,8 @@ static inline bool zone_watermark_fast(struct zone *z, unsigned int order,return true; } -if (__zone_watermark_ok (z, order, mark, highest_zoneidx, alloc_flags, - free_pages)) -return true; - -/* -* Ignore watermark boosting for __GFP_HIGH order-0 allocations -* when checking the min watermark. The min watermark is the -* point where boosting is ignored so that kswapd is woken up -* when below the low watermark. -*/ -if (unlikely (!order && (alloc_flags &ALLOC_MIN_RESERVE ) && z->watermark_boost - && ((alloc_flags &ALLOC_WMARK_MASK ) ==WMARK_MIN ))) { - mark = z->_watermark[WMARK_MIN ]; -return __zone_watermark_ok (z, order, mark, highest_zoneidx, - alloc_flags, free_pages); - } - -return false; +return __zone_watermark_ok (z, order, mark, highest_zoneidx, alloc_flags, + free_pages); }#ifdef CONFIG_NUMA @@ -6919,7 +6850,6 @@ static void __setup_per_zone_wmarks(void)mult_frac (zone_managed_pages (zone), watermark_scale_factor, 10000)); - zone->watermark_boost =0 ; zone->_watermark[WMARK_LOW ] =min_wmark_pages (zone) + tmp; zone->_watermark[WMARK_HIGH ] =low_wmark_pages (zone) + tmp; zone->_watermark[WMARK_PROMO ] =high_wmark_pages (zone) + tmp;@@ -7187,14 +7117,6 @@ static const struct ctl_table page_alloc_sysctl_table[] = { .proc_handler = min_free_kbytes_sysctl_handler,
mm/page_alloc.c static const struct ctl_table page_alloc_sysctl_table[] = { · line 7197
Quoted 10 lines
mm/page_alloc.c +0
-8.extra1 = SYSCTL_ZERO, }, - { - .procname = "watermark_boost_factor", - .data = &watermark_boost_factor, - .maxlen = sizeof(watermark_boost_factor), - .mode = 0644, - .proc_handler = proc_dointvec_minmax, - .extra1 = SYSCTL_ZERO, - },
This is a userspace-visible removal. Writes to /proc/sys/vm/watermark_boost_factor will now return -ENOENT instead of being accepted, breaking userspace.
I am not sure whats been done in the past, but we need to add a Documentation/ABI/removed/ note explaining what replaces it (SPB steering). and also maybe keep the sysctl entry as a no-op with warning for a few cycles before deletion?
mm/show_mem.c static void show_free_areas(unsigned int filter, nodemask_t *nodemask, int max_z · line 305
Quoted 12 lines
mm/page_alloc.c +0
-0{ .procname = "watermark_scale_factor", .data = &watermark_scale_factor,mm/show_mem.c +0
-1@@ -302,7 +302,6 @@ static void show_free_areas(unsigned int filter, nodemask_t *nodemask, int max_zprintk (KERN_CONT "%s" " free:%lukB" - " boost:%lukB"
The boost: field in /proc/zoneinfo and the show_mem output also disappears. Something similar might need to be done for this as well.
Quoted 219 lines
mm/show_mem.c +0
-1" min:%lukB" " low:%lukB" " high:%lukB" @@ -325,7 +324,6 @@ static void show_free_areas(unsigned int filter, nodemask_t *nodemask, int max_z"\n" , zone->name,K (zone_page_state (zone,NR_FREE_PAGES )), -K (zone->watermark_boost),K (min_wmark_pages (zone)),K (low_wmark_pages (zone)), K(high_wmark_pages(zone)),mm/vmscan.c +8
-107@@ -6883,30 +6883,6 @@ static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc) }while (memcg); } -static bool pgdat_watermark_boosted (pg_data_t *pgdat,int highest_zoneidx) -{ -int i; -struct zone *zone; - -/* -* Check for watermark boosts top-down as the higher zones -* are more likely to be boosted. Both watermarks and boosts -* should not be checked at the same time as reclaim would -* start prematurely when there is no boosting and a lower -* zone is balanced. -*/ -for (i = highest_zoneidx; i >=0 ; i--) { - zone = pgdat->node_zones + i; -if (!managed_zone (zone)) -continue ; - -if (zone->watermark_boost) -return true; - } - -return false; -} -/* * Returns true if there is an eligible zone balanced for the request order * and highest_zoneidx @@ -7111,14 +7087,13 @@ static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)unsigned long nr_soft_reclaimed;unsigned long nr_soft_scanned;unsigned long pflags; -unsigned long nr_boost_reclaim; -unsigned long zone_boosts[MAX_NR_ZONES ] = {0 , }; -bool boosted;struct zone *zone;struct scan_control sc = { .gfp_mask =GFP_KERNEL , .order = order, .may_unmap =1 , + .may_writepage =1 , + .may_swap =1 , };set_task_reclaim_state (current, &sc.reclaim_state);@@ -7127,18 +7102,6 @@ static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)count_vm_event (PAGEOUTRUN ); -/* -* Account for the reclaim boost. Note that the zone boost is left in -* place so that parallel allocations that are near the watermark will -* stall or direct reclaim until kswapd is finished. -*/ - nr_boost_reclaim =0 ; -for_each_managed_zone_pgdat (zone, pgdat, i, highest_zoneidx) { - nr_boost_reclaim += zone->watermark_boost; - zone_boosts[i] = zone->watermark_boost; - } - boosted = nr_boost_reclaim; - restart:set_reclaim_active (pgdat, highest_zoneidx); sc.priority =DEF_PRIORITY ;@@ -7173,39 +7136,14 @@ static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx) }/* -* If the pgdat is imbalanced then ignore boosting and preserve -* the watermarks for a later time and restart. Note that the -* zone watermarks will be still reset at the end of balancing -* on the grounds that the normal reclaim should be enough to -* re-evaluate if boosting is required when kswapd next wakes. +* If there are no eligible zones, no work to do. Note that +* sc.reclaim_idx is not used as buffer_heads_over_limit may +* have adjusted it. */ balanced =pgdat_balanced (pgdat, sc.order, highest_zoneidx); -if (!balanced && nr_boost_reclaim) { - nr_boost_reclaim =0 ; - goto restart; - } - -/* -* If boosting is not active then only reclaim if there are no -* eligible zones. Note that sc.reclaim_idx is not used as -* buffer_heads_over_limit may have adjusted it. -*/ -if (!nr_boost_reclaim && balanced) +if (balanced) goto out; -/* Limit the priority of boosting to avoid reclaim writeback */ -if (nr_boost_reclaim && sc.priority ==DEF_PRIORITY -2 ) - raise_priority = false; - -/* -* Do not writeback or swap pages for boosted reclaim. The -* intent is to relieve pressure not issue sub-optimal IO -* from reclaim context. If no pages are reclaimed, the -* reclaim will be aborted. -*/ - sc.may_writepage = !nr_boost_reclaim; - sc.may_swap = !nr_boost_reclaim; -/* * Do some background aging, to give pages a chance to be * referenced before reclaiming. All pages are rotated @@ -7249,15 +7187,6 @@ static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)* progress in reclaiming pages */ nr_reclaimed = sc.nr_reclaimed - nr_reclaimed; - nr_boost_reclaim -=min (nr_boost_reclaim, nr_reclaimed); - -/* -* If reclaim made no progress for a boost, stop reclaim as -* IO cannot be queued and it could be an infinite loop in -* extreme circumstances. -*/ -if (nr_boost_reclaim && !nr_reclaimed) -break ;if (raise_priority || !nr_reclaimed) sc.priority--;@@ -7273,12 +7202,7 @@ static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx) goto restart; } -/* -* If the reclaim was boosted, we might still be far from the -* watermark_high at this point. We need to avoid increasing the -* failure count to prevent the kswapd thread from stopping. -*/ -if (!sc.nr_reclaimed && !boosted) { +if (!sc.nr_reclaimed) {int fail_cnt =atomic_inc_return (&pgdat->kswapd_failures);/* kswapd context, low overhead to trace every failure */ trace_mm_vmscan_kswapd_reclaim_fail (pgdat->node_id, fail_cnt);@@ -7287,28 +7211,6 @@ static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx) out:clear_reclaim_active (pgdat, highest_zoneidx); -/* If reclaim was boosted, account for the reclaim done in this pass */ -if (boosted) { -unsigned long flags; - -for (i =0 ; i <= highest_zoneidx; i++) { -if (!zone_boosts[i]) -continue ; - -/* Increments are under the zone lock */ - zone = pgdat->node_zones + i; -spin_lock_irqsave (&zone->lock, flags); - zone->watermark_boost -=min (zone->watermark_boost, zone_boosts[i]); -spin_unlock_irqrestore (&zone->lock, flags); - } - -/* -* As there is now likely space, wakeup kcompact to defragment -* pageblocks. -*/ -wakeup_kcompactd (pgdat, pageblock_order, highest_zoneidx); - } -snapshot_refaults (NULL , pgdat);__fs_reclaim_release (_THIS_IP_);psi_memstall_leave (&pflags);@@ -7542,8 +7444,7 @@ void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,/* Hopeless node, leave it to direct reclaim if possible */ if (kswapd_test_hopeless (pgdat) || - (pgdat_balanced (pgdat, order, highest_zoneidx) && - !pgdat_watermark_boosted (pgdat, highest_zoneidx))) { +pgdat_balanced (pgdat, order, highest_zoneidx)) {/* * There may be plenty of free memory available, but it's too * fragmented for high-order allocations. Wake up kcompactd mm/vmstat.c +0
-2@@ -1769,7 +1769,6 @@ static void zoneinfo_show_print(struct seq_file *m, pg_data_t *pgdat, }seq_printf (m,"\n pages free %lu" -"\n boost %lu" "\n min %lu" "\n low %lu" "\n high %lu"@@ -1779,7 +1778,6 @@ static void zoneinfo_show_print(struct seq_file *m, pg_data_t *pgdat,"\n managed %lu" "\n cma %lu" ,zone_page_state (zone,NR_FREE_PAGES ), - zone->watermark_boost,min_wmark_pages (zone),low_wmark_pages (zone), high_wmark_pages(zone),Signature · 1 line
2.54.0
Re: [RFC PATCH 05/40] mm: page_alloc: remove watermark boost mechanism
Quoted 24 lines · Usama Arif
Quoted 4 lines · On Wed, 20 May 2026 10:59:11 -0400 Rik van Riel <[email protected]> wrote:
mm/page_alloc.c +0
-0@@ -7187,14 +7117,6 @@ static const struct ctl_table page_alloc_sysctl_table[] = { .proc_handler = min_free_kbytes_sysctl_handler, .extra1 = SYSCTL_ZERO,mm/page_alloc.c static const struct ctl_table · line 7199
Quoted 10 lines
mm/page_alloc.c +0
-8}, - { - .procname = "watermark_boost_factor", - .data = &watermark_boost_factor, - .maxlen = sizeof(watermark_boost_factor), - .mode = 0644, - .proc_handler = proc_dointvec_minmax, - .extra1 = SYSCTL_ZERO, - },This is a userspace-visible removal. Writes to
/proc/sys/vm/watermark_boost_factorwill now return-ENOENTinstead of being
accepted, breaking userspace.
Quoted 6 lines
I am not sure whats been done in the past, but we need to add a
Documentation/ABI/removed/note explaining what replaces it (SPB steering).
and also maybe keep the sysctl entry as a no-op with warning for a few
cycles before deletion?
I'll just drop this patch for now.
While we no longer need it, and the watermark boosting can cause a little bit of harm at times, this probably isn't worth the extra code churn in this series.
Signature · 1 line
All Rights Reversed.
RFC PATCH 6/40 mm: page_alloc: async evacuation of stolen movable pageblocks
In reply to Rik van RielWhen the page allocator steals a movable pageblock for unmovable or reclaimable allocations (via try_to_claim_block), the remaining movable pages in that block can prevent future unmovable/reclaimable allocations from being concentrated in fewer pageblocks, leading to long-term memory fragmentation.
Add a lightweight asynchronous evacuation mechanism: when a movable pageblock is claimed for unmovable/reclaimable use, queue a work item to migrate the remaining movable pages out. This allows future unmovable/reclaimable allocations to be satisfied from the now-evacuated block, keeping those allocation types concentrated and reducing fragmentation.
--- include/linux/mmzone.h | 4 + mm/page_alloc.c | 223 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 227 insertions(+)
include/linux/mmzone.h +4 -0
@@ -22,6 +22,7 @@#include <linux/mm_types.h> #include <linux/page-flags.h> #include <linux/local_lock.h> +#include <linux/irq_work_types.h> #include <linux/zswap.h> #include <linux/sizes.h> #include <asm/page.h>
@@ -1540,6 +1541,9 @@ typedef struct pglist_data {wait_queue_head_t kcompactd_wait;struct task_struct *kcompactd;bool proactive_compact_trigger; +struct workqueue_struct *evacuate_wq; +struct llist_head evacuate_pending; +struct irq_work evacuate_irq_work;#endif /* * This is a per-node reserve of pages that are not available
mm/page_alloc.c +223 -0
259 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 7/40 mm: page_alloc: track actual page contents in pageblock flags
In reply to Rik van RielExtend pageblock_data flags with PB_has_unmovable, PB_has_reclaimable, and PB_has_movable bits to track the actual types of pages allocated within a pageblock, independent of its intended migratetype.
The flags are set at steal time in try_to_claim_block(), avoiding overhead on every allocation in __rmqueue_smallest():
1. Allocation / steal time: when try_to_claim_block() claims a pageblock, set the PB_has_* flag corresponding to the allocation's migratetype. If unmovable or reclaimable pages are being placed into a pageblock that already has PB_has_movable set, queue async evacuation of the remaining movable pages.
2. Full pageblock free: when buddy merging reconstructs a complete pageblock in __free_one_page(), clear all PB_has_* flags since the block is now empty.
3. Migration scan: when isolate_migratepages_block() completes a full pageblock scan and finds no movable pages to isolate, clear PB_has_movable. This consolidates the clearing for all callers: evacuate_pageblock(), compaction, and alloc_contig_range().
This provides the foundation for superpageblock-level steering decisions:
knowing which pageblocks actually contain unmovable/reclaimable pages allows directing future allocations to already-tainted regions, keeping clean regions available for large contiguous allocations.
--- include/linux/pageblock-flags.h | 9 ++++ mm/compaction.c | 17 ++++++ mm/page_alloc.c | 93 +++++++++++++++++++++++++-------- 3 files changed, 98 insertions(+), 21 deletions(-)
include/linux/pageblock-flags.h +9 -0
@@ -20,6 +20,15 @@ enum pageblock_bits { PB_migrate_2, PB_compact_skip,/* If set the block is skipped by compaction */ +/* +* Track actual page contents independent of the intended migratetype. +* Set at allocation time; cleared on full pageblock free or when +* migration confirms no pages of that type remain. +*/ + PB_has_unmovable, + PB_has_reclaimable, + PB_has_movable, + #ifdef CONFIG_MEMORY_ISOLATION/* * Pageblock isolation is represented with a separate bit, so that
mm/compaction.c +17 -0
@@ -867,6 +867,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,bool skip_on_failure = false;unsigned long next_skip_pfn =0 ;bool skip_updated = false; +bool movable_skipped = false;int ret =0 ; cc->migrate_pfn = low_pfn;
@@ -1079,6 +1080,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, folio =page_folio (page); goto isolate_success; } + movable_skipped = true; } goto isolate_fail;
@@ -1246,6 +1248,7 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,lruvec_unlock_irqrestore (locked, flags); locked =NULL ; } + movable_skipped = true;folio_put (folio); isolate_fail:
@@ -1309,6 +1312,20 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,if (!cc->no_set_skip_hint && valid_page && !skip_updated)set_pageblock_skip (valid_page);update_cached_migrate (cc, low_pfn); + +/* +* Full pageblock scanned with no movable pages isolated. +* Only clear PB_has_movable if no movable pages were +* seen at all. If movable pages exist but could not be +* isolated (pinned, writeback, dirty, etc.), leave the +* flag set so a future migration attempt can try again. +*/ +if (!nr_isolated && !movable_skipped && valid_page && +get_pfnblock_bit (valid_page,pageblock_start_pfn (start_pfn), + PB_has_movable)) +clear_pfnblock_bit (valid_page, +pageblock_start_pfn (start_pfn), + PB_has_movable); } trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
mm/page_alloc.c +72 -21
133 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 8/40 mm: page_alloc: superpageblock metadata for 1GB anti-fragmentation
In reply to Rik van RielIntroduce a 1GB (PUD-sized) "superpageblock" data structure to track pageblock composition at a coarser granularity, enabling future steering of unmovable/reclaimable allocations into already-tainted superpageblocks and preserving clean superpageblocks for 1GB hugepage allocation.
Each superpageblock groups SUPERBLOCK_NR_PAGEBLOCKS pageblocks (512 on
x86_64 with 2MB pageblocks) and maintains:
- Counts of pageblocks by migratetype (nr_free, nr_unmovable, nr_reclaimable, nr_movable, nr_reserved)
- A list_head for future organization by fullness category
- Identity (start_pfn, zone pointer)
Superblock counters are maintained by hooking into init_pageblock_migratetype(). Memory holes and firmware-reserved regions are tracked as reserved pageblocks by initializing all slots as reserved during setup and decrementing as init_pageblock_migratetype() claims them.
The superpageblock array is allocated per-zone during boot via memblock. At ~48 bytes per superpageblock (~12KB for a 256GB system), the overhead is negligible.
This is pure bookkeeping with no allocation behavior change.
--- include/linux/mmzone.h | 57 ++++++++++++++++++++++++++ mm/mm_init.c | 90 ++++++++++++++++++++++++++++++++++++++++++ mm/page_alloc.c | 65 ++++++++++++++++++++++++++++++ 3 files changed, 212 insertions(+)
include/linux/mmzone.h +57 -0
@@ -974,6 +974,43 @@ enum zone_type {#define ASYNC_AND_SYNC 2 +/* +* Superpageblock: 1GB (PUD-sized) region for anti-fragmentation tracking. +* +* Groups pageblocks to steer unmovable/reclaimable allocations into +* already-tainted superpageblocks, preserving clean superpageblocks for 1GB +* hugepage allocation. +* +* SUPERPAGEBLOCK_ORDER derived from PUD geometry: +* x86_64: PUD_SHIFT=30, PAGE_SHIFT=12 → order 18 → 1GB +* Each superpageblock contains SUPERPAGEBLOCK_NR_PAGEBLOCKS pageblocks +* (512 on x86_64 with 2MB pageblocks). +*/ +#define SUPERPAGEBLOCK_ORDER (PUD_SHIFT - PAGE_SHIFT) +#define SUPERPAGEBLOCK_NR_PAGES (1UL << SUPERPAGEBLOCK_ORDER) + +/* +* SUPERPAGEBLOCK_NR_PAGEBLOCKS depends on pageblock_order which may be +* variable (CONFIG_HUGETLB_PAGE_SIZE_VARIABLE). +*/ +#define SUPERPAGEBLOCK_NR_PAGEBLOCKS (1UL << (SUPERPAGEBLOCK_ORDER - pageblock_order)) + +struct superpageblock { +/* Pageblock counts by current migratetype */ +u16 nr_free; +u16 nr_unmovable; +u16 nr_reclaimable; +u16 nr_movable; +u16 nr_reserved;/* holes, firmware, etc. */ + +/* For organizing superpageblocks by fullness category */ +struct list_head list; + +/* Identity */ +unsigned long start_pfn; +struct zone *zone; +}; +struct zone {/* Read-mostly fields */
@@ -1016,6 +1053,11 @@ struct zone {struct pageblock_data *pageblock_data;#endif /* CONFIG_SPARSEMEM */ +/* Superpageblock array for 1GB anti-fragmentation tracking */ +struct superpageblock *superpageblocks; +unsigned long nr_superpageblocks; +unsigned long superpageblock_base_pfn;/* 1GB-aligned base */ +/* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */ unsigned long zone_start_pfn;
@@ -1159,6 +1201,21 @@ struct zone {#endif }____cacheline_internodealigned_in_smp ; +static inline struct superpageblock *pfn_to_superpageblock (struct zone *zone, +unsigned long pfn) +{ +unsigned long idx; + +if (!zone->superpageblocks) +return NULL ; + + idx = (pfn - zone->superpageblock_base_pfn) >>SUPERPAGEBLOCK_ORDER ; +if (idx >= zone->nr_superpageblocks) +return NULL ; + +return &zone->superpageblocks[idx]; +} +enum pgdat_flags {PGDAT_WRITEBACK ,/* reclaim scanning has recently found * many pages under writeback
mm/mm_init.c +90 -0
102 lines not on this page · raw message
mm/page_alloc.c +65 -0
83 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 9/40 mm: page_alloc: support superpageblock resize for memory hotplug
In reply to Rik van Rielsetup_superpageblocks() is __init-only and uses memblock_alloc_node(), so hotplugged memory that extends a zone's span has no superpageblock coverage. Pages in those regions would bypass superpageblock steering entirely.
Add resize_zone_superpageblocks() which is called from move_pfn_range_to_zone() after the zone span has been updated. It allocates a new superpageblock array with kvmalloc_node() covering the full zone span, copies existing superpageblocks (fixing up list head pointers), and initializes new superpageblocks for the added range.
Use round-up division for partial pageblock counting to match init_one_superpageblock().
ZONE_DEVICE is excluded since device pages should not participate in anti- fragmentation steering.
--- include/linux/mmzone.h | 1 + mm/internal.h | 4 ++ mm/memory_hotplug.c | 4 ++ mm/mm_init.c | 138 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 147 insertions(+)
include/linux/mmzone.h +1 -0
@@ -1057,6 +1057,7 @@ struct zone {struct superpageblock *superpageblocks;unsigned long nr_superpageblocks;unsigned long superpageblock_base_pfn;/* 1GB-aligned base */ +bool spb_kvmalloced;/* true if from kvmalloc (hotplug) */ /* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */ unsigned long zone_start_pfn;
mm/internal.h +4 -0
@@ -1101,6 +1101,10 @@ void init_cma_reserved_pageblock(struct page *page);#endif /* CONFIG_COMPACTION || CONFIG_CMA */ +#ifdef CONFIG_MEMORY_HOTPLUG +void resize_zone_superpageblocks (struct zone *zone); +#endif +struct cma ;#ifdef CONFIG_CMA
mm/memory_hotplug.c +4 -0
@@ -752,6 +752,10 @@ void move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,resize_zone_range (zone, start_pfn, nr_pages);resize_pgdat_range (pgdat, start_pfn, nr_pages); +/* Grow superpageblock array to cover the new zone span */ +if (!zone_is_zone_device (zone)) +resize_zone_superpageblocks (zone); +/* * Subsection population requires care in pfn_to_online_page(). * Set the taint to enable the slow path detection of
mm/mm_init.c +138 -0
144 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 10/40 mm: page_alloc: add superpageblock fullness lists for allocation steering
In reply to Rik van RielOrganize superpageblocks into bucketed lists by fullness level and taint status to enable efficient allocation steering without sorting.
Five fullness buckets (FULL, 75%, 50%, 25%, ALMOST_EMPTY) track what fraction of a superpageblock's pageblocks are in use. Two categories (CLEAN vs TAINTED) distinguish superpageblocks that contain only free and movable pageblocks from those contaminated with unmovable, reclaimable, or reserved pageblocks. A separate sb_empty list tracks completely free superpageblocks.
Track fully-free pageblocks with a PB_all_free pageblock flag. When buddy coalescing reconstructs a full pageblock, increment nr_free. Type counters are driven by PB_has_* bit transitions, not by migratetype label changes.
For tainted superpageblocks, fullness is based on unmovable + reclaimable pageblock counts rather than total usage, correctly reflecting how full they are with the content types we're trying to concentrate.
Add a debugfs interface at /sys/kernel/debug/superpageblocks.
--- include/linux/mmzone.h | 22 +++ include/linux/pageblock-flags.h | 1 + mm/mm_init.c | 26 ++- mm/page_alloc.c | 295 +++++++++++++++++++++++++++++++- 4 files changed, 339 insertions(+), 5 deletions(-)
include/linux/mmzone.h +22 -0
@@ -995,6 +995,23 @@ enum zone_type {*/ #define SUPERPAGEBLOCK_NR_PAGEBLOCKS (1UL << (SUPERPAGEBLOCK_ORDER - pageblock_order)) +/* Superpageblock fullness buckets (by % of pageblocks in use) */ +enum sb_fullness { +SB_FULL ,/* 100% full, 0 free pageblocks */ +SB_FULL_75 ,/* 75-99% full */ +SB_FULL_50 ,/* 50-74% full */ +SB_FULL_25 ,/* 25-49% full */ +SB_ALMOST_EMPTY ,/* 1-24% full */ + __NR_SB_FULLNESS, +}; + +/* Superpageblock taint categories */ +enum sb_category { +SB_CLEAN ,/* only free + movable pageblocks */ +SB_TAINTED ,/* has unmovable/reclaimable/reserved */ + __NR_SB_CATEGORIES, +}; +struct superpageblock {/* Pageblock counts by current migratetype */ u16 nr_free;
@@ -1002,6 +1019,7 @@ struct superpageblock {u16 nr_reclaimable;u16 nr_movable;u16 nr_reserved;/* holes, firmware, etc. */ +u16 total_pageblocks;/* zone-clipped total */ /* For organizing superpageblocks by fullness category */ struct list_head list;
@@ -1059,6 +1077,10 @@ struct zone {unsigned long superpageblock_base_pfn;/* 1GB-aligned base */ bool spb_kvmalloced;/* true if from kvmalloc (hotplug) */ +/* Superpageblock fullness lists for allocation steering */ +struct list_head spb_empty;/* completely free superpageblocks */ +struct list_head spb_lists[__NR_SB_CATEGORIES][__NR_SB_FULLNESS]; +/* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */ unsigned long zone_start_pfn;
include/linux/pageblock-flags.h +1 -0
@@ -28,6 +28,7 @@ enum pageblock_bits { PB_has_unmovable, PB_has_reclaimable, PB_has_movable, + PB_all_free,/* All pages in pageblock are free in buddy */ #ifdef CONFIG_MEMORY_ISOLATION/*
mm/mm_init.c +23 -3
@@ -1548,7 +1548,17 @@ static void __meminit init_one_superpageblock(struct superpageblock *sb, actual_pbs = (pb_end > pb_start) ? ((pb_end - pb_start + pageblock_nr_pages -1 ) >> pageblock_order) :0 ; + sb->total_pageblocks = actual_pbs; sb->nr_reserved = actual_pbs; +if (actual_pbs) { +/* +* All superpageblocks start as reserved (tainted+full). +* They move to the correct category when the pages +* inside are freed during boot. +*/ +list_add_tail (&sb->list, + &zone->spb_lists[SB_TAINTED ][SB_FULL ]); + } }static void __init setup_superpageblocks (struct zone *zone)
@@ -1558,11 +1568,18 @@ static void __init setup_superpageblocks(struct zone *zone)unsigned long sb_base, nr_superpageblocks;size_t alloc_size;unsigned long i; +int cat, full; zone->superpageblocks =NULL ; zone->nr_superpageblocks =0 ; zone->superpageblock_base_pfn =0 ; +/* Fullness lists steer allocations to preferred superpageblocks */ +INIT_LIST_HEAD (&zone->spb_empty); +for (cat =0 ; cat < __NR_SB_CATEGORIES; cat++) +for (full =0 ; full < __NR_SB_FULLNESS; full++) +INIT_LIST_HEAD (&zone->spb_lists[cat][full]); +if (!zone->spanned_pages)return ;
@@ -1688,8 +1705,9 @@ void __meminit resize_zone_superpageblocks(struct zone *zone) }/* -* Update existing superpageblocks whose nr_reserved may have -* increased due to the zone span growing into them. +* Update existing superpageblocks whose nr_reserved and +* total_pageblocks may have increased due to the zone +* span growing into them. */ if (zone->superpageblocks) { old_offset = (zone->superpageblock_base_pfn - new_sb_base) >>
@@ -1707,8 +1725,10 @@ void __meminit resize_zone_superpageblocks(struct zone *zone) sb->nr_reclaimable + sb->nr_movable + sb->nr_reserved; -if (new_pbs > old_pbs) +if (new_pbs > old_pbs) { sb->nr_reserved += new_pbs - old_pbs; + sb->total_pageblocks = new_pbs; + } } }
mm/page_alloc.c +293 -2
358 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 11/40 mm: page_alloc: steer pageblock stealing to tainted superpageblocks
In reply to Rik van RielWhen the allocator needs to steal a movable pageblock for unmovable or reclaimable allocations, prefer pages from already-tainted superpageblocks. This concentrates contamination in superpageblocks that are already impure, preserving clean superpageblocks for future 1GB hugepage allocations.
In __rmqueue_claim, after finding a candidate page on the free list, check if it belongs to a clean superpageblock. If so, do a bounded scan (SPB_SCAN_LIMIT=8) of the same free list looking for a page from a tainted superpageblock instead. This is a best-effort optimization:
if no tainted alternative is found, the original page is used.
--- mm/page_alloc.c | 100 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 79 insertions(+), 21 deletions(-)
mm/page_alloc.c +79 -21
@@ -2327,6 +2327,9 @@ static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flagsclear_page_pfmemalloc (page); } +/* Bounded scan limit when searching free lists for tainted superpageblock pages */ +#define SPB_SCAN_LIMIT 8 +/* * Go through the free lists for the given migratetype and remove * the smallest available page from the freelists
@@ -2694,6 +2697,7 @@ try_to_claim_block(struct zone *zone, struct page *page, {int free_pages, movable_pages, alike_pages;unsigned long start_pfn; +struct superpageblock *sb;#ifdef CONFIG_COMPACTION struct page *start_page;#endif
@@ -2726,7 +2730,12 @@ try_to_claim_block(struct zone *zone, struct page *page,clear_pfnblock_bit (pb_page, pb_pfn, PB_all_free);superpageblock_pb_now_used (pb_page); } +__spb_set_has_type (pb_page, start_type); } +/* Single list update after all pageblocks processed */ + sb =pfn_to_superpageblock (zone,page_to_pfn (page)); +if (sb) +spb_update_list (sb);del_page_from_free_list (page, zone, current_order, block_type);change_pageblock_range (page, current_order, start_type);
@@ -2771,29 +2780,24 @@ try_to_claim_block(struct zone *zone, struct page *page,set_pageblock_migratetype (pfn_to_page (start_pfn), start_type);#ifdef CONFIG_COMPACTION /* -* Track actual page contents in pageblock flags. -* Mark the pageblock with the type being allocated, and -* if unmovable/reclaimable pages are being placed into a -* pageblock that already has movable pages, queue async -* evacuation of the movable pages. +* Track actual page contents in pageblock flags and +* update superpageblock counters so the SPB moves to +* the correct fullness list for steering. */ start_page =pfn_to_page (start_pfn); -if (start_type ==MIGRATE_UNMOVABLE ) { -set_pfnblock_bit (start_page, start_pfn, - PB_has_unmovable); -if (get_pfnblock_bit (start_page, start_pfn, - PB_has_movable)) -queue_pageblock_evacuate (zone, start_pfn); - }else if (start_type ==MIGRATE_RECLAIMABLE ) { -set_pfnblock_bit (start_page, start_pfn, - PB_has_reclaimable); -if (get_pfnblock_bit (start_page, start_pfn, - PB_has_movable)) -queue_pageblock_evacuate (zone, start_pfn); - }else if (start_type ==MIGRATE_MOVABLE ) { -set_pfnblock_bit (start_page, start_pfn, - PB_has_movable); - } +__spb_set_has_type (start_page, start_type); +if (block_type != start_type) +__spb_set_has_type (start_page, block_type); + + sb =pfn_to_superpageblock (zone, start_pfn); +if (sb) +spb_update_list (sb); + +if ((start_type ==MIGRATE_UNMOVABLE || + start_type ==MIGRATE_RECLAIMABLE ) && +get_pfnblock_bit (start_page, start_pfn, + PB_has_movable)) +queue_pageblock_evacuate (zone, start_pfn);#endif return __rmqueue_smallest (zone, order, start_type); }
@@ -2847,6 +2851,38 @@ __rmqueue_claim(struct zone *zone, int order, int start_migratetype,break ; page =get_page_from_free_area (area, fallback_mt); + +/* +* For unmovable/reclaimable stealing, prefer pages from +* tainted superpageblocks (already contaminated) to keep clean +* superpageblocks clean for future 1GB allocations. +*/ +if (start_migratetype !=MIGRATE_MOVABLE && + zone->superpageblocks && page) { +struct superpageblock *sb; +struct page *alt; +int scanned =0 ; + + sb =pfn_to_superpageblock (zone,page_to_pfn (page)); +if (sb &&spb_get_category (sb) ==SB_CLEAN ) { +list_for_each_entry (alt, + &area->free_list[fallback_mt], + buddy_list) { +struct superpageblock *asb; + +if (++scanned >SPB_SCAN_LIMIT ) +break ; + asb =pfn_to_superpageblock (zone, +page_to_pfn (alt)); +if (asb &&spb_get_category (asb) == +SB_TAINTED ) { + page = alt; +break ; + } + } + } + } + page =try_to_claim_block (zone, page, current_order, order, start_migratetype, fallback_mt, alloc_flags);
@@ -2867,6 +2903,7 @@ __rmqueue_claim(struct zone *zone, int order, int start_migratetype, static __always_inline struct page *__rmqueue_steal (struct zone *zone,int order,int start_migratetype) { +struct superpageblock *sb;struct free_area *area;int current_order;struct page *page;
@@ -2881,6 +2918,27 @@ __rmqueue_steal(struct zone *zone, int order, int start_migratetype) page =get_page_from_free_area (area, fallback_mt);page_del_and_expand (zone, page, order, current_order, fallback_mt); + +/* +* page_del_and_expand recorded PB_has_<fallback_mt> for the +* source free list type. Also record the actual allocation +* type so evacuation and defrag can find these pages. +* +* For example, a MOVABLE allocation stealing from an +* UNMOVABLE free list must set PB_has_movable so the +* pageblock is visible to evacuate_pageblock() and +* spb_defrag_tainted(). __spb_set_has_type is idempotent: +* it only increments the SPB counter on the 0->1 bit +* transition. +*/ +if (fallback_mt != start_migratetype) { +__spb_set_has_type (page, start_migratetype); + sb =pfn_to_superpageblock (zone, +page_to_pfn (page)); +if (sb) +spb_update_list (sb); + } +trace_mm_page_alloc_extfrag (page, order, current_order, start_migratetype, fallback_mt);return page;
Signature · 1 line
2.54.0
RFC PATCH 12/40 mm: page_alloc: steer movable allocations to fullest clean superpageblocks
In reply to Rik van RielWhen refilling PCP with whole pageblocks for movable allocations, prefer pageblocks from the fullest clean (only free + movable) superpageblock. This packs movable allocations into already-partial superpageblocks, preserving empty superpageblocks for potential 1GB hugepage allocation.
Add sb_preferred_for_movable() which walks the clean superpageblock lists from SB_FULL toward SB_ALMOST_EMPTY to find the fullest clean superpageblock with available free pageblocks. Add __rmqueue_from_sb() which scans the buddy free list for a page within a specific superpageblock's PFN range, with a bounded scan limit (8 entries) to avoid excessive latency.
Hook into rmqueue_bulk() phase 1 (whole pageblock grab for PCP refill) to try the preferred superpageblock before falling back to the normal __rmqueue() path. This is the primary steering point for movable allocations without per-superpageblock free lists.
Also fix an ALLOC_NOFRAGMENT propagation oversight in alloc_pages_bulk_noprof(): the bulk allocator's preferred_zoneref is computed locally, so it must also call alloc_flags_nofragment() to match the protection that the single-page fastpath gets via prepare_alloc_pages(). Without this, bulk folio refills for the page cache could taint clean SPBs that the single-page path would have left alone.
--- mm/page_alloc.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 3 deletions(-)
mm/page_alloc.c +86 -3
@@ -2330,6 +2330,73 @@ static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags/* Bounded scan limit when searching free lists for tainted superpageblock pages */ #define SPB_SCAN_LIMIT 8 +/** +* sb_preferred_for_movable - Find the fullest clean superpageblock for movable +* @zone: zone to search +* +* Walk spb_lists[CLEAN] from nearly full toward emptiest -- pack movable +* allocations into already-partial superpageblocks before starting new ones. +* Skip SB_FULL since those have no free pageblocks. +* Returns NULL if no suitable superpageblock found. +*/ +static struct superpageblock *sb_preferred_for_movable (struct zone *zone) +{ +int full; +struct superpageblock *sb; + +for (full =SB_FULL_75 ; full < __NR_SB_FULLNESS; full++) { +list_for_each_entry (sb, &zone->spb_lists[SB_CLEAN ][full], list) { +if (sb->nr_free) +return sb; + } + } +/* Fall back to empty superpageblocks -- no clean partials available */ +return NULL ; +} + +/** +* __rmqueue_from_sb - Try to allocate a page from a specific superpageblock +* @zone: zone to allocate from +* @order: allocation order +* @migratetype: type to allocate +* @sb: preferred superpageblock +* +* Scan the free list at the given order for a page within the superpageblock's +* PFN range. Bounded scan to avoid excessive latency. Returns NULL if +* no suitable page found. +*/ +static struct page *__rmqueue_from_sb (struct zone *zone,unsigned int order, +int migratetype,struct superpageblock *sb) +{ +unsigned int current_order; +unsigned long sb_start = sb->start_pfn; +unsigned long sb_end = sb_start + (1UL <<SUPERPAGEBLOCK_ORDER ); +struct free_area *area; +struct page *page; +int scanned; + +for (current_order = order; current_order <NR_PAGE_ORDERS ; + ++current_order) { + area = &zone->free_area[current_order]; + scanned =0 ; + +list_for_each_entry (page, &area->free_list[migratetype], + buddy_list) { +unsigned long pfn =page_to_pfn (page); + +if (pfn >= sb_start && pfn < sb_end) { +page_del_and_expand (zone, page, order, + current_order, + migratetype); +return page; + } +if (++scanned >=SPB_SCAN_LIMIT ) +break ; + } + } +return NULL ; +} +/* * Go through the free lists for the given migratetype and remove * the smallest available page from the freelists
@@ -3119,12 +3186,26 @@ static bool rmqueue_bulk(struct zone *zone, unsigned int order,* small zones, pages_needed can be less than a whole * pageblock; skip to smaller blocks or individual pages to * avoid overshooting the PCP high watermark. +* +* For movable allocations, prefer pageblocks from the +* fullest clean superpageblock to pack allocations and +* preserve empty superpageblocks for 1GB hugepages. */ while (refilled + pageblock_nr_pages <= pages_needed) { -struct page *page; +struct page *page =NULL ; - page =__rmqueue (zone, pageblock_order, - migratetype, alloc_flags, &rmqm); +if (migratetype ==MIGRATE_MOVABLE ) { +struct superpageblock *sb; + + sb =sb_preferred_for_movable (zone); +if (sb) + page =__rmqueue_from_sb (zone, pageblock_order, + migratetype, sb); + } +if (!page) + page =__rmqueue (zone, pageblock_order, + migratetype, + alloc_flags, &rmqm);if (!page)break ;
@@ -5843,6 +5924,8 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, goto out; gfp = alloc_gfp; + alloc_flags |=alloc_flags_nofragment (zonelist_zone (ac.preferred_zoneref), gfp); +/* Find an allowed local zone that meets the low watermark. */ z = ac.preferred_zoneref; for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
Signature · 1 line
2.54.0
RFC PATCH 13/40 mm: page_alloc: extract claim_whole_block from try_to_claim_block
In reply to Rik van RielExtract the whole-pageblock claiming logic from try_to_claim_block() into a standalone claim_whole_block() function. This handles the PB_all_free → used transition, pageblock migratetype change, and block splitting for orders >= pageblock_order.
Pure refactoring, no functional change. Prepares for reuse of this logic in the per-superpageblock free lists patch.
--- mm/page_alloc.c | 89 ++++++++++++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 34 deletions(-)
mm/page_alloc.c +55 -34
@@ -2750,6 +2750,57 @@ int find_suitable_fallback(struct free_area *area, unsigned int order,return -1 ; } +/* +* claim_whole_block - claim a free block (>= pageblock_order) for a new type +* @zone: zone containing the page +* @page: free page to claim +* @current_order: order of the free page +* @order: requested allocation order +* @new_type: migratetype to assign +* @old_type: current migratetype of the block (for free list removal) +* +* Handle the PB_all_free → used transition, change the pageblock +* migratetype, split the block down to @order, and return the page. +*/ +static struct page * +claim_whole_block (struct zone *zone,struct page *page, +int current_order,int order,int new_type,int old_type) +{ +struct superpageblock *sb; +unsigned int nr_added; +unsigned long pb_pfn; + +VM_WARN_ON_ONCE (current_order < order); + +/* +* Clear PB_all_free for pageblocks being claimed. +* This path bypasses page_del_and_expand(), so we +* must handle the free→used transition here. +*/ +for (pb_pfn =page_to_pfn (page); + pb_pfn <page_to_pfn (page) + (1 << current_order); + pb_pfn += pageblock_nr_pages) { +struct page *pb_page =pfn_to_page (pb_pfn); + +if (get_pfnblock_bit (pb_page, pb_pfn, PB_all_free)) { +clear_pfnblock_bit (pb_page, pb_pfn, PB_all_free); +superpageblock_pb_now_used (pb_page); + } +__spb_set_has_type (pb_page, new_type); + } + +del_page_from_free_list (page, zone, current_order, old_type); +change_pageblock_range (page, current_order, new_type); + nr_added =expand (zone, page, order, current_order, new_type); +account_freepages (zone, nr_added, new_type); + +/* Single list update after all pageblocks processed */ + sb =pfn_to_superpageblock (zone,page_to_pfn (page)); +if (sb) +spb_update_list (sb); +return page; +} +/* * This function implements actual block claiming behaviour. If order is large * enough, we can claim the whole pageblock for the requested migratetype. If
@@ -2764,9 +2815,9 @@ try_to_claim_block(struct zone *zone, struct page *page, {int free_pages, movable_pages, alike_pages;unsigned long start_pfn; -struct superpageblock *sb;#ifdef CONFIG_COMPACTION struct page *start_page; +struct superpageblock *sb;#endif /*
@@ -2777,39 +2828,9 @@ try_to_claim_block(struct zone *zone, struct page *page,return NULL ;/* Take ownership for orders >= pageblock_order */ -if (current_order >= pageblock_order) { -unsigned int nr_added; -unsigned long pb_pfn; - -/* -* Clear PB_all_free for pageblocks being claimed. -* This path bypasses page_del_and_expand(), so we -* must handle the free→used transition here. -* Use block_type (the original migratetype) because -* that's what was decremented when PB_all_free was set. -*/ -for (pb_pfn =page_to_pfn (page); - pb_pfn <page_to_pfn (page) + (1 << current_order); - pb_pfn += pageblock_nr_pages) { -struct page *pb_page =pfn_to_page (pb_pfn); - -if (get_pfnblock_bit (pb_page, pb_pfn, PB_all_free)) { -clear_pfnblock_bit (pb_page, pb_pfn, PB_all_free); -superpageblock_pb_now_used (pb_page); - } -__spb_set_has_type (pb_page, start_type); - } -/* Single list update after all pageblocks processed */ - sb =pfn_to_superpageblock (zone,page_to_pfn (page)); -if (sb) -spb_update_list (sb); - -del_page_from_free_list (page, zone, current_order, block_type); -change_pageblock_range (page, current_order, start_type); - nr_added =expand (zone, page, order, current_order, start_type); -account_freepages (zone, nr_added, start_type); -return page; - } +if (current_order >= pageblock_order) +return claim_whole_block (zone, page, current_order, order, + start_type, block_type);/* moving whole block can fail due to zone boundary conditions */ if (!prep_move_freepages_block(zone, page, &start_pfn, &free_pages,
Signature · 1 line
2.54.0
RFC PATCH 14/40 mm: page_alloc: add per-superpageblock free lists
In reply to Rik van RielPer-superpageblock free lists keep allocation steering effective at every
order: all pages belonging to a superpageblock are tracked on its own free_area[NR_PAGE_ORDERS], not on the zone-level free_area. This lets __rmqueue_smallest target a specific SPB by category/fullness without walking the whole zone.
Sub-pageblock-order frees route to the containing SPB's free list via __free_one_page; whole-pageblock and higher orders likewise. PCP refill, buddy coalescing, and migratetype steering all consult the per-SPB free_area.
Memory-hotplug correctness. Once the resize loop in resize_zone_superpageblocks() may be invoked on a previously-empty zone (memoryless NUMA node receiving its first online memory, CXL hot-add into a zone with no prior pages), two latent bugs surface:
- The SPB list heads (zone->spb_empty and the spb_lists[cat][full] matrix) are initialized only by setup_superpageblocks(), which is __init and runs only at boot. Hot-add into a previously-empty zone invokes init_one_superpageblock() with zero-initialized list_heads, and the inlined list_add_tail() NULL-derefs walking ->next->prev. Factor list-head init out of setup_superpageblocks() into init_zone_spb_lists(), call it from resize_zone_superpageblocks() on the first-time path (zone->superpageblocks == NULL); subsequent resizes skip it.
- The resize loop copies struct superpageblock entries to a newly kvmalloc()'d array but does not fix up the embedded free_area[order].free_list[mt] list_heads. Pages on those lists have buddy_list.prev/next pointing into the *old* array's list heads, so as soon as the swap takes effect, __rmqueue_smallest walks pointers into freed memory. Extend the per-SPB list_replace pass to walk all NR_PAGE_ORDERS * MIGRATE_TYPES free lists too.
The same critical section that copies struct contents and fixes up list heads must run under zone->lock to prevent a concurrent allocator from observing partial state; take the lock around the copy+fixup+swap.
--- include/linux/mmzone.h | 10 + mm/compaction.c | 36 +- mm/internal.h | 10 + mm/mm_init.c | 146 +++++-- mm/page_alloc.c | 853 ++++++++++++++++++++++++++++++++--------- mm/vmstat.c | 66 ++-- 6 files changed, 883 insertions(+), 238 deletions(-)
include/linux/mmzone.h +10 -0
@@ -1021,9 +1021,19 @@ struct superpageblock {u16 nr_reserved;/* holes, firmware, etc. */ u16 total_pageblocks;/* zone-clipped total */ +/* Total free pages across all per-superpageblock free lists */ +unsigned long nr_free_pages; +/* For organizing superpageblocks by fullness category */ struct list_head list; +/* +* Per-superpageblock free lists for all buddy orders. +* All pages belonging to this superpageblock are tracked here, +* keeping allocation steering effective at every order. +*/ +struct free_area free_area[NR_PAGE_ORDERS ]; +/* Identity */ unsigned long start_pfn;struct zone *zone;
mm/compaction.c +30 -6
@@ -979,6 +979,12 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, low_pfn += (1UL << order) -1 ; nr_scanned += (1UL << order) -1 ; } +/* +* Skipped a movable page; clearing +* PB_has_movable here would orphan SPB type +* counters (debugfs invariant 1). +*/ + movable_skipped = true; goto isolate_fail; }/* for alloc_contig case */
@@ -1058,6 +1064,12 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, low_pfn += (1UL << order) -1 ; nr_scanned += (1UL << order) -1 ; } +/* +* Skipped a movable compound page; clearing +* PB_has_movable here would orphan SPB type +* counters (debugfs invariant 1). +*/ + movable_skipped = true; goto isolate_fail; } }
@@ -1083,6 +1095,12 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, movable_skipped = true; } +/* +* Non-LRU non-movable_ops page: still occupies the +* pageblock, so clearing PB_has_movable here would +* orphan SPB type counters (debugfs invariant 1). +*/ + movable_skipped = true; goto isolate_fail; }
@@ -1320,12 +1338,9 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,* isolated (pinned, writeback, dirty, etc.), leave the * flag set so a future migration attempt can try again. */ -if (!nr_isolated && !movable_skipped && valid_page && -get_pfnblock_bit (valid_page,pageblock_start_pfn (start_pfn), - PB_has_movable)) -clear_pfnblock_bit (valid_page, -pageblock_start_pfn (start_pfn), - PB_has_movable); +if (!nr_isolated && !movable_skipped && valid_page) +superpageblock_clear_has_movable (cc->zone, + valid_page); } trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
@@ -1873,6 +1888,15 @@ static struct folio *compaction_alloc_noprof(struct folio *src, unsigned long daprep_compound_page (&dst->page, order); cc->nr_freepages -=1 << order; cc->nr_migratepages -=1 << order; + +/* +* Compaction isolates free pages via __isolate_free_page, which +* bypasses page_del_and_expand and its PB_has_* tracking. The +* destination will hold movable pages after migration, so mark +* PB_has_movable on the destination pageblock now. +*/ +superpageblock_set_has_movable (cc->zone, &dst->page); +return page_rmappable_folio (&dst->page); }
mm/internal.h +10 -0
@@ -1101,6 +1101,16 @@ void init_cma_reserved_pageblock(struct page *page);#endif /* CONFIG_COMPACTION || CONFIG_CMA */ +#ifdef CONFIG_COMPACTION +void superpageblock_clear_has_movable (struct zone *zone,struct page *page); +void superpageblock_set_has_movable (struct zone *zone,struct page *page); +#else +static inline void superpageblock_clear_has_movable (struct zone *zone, +struct page *page) {} +static inline void superpageblock_set_has_movable (struct zone *zone, +struct page *page) {} +#endif +#ifdef CONFIG_MEMORY_HOTPLUG void resize_zone_superpageblocks (struct zone *zone);#endif
mm/mm_init.c +113 -33
223 lines not on this page · raw message
mm/page_alloc.c +682 -171
1,087 lines not on this page · raw message
mm/vmstat.c +38 -28
79 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 15/40 mm: page_alloc: add background superpageblock defragmentation worker
In reply to Rik van RielAdd an event-driven background worker that evacuates movable pages from tainted superpageblocks when free space runs low. Each super- pageblock has its own work_struct, so defrag targets the specific superpageblock that needs it rather than scanning the entire system.
Defrag is triggered from sb_update_list() when a tainted super- pageblock drops below threshold: 1 or fewer free pageblocks, or less than 2 pageblocks worth of free pages. The worker evacuates movable pageblocks until free space recovers: at least 2 free pageblocks or 3 pageblocks worth of free pages, or no movable pages remain. Clean superpageblocks (only free + movable) are never defragged; super- pageblocks with no movable pages are skipped.
The worker calls evacuate_pageblock() directly from within its own work_struct, so the older per-pageblock evacuate plumbing (queue_pageblock_evacuate, evacuate_item, evacuate_pool, evacuate_freelist, evacuate_item_alloc/free, evacuate_work_fn, evacuate_irq_work_fn, pgdat->evacuate_pending, pgdat->evacuate_irq_work, and their per-pgdat init in pageblock_evacuate_init()) is no longer used and is dropped, along with its sole remaining call site in try_to_claim_block().
Memory-hotplug correctness: this commit introduces the per-SPB defrag_work / defrag_irq_work fields. The resize loop in resize_zone_superpageblocks() already runs init_zone_spb_lists() on the first-time path and rewires per-SPB list heads after the kvmalloc copy (from the previous commit), but the defrag work_structs need their own init both for *copied* SPBs (the memcpy leaves them with function pointers that reference the old array's per-SPB storage) and for *newly allocated* SPBs (boot-time init via the pageblock_evacuate_init late_initcall only walks SPBs that exist at boot, so hot-added SPBs would otherwise have zero-initialized defrag_work and crash on first defrag attempt). Call init_superpageblock_defrag(sb) right after init_one_superpageblock(sb) in the new-SPB loop, and add it to the copied-SPB fixup loop as well.
--- include/linux/mmzone.h | 19 ++- mm/internal.h | 2 + mm/mm_init.c | 11 ++ mm/page_alloc.c | 325 +++++++++++++++++++++++++++++------------ 4 files changed, 259 insertions(+), 98 deletions(-)
include/linux/mmzone.h +17 -2
@@ -1034,6 +1034,23 @@ struct superpageblock {*/ struct free_area free_area[NR_PAGE_ORDERS ]; +#ifdef CONFIG_COMPACTION +/* Background defragmentation work for this superpageblock */ +struct work_struct defrag_work; +struct irq_work defrag_irq_work; +bool defrag_active; +/* +* Back-off state after a no-op defrag pass: defer the next attempt +* until either nr_free_pages has grown by at least pageblock_nr_pages +* or a cooldown elapses, so allocator hot paths cannot re-arm +* defrag_work many times per second on an SB that cannot make progress. +* defrag_last_no_progress_jiffies == 0 means the previous pass made +* progress (or no pass has run yet). +*/ +unsigned long defrag_last_no_progress_jiffies; +unsigned long defrag_last_no_progress_pages; +#endif +/* Identity */ unsigned long start_pfn;struct zone *zone;
@@ -1632,8 +1649,6 @@ typedef struct pglist_data {struct task_struct *kcompactd;bool proactive_compact_trigger;struct workqueue_struct *evacuate_wq; -struct llist_head evacuate_pending; -struct irq_work evacuate_irq_work;#endif /* * This is a per-node reserve of pages that are not available
mm/internal.h +2 -0
@@ -1102,9 +1102,11 @@ void init_cma_reserved_pageblock(struct page *page);#endif /* CONFIG_COMPACTION || CONFIG_CMA */ #ifdef CONFIG_COMPACTION +void init_superpageblock_defrag (struct superpageblock *sb);void superpageblock_clear_has_movable (struct zone *zone,struct page *page);void superpageblock_set_has_movable (struct zone *zone,struct page *page);#else +static inline void init_superpageblock_defrag (struct superpageblock *sb) {}static inline void superpageblock_clear_has_movable (struct zone *zone,struct page *page) {} static inline void superpageblock_set_has_movable(struct zone *zone,
mm/mm_init.c +11 -0
@@ -1726,6 +1726,14 @@ void __meminit resize_zone_superpageblocks(struct zone *zone)init_one_superpageblock (sb, zone, new_sb_base + (i <<SUPERPAGEBLOCK_ORDER ), zone_start, zone_end); +/* +* Boot-time defrag work init in pageblock_evacuate_init() +* is a late_initcall and only walks SPBs that exist at +* that point. Newly hot-added SPBs need their work structs +* initialized here, mirroring the reinit loop above for +* copied SPBs. +*/ +init_superpageblock_defrag (sb); }/*
@@ -1779,6 +1787,9 @@ void __meminit resize_zone_superpageblocks(struct zone *zone)list_replace (old_list, new_list); } } + +/* Reinitialize defrag work structs (contain stale pointers) */ +init_superpageblock_defrag (sb); } }
mm/page_alloc.c +229 -96
414 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 16/40 mm: compaction: walk per-superpageblock free lists for migration targets
In reply to Rik van RielFree pages live on per-SPB free lists
rather than zone-level free_lists. Standard compaction's free-page scanner needs to walk the per-SPB free lists to find migration targets; without this, kcompactd would see "nothing free" even when SPBs hold plenty of order-9 buddies.
Also wire superpageblock_set_has_movable() and the corresponding clear calls into the migration-source-isolation and free-page-isolation paths, so pageblock movability bookkeeping stays correct as compaction shuffles contents around.
Fix the PB_has_movable check for zones whose start_pfn is not aligned to pageblock_order (DMA32 with reserved memory at the bottom).
This is the compaction-side infrastructure for SPB-aware standard compaction. Subsequent commits add the predicates that let kcompactd skip useless tainted SPBs.
--- include/linux/mmzone.h | 1 + mm/compaction.c | 337 ++++++++++++++++++++++++++++------------- mm/page_alloc.c | 135 ++++++++++++----- 3 files changed, 330 insertions(+), 143 deletions(-)
include/linux/mmzone.h +1 -0
@@ -1039,6 +1039,7 @@ struct superpageblock {struct work_struct defrag_work;struct irq_work defrag_irq_work;bool defrag_active; +unsigned long defrag_cursor;/* * Back-off state after a no-op defrag pass: defer the next attempt * until either nr_free_pages has grown by at least pageblock_nr_pages
mm/compaction.c +231 -106
470 lines not on this page · raw message
mm/page_alloc.c +98 -37
209 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 17/40 mm: page_alloc: superpageblock-aware contiguous and higher order allocation
In reply to Rik van RielAdd superpageblock-aware contiguous page allocation that leverages SPB metadata to find ranges of clean (all-free) superpageblocks, instead of scanning all memory with alloc_contig_range(). The SPB metadata identifies exactly which 1GB regions have only free pages, making CMA and large contiguous allocations more targeted.
Track contiguous allocations in superpageblock metadata by marking fully- covered SPBs with contig_allocated, moving them to the spb_isolated list so they don't participate in allocation steering. Fix the iteration to use ALIGN(start, spb_pages) to correctly handle non-aligned allocation boundaries.
Hook superpageblock-aware allocation into __alloc_pages_direct_compact() for THP/mTHP and high-order unmovable/reclaimable allocations. For movable allocations at pageblock_order or above, try sb_try_alloc_contig() first. For unmovable/reclaimable, evacuate movable pages from tainted superpageblocks to create buddy coalescing opportunities. Both paths fall through to traditional compaction if the SPB approach fails.
--- include/linux/mmzone.h | 2 + mm/page_alloc.c | 484 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 479 insertions(+), 7 deletions(-)
include/linux/mmzone.h +2 -0
@@ -1020,6 +1020,7 @@ struct superpageblock {u16 nr_movable;u16 nr_reserved;/* holes, firmware, etc. */ u16 total_pageblocks;/* zone-clipped total */ +bool contig_allocated;/* all pages held by contig alloc */ /* Total free pages across all per-superpageblock free lists */ unsigned long nr_free_pages;
@@ -1107,6 +1108,7 @@ struct zone {/* Superpageblock fullness lists for allocation steering */ struct list_head spb_empty;/* completely free superpageblocks */ +struct list_head spb_isolated;/* fully isolated (1GB contig alloc) */ struct list_head spb_lists[__NR_SB_CATEGORIES][__NR_SB_FULLNESS];/* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */
mm/page_alloc.c +477 -7
572 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 18/40 mm: page_alloc: prevent atomic allocations from tainting clean SPBs
In reply to Rik van RielNon-DIRECT_RECLAIM (atomic) allocations that fail with ALLOC_NOFRAGMENT previously dropped the flag entirely and retried, allowing them to taint clean superpageblocks. This was the primary source of taint spreading observed on production systems.
Stage the relaxation in three steps that keep atomic allocations inside tainted SPBs as long as possible:
1. Extend Pass 2 in __rmqueue_smallest with a sub-pageblock phase (Pass 2b). Pass 2 only finds whole free pageblocks (>= pageblock order) in tainted SPBs. Pass 2b searches for sub-pageblock-order free blocks and uses try_to_claim_block() to claim a pageblock that has enough compatible pages. This finds pages in tainted SPBs that have fragmented free space but no whole free pageblocks.
2. Add an ALLOC_NOFRAG_TAINTED_OK intermediate flag. Instead of going directly from ALLOC_NOFRAGMENT to no protection, atomic allocations first retry with ALLOC_NOFRAG_TAINTED_OK, which allows __rmqueue_steal to search tainted SPBs only. Clean and empty SPBs remain protected. Only if steal from tainted SPBs also fails is ALLOC_NOFRAGMENT fully dropped as a last resort.
3. Bypass the pageblock compatibility threshold inside try_to_claim_block() when the call originates from the tainted-SPB walk in Pass 2b. The
free_pages + alike_pages >= 1 << (pageblock_order - 1) gate was designed to prevent the cross-fragment-fallback path from spreading mixing into clean SPBs; inside an already-tainted SPB the fragmentation has already been accepted, and the threshold rejects the typical fragmented-MOVABLE-pageblock case Pass 2b is meant to reclaim. Without the bypass Pass 2b would be largely a no-op.
For callers that pass __GFP_NORETRY, the relaxation sequence is wrong in principle. The NORETRY contract is "I have a fallback; don't go to extreme lengths." Network skb_page_frag_refill, slab high-order allocations, and similar hot-path callers use NORETRY exactly so the allocator can return NULL and let their own fallback (smaller frag, lower-order slab, etc.) take over. Tainting a clean superpageblock to satisfy such a request is a lasting cost -- the SPB stays tainted for the remainder of the workload's lifetime, blocking 1 GiB hugepage allocation from that region -- that outlives the single allocation that triggered it. Skip the relaxation steps for NORETRY callers and return NULL immediately; their fallback path absorbs the failure cleanly.
Observed on a 250 GB system running the page-superblock series:
an atomic order-3 alloc from swapper context (PCP refill, gfp=0x152820 = __GFP_HIGH | __GFP_KSWAPD_RECLAIM | __GFP_NOWARN | __GFP_NORETRY | __GFP_COMP | __GFP_HARDWALL) tainted a fresh clean SPB at boot+~90 min despite ALLOC_NOFRAGMENT being set, because the atomic-retry path stripped the flag. The caller had a NORETRY fallback ready; the taint was gratuitous.
--- mm/internal.h | 1 + mm/page_alloc.c | 120 +++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 110 insertions(+), 11 deletions(-)
mm/internal.h +1 -0
@@ -1511,6 +1511,7 @@ unsigned int reclaim_clean_pages_from_list(struct zone *zone,#define ALLOC_HIGHATOMIC 0x200/* Allows access to MIGRATE_HIGHATOMIC */ #define ALLOC_TRYLOCK 0x400/* Only use spin_trylock in allocation path */ #define ALLOC_KSWAPD 0x800/* allow waking of kswapd, __GFP_KSWAPD_RECLAIM set */ +#define ALLOC_NOFRAG_TAINTED_OK 0x1000/* NOFRAGMENT, but allow steal from tainted SPBs */ /* Flags that allow allocations below the min watermark. */ #define ALLOC_RESERVES (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM)
mm/page_alloc.c +109 -11
189 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 19/40 mm: page_alloc: aggressively pack non-movable allocs in tainted SPBs on large systems
In reply to Rik van RielOn systems with many superpageblocks, sub-pageblock MOVABLE fragments within already-tainted SPBs were being skipped by __rmqueue_claim() due to the ALLOC_NOFRAGMENT pageblock_order floor. This caused the allocator to fall through to clean SPBs, tainting them unnecessarily.
Introduce SPB_AGGRESSIVE_THRESHOLD: on systems with more than 8 superpageblocks, relax the min_order floor for the preferred category (tainted SPBs) so non-movable allocations consume free space there at any granularity. On small systems, preserve the pageblock_order floor to protect MOVABLE capacity within tainted SPBs.
--- mm/page_alloc.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 2 deletions(-)
mm/page_alloc.c +68 -2
@@ -2659,6 +2659,24 @@ static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags*/ #define SPB_TAINTED_RESERVE 4 +/* +* On systems with many superpageblocks, we can afford to "write off" +* tainted superpageblocks by aggressively packing unmovable/reclaimable +* allocations into them -- even sub-pageblock fragments -- to keep clean +* superpageblocks clean for future 1GB hugepage and contiguous allocations. +* +* On small systems (few superpageblocks), each SPB represents a large +* fraction of total memory. Aggressively claiming sub-pageblock movable +* fragments from tainted SPBs would destroy MOVABLE capacity that the +* system can't afford to lose, with little benefit since there are too +* few SPBs to meaningfully separate movable from unmovable anyway. +* +* This threshold controls the crossover: above it, prefer concentrating +* non-movable allocations in tainted SPBs at any granularity; below it, +* only claim whole free pageblocks from tainted SPBs. +*/ +#define SPB_AGGRESSIVE_THRESHOLD 8 +/** * sb_preferred_for_movable - Find the fullest clean superpageblock for movable * @zone: zone to search
@@ -3585,6 +3603,7 @@ __rmqueue_claim(struct zone *zone, int order, int start_migratetype, {int current_order;int min_order = order; +int nofrag_min_order = order;struct page *page;int fallback_mt;static const unsigned int cat_search[] = {
@@ -3598,9 +3617,18 @@ __rmqueue_claim(struct zone *zone, int order, int start_migratetype,* Do not steal pages from freelists belonging to other pageblocks * i.e. orders < pageblock_order. If there are no local zones free, * the zonelists will be reiterated without ALLOC_NOFRAGMENT. +* +* Only apply this restriction to empty and clean superpageblocks. +* Claiming within already-tainted superpageblocks does not cause +* new fragmentation, and skipping them wastes free space that +* could prevent tainting clean superpageblocks. +* +* When ALLOC_NOFRAGMENT is set, skip empty and clean superpageblocks +* entirely to avoid tainting them. The slowpath will try reclaim and +* compaction first, and only drop ALLOC_NOFRAGMENT as a last resort. */ if (order < pageblock_order && alloc_flags &ALLOC_NOFRAGMENT ) - min_order = pageblock_order; + nofrag_min_order = pageblock_order;/* * Find the largest available free page in a fallback migratetype.
@@ -3610,6 +3638,31 @@ __rmqueue_claim(struct zone *zone, int order, int start_migratetype, * ones. */ for (c = 0; c < ARRAY_SIZE(cat_search); c++) { + /* + * When avoiding fragmentation, do not search clean/empty + * superpageblocks for fallback pages. Tainting a clean SPB + * is the worst outcome -- better to fail and let the slowpath + * try reclaim and compaction in already-tainted SPBs first. + */ + if ((alloc_flags & ALLOC_NOFRAGMENT) && + cat_search[c] != SB_SEARCH_PREFERRED) + continue; + + /* + * For the preferred category (tainted SPBs for non-movable), + * search all orders down to the allocation order on systems + * with enough superpageblocks that we can afford to write off + * tainted ones. These SPBs are already tainted, so sub-pageblock + * stealing doesn't cause additional fragmentation. + * + * On small systems, keep the pageblock_order floor to preserve + * MOVABLE capacity within tainted SPBs -- see comment at + * SPB_AGGRESSIVE_THRESHOLD. + */ + min_order = (cat_search[c] == SB_SEARCH_PREFERRED && + zone->nr_superpageblocks > SPB_AGGRESSIVE_THRESHOLD) ? + order : nofrag_min_order; + for (current_order = MAX_PAGE_ORDER; current_order >= min_order; --current_order) { if (!should_try_claim_block(current_order,
@@ -3881,8 +3934,18 @@ static bool rmqueue_bulk(struct zone *zone, unsigned int order,* For movable allocations, prefer pageblocks from the * fullest clean superpageblock to pack allocations and * preserve empty superpageblocks for 1GB hugepages. +* +* For non-movable allocations, force ALLOC_NOFRAGMENT so +* __rmqueue cannot steal a whole pageblock out of a clean +* SPB. Stealing is the worst possible outcome for a bulk +* refill: a single network or slab burst can taint dozens +* of clean pageblocks. Phase 2 will adopt sub-pageblock +* fragments from tainted SPBs before Phase 3 falls back to +* the original alloc_flags (which may eventually steal at +* the requested order, a much smaller fragmentation event). */ while (refilled + pageblock_nr_pages <= pages_needed) { +unsigned int p1_alloc_flags = alloc_flags;struct page *page =NULL ;if (migratetype ==MIGRATE_MOVABLE ) {
@@ -3892,11 +3955,14 @@ static bool rmqueue_bulk(struct zone *zone, unsigned int order,if (sb) page =__rmqueue_from_sb (zone, pageblock_order, migratetype, sb); + }else if (!is_migrate_cma (migratetype)) { + p1_alloc_flags = (p1_alloc_flags |ALLOC_NOFRAGMENT ) & + ~ALLOC_NOFRAG_TAINTED_OK ; }if (!page) page =__rmqueue (zone, pageblock_order, migratetype, - alloc_flags, &rmqm); + p1_alloc_flags, &rmqm);if (!page)break ;
Signature · 1 line
2.54.0
RFC PATCH 20/40 mm: page_alloc: prefer reclaim over tainting clean superpageblocks
In reply to Rik van RielWhen the allocator needs pages for unmovable or reclaimable allocations and tainted superpageblocks are exhausted, it currently falls through to clean superpageblocks immediately, permanently tainting them. This defeats the purpose of superpageblock anti-fragmentation.
Restructure the allocation fallback cascade to try reclaim and compaction before tainting clean superpageblocks:
1. Reorder __rmqueue_smallest to search each preferred SPB completely before moving to the next source. Within each preferred SPB, try whole-pageblock allocations first (for PCP buddy optimization), then fall back to sub-pageblock allocations. This ensures that sub-pageblock free pages in existing tainted SPBs are used before tainting empty or clean SPBs. The pass order is:
- Preferred SPBs: whole pageblock first, then sub-pageblock
- Whole pageblock inline claim from tainted SPBs (non-movable only)
- Whole pageblock from empty SPBs
- Fallback to non-preferred SPBs
2. Preserve ALLOC_NOFRAGMENT through the slowpath by calling alloc_flags_nofragment() after gfp_to_alloc_flags(). Previously the slowpath only set NOFRAGMENT for defrag_mode, losing the SPB protection that the fastpath established.
3. After reclaim and compaction have both been tried and failed, drop ALLOC_NOFRAGMENT unconditionally as a last resort before OOM. Previously this was gated on defrag_mode.
Testing shows that with this change, clean superpageblocks maintain unmov=0 throughout a heavy mixed workload (swap pressure, filesystem metadata, anonymous memory cycling, compaction, hugepage allocation), where previously 2-3 additional SPBs would become tainted with 7-8 unmovable pageblocks each.
--- mm/page_alloc.c | 74 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 13 deletions(-)
mm/page_alloc.c +61 -13
@@ -2781,11 +2781,23 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,* concentrate non-movable allocations into fewer superpageblocks. * For movable, prefer clean superpageblocks to keep them homogeneous. * -* Search empty superpageblocks between the preferred and fallback -* category passes to avoid movable allocations consuming free -* pageblocks in tainted superpageblocks (which unmovable needs for -* future CLAIMs), and vice versa. +* Prefer whole pageblock allocations (>= pageblock_order) over +* sub-pageblock allocations because whole pageblocks enable the +* PCP buddy optimization for fast subsequent allocations. +* +* Search order: +* 1. Preferred SPBs: whole pageblock first, then sub-pageblock +* 2. Whole pageblock inline claim from tainted SPBs (non-movable only) +* 3. Whole pageblock from empty SPBs +* 4. Fallback to non-preferred SPBs +* +* Pass 1 tries whole pageblock first for PCP buddy optimization, +* then falls back to sub-pageblock within the same preferred SPBs. +* This ensures we never taint empty/clean SPBs while preferred +* SPBs still have free pages at any order. */ + +/* Pass 1: preferred SPBs -- whole pageblock first, then sub-pageblock */ for (full =SB_FULL ; full < __NR_SB_FULLNESS; full++) {enum sb_category cat = cat_order[movable][0 ];
@@ -2793,7 +2805,8 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, &zone->spb_lists[cat][full], list) {if (!sb->nr_free_pages)continue ; -for (current_order = order; +/* Try whole pageblock (or larger) first for PCP buddy */ +for (current_order =max (order, pageblock_order); current_order <NR_PAGE_ORDERS ; ++current_order) { area = &sb->free_area[current_order];
@@ -2810,15 +2823,34 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, migratetype < MIGRATE_PCPTYPES);return page; } +/* Then try sub-pageblock (no PCP buddy) */ +if (order < pageblock_order) { +for (current_order = order; + current_order < pageblock_order; + ++current_order) { + area = &sb->free_area[current_order]; + page =get_page_from_free_area ( + area, migratetype); +if (!page) +continue ; +page_del_and_expand (zone, page, + order, current_order, + migratetype); +trace_mm_page_alloc_zone_locked ( + page, order, migratetype, +pcp_allowed_order (order) && + migratetype <MIGRATE_PCPTYPES ); +return page; + } + } } }/* -* For non-movable allocations, try to reclaim free pageblocks -* from tainted superpageblocks before looking at empty or clean -* ones. Free pageblocks in tainted SBs have pages on the MOVABLE -* free list (reset by mark_pageblock_free), so the search above -* misses them. Claim them inline to keep non-movable allocations +* Pass 2: for non-movable allocations, try to claim free pageblocks +* from tainted superpageblocks. Free pageblocks in tainted SBs have +* pages on the MOVABLE free list (reset by mark_pageblock_free), so +* pass 1 misses them. Claim them inline to keep non-movable allocations * concentrated in already-tainted superpageblocks. * * Try whole pageblock orders first (preferred for PCP buddy optimization),
@@ -2896,7 +2928,7 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, } } -/* Empty superpageblocks: try before falling back to non-preferred category */ +/* Pass 3: whole pageblock from empty superpageblocks */ list_for_each_entry (sb, &zone->spb_empty, list) {if (!sb->nr_free_pages)continue ;
@@ -6422,6 +6454,17 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,if (!zonelist_zone (ac->preferred_zoneref)) goto nopage; +/* +* Preserve ALLOC_NOFRAGMENT through the slowpath so that reclaim +* and compaction are tried before allowing clean superpageblocks +* to be tainted. The fast path sets this via alloc_flags_nofragment() +* but gfp_to_alloc_flags() only sets it for defrag_mode. Re-add it +* here so the slowpath retries with NOFRAGMENT still protecting +* clean SPBs until the last-resort drop below. +*/ + alloc_flags |=alloc_flags_nofragment ( +zonelist_zone (ac->preferred_zoneref), gfp_mask); +/* * Check for insane configurations where the cpuset doesn't contain * any suitable zone to satisfy the request - e.g. non-movable
@@ -6561,8 +6604,13 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, &compaction_retries)) goto retry; -/* Reclaim/compaction failed to prevent the fallback */ -if (defrag_mode && (alloc_flags &ALLOC_NOFRAGMENT )) { +/* +* Reclaim and compaction have been tried but could not free enough +* pages in already-tainted superpageblocks. Drop NOFRAGMENT as a +* last resort to allow claiming from clean/empty SPBs and stealing +* across migratetype boundaries. This is better than OOM-killing. +*/ +if (alloc_flags &ALLOC_NOFRAGMENT ) { alloc_flags &= ~ALLOC_NOFRAGMENT ; goto retry; }
Signature · 1 line
2.54.0
RFC PATCH 21/40 mm: page_alloc: adopt partial pageblocks from tainted superpageblocks
In reply to Rik van RielAdd Phase 2 to rmqueue_bulk: when refilling PCP for unmovable or reclaimable allocations, search tainted superpageblocks for partially-free pageblocks with sub-pageblock buddy entries of the requested migratetype.
Claim ownership of the pageblock and move the found entry to PCP with PCPBuddy marking. Pass 0 (the existing owned-block recovery phase) picks up remaining buddy entries on subsequent refills, so there is no need to sweep the entire pageblock eagerly.
This concentrates non-movable allocations into already-tainted superpageblocks, reducing fragmentation spread to clean superpageblocks.
Pageblock-ownership handling: a pageblock encoded as pbd->cpu==0 is unowned and may be claimed; a non-zero value means another CPU's PCP has frozen pages from this block. In the latter case the refill walk keeps following the pageblock (the merge pass at __free_one_page can reabsorb the other CPU's PCPBuddy entries in the same lock acquire, clearing ownership before the walk finishes), instead of unconditionally skipping it. Without this, busy multi-CPU systems with high tainted-SPB occupancy would skip every already-touched pageblock in Phase 2 and let clean SPBs taint instead -- the exact failure Phase 2 was added to prevent.
--- mm/page_alloc.c | 131 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 117 insertions(+), 14 deletions(-)
mm/page_alloc.c +117 -14
@@ -1090,7 +1090,7 @@ static inline void set_buddy_order(struct page *page, unsigned int order)* - Set when Phase 0/1 restore or acquire whole pageblocks. * - Propagated to split remainders in pcp_rmqueue_smallest(). * - Set on freed pages from owned blocks routed to the owner PCP. -* - NOT set for Phase 2/3 fragments or zone-owned frees. +* - NOT set for Phase 3 fragments or zone-owned frees. * - The merge pass in free_pcppages_bulk() only processes * PagePCPBuddy pages, ensuring it never touches pages on * another CPU's PCP list.
@@ -3871,15 +3871,15 @@ __rmqueue(struct zone *zone, unsigned int order, int migratetype,* under a single hold of the lock, for efficiency. Add them to the * freelist of @pcp. * -* When @pcp is non-NULL and @count > 1 (normal pageset), uses a four-phase +* When @pcp is non-NULL and @count > 1 (normal pageset), uses a multi-phase * approach: -* Phase 0: Recover previously owned, partially drained blocks. -* Phase 1: Acquire whole pageblocks, claim ownership, set PagePCPBuddy. -* These pages are eligible for PCP-level buddy merging. -* Phase 2: Grab sub-pageblock fragments of the same migratetype. -* Phase 3: Fall back to __rmqueue() with migratetype fallback. -* Phase 2/3 pages are cached for batching only -- no ownership claim, -* no PagePCPBuddy, no PCP-level merging. +* Phase 0: Recover previously owned, partially drained blocks. +* Phase 1: Acquire whole pageblocks, claim ownership, set PagePCPBuddy. +* These pages are eligible for PCP-level buddy merging. +* Phase 2: Adopt partial pageblocks from tainted SPBs (non-movable only). +* Claims ownership so Pass 0 can recover buddy entries later. +* Phase 3: Fall back to __rmqueue() with migratetype fallback. +* No ownership claim, no PagePCPBuddy, no PCP-level merging. * * When @pcp is NULL or @count <= 1 (boot pageset), acquires individual * pages of the requested order directly.
@@ -3897,7 +3897,7 @@ static bool rmqueue_bulk(struct zone *zone, unsigned int order,int cpu =smp_processor_id ();unsigned long refilled =0 ;unsigned long flags; -int o; +unsigned int o;if (unlikely (alloc_flags &ALLOC_TRYLOCK )) {if (!spin_trylock_irqsave (&zone->lock, flags))
@@ -4007,11 +4007,114 @@ static bool rmqueue_bulk(struct zone *zone, unsigned int order, goto out;/* -* Phase 2 was removed: it swept zone free lists for sub-pageblock -* fragments, which are always empty when superpageblocks are enabled. -* Phase 3's __rmqueue() -> __rmqueue_smallest() properly searches -* per-superpageblock free lists at all orders. +* Phase 2: Adopt partial pageblocks from tainted SPBs. +* +* Phase 1 only grabs whole free pageblocks. When a tainted SPB +* has partially-used pageblocks with free sub-pageblock buddy +* entries, Phase 1 can't use them. Phase 3 can find them via +* __rmqueue_smallest, but without ownership or PCPBuddy marking, +* so they fragment further on drain. +* +* This phase bridges the gap: find a sub-pageblock free entry +* in a tainted SPB and claim ownership of its pageblock. Pass 0 +* will pick up remaining buddy entries on subsequent refills. +* +* Only for unmovable/reclaimable -- movable should use clean SPBs. */ +if (migratetype !=MIGRATE_MOVABLE && + !is_migrate_cma (migratetype)) { +enum sb_fullness full; + +for (full =SB_FULL ; full < __NR_SB_FULLNESS; full++) { +struct superpageblock *sb; + +list_for_each_entry (sb, + &zone->spb_lists[SB_TAINTED ][full], list) { +struct page *page; +int found_order =-1 ; +bool claim_pb; + +if (sb->nr_free_pages < pageblock_nr_pages /4 ) +continue ; + +/* +* Find a sub-pageblock free entry for our +* migratetype, starting from the largest order. +* +* Use a post-decrement loop so the unsigned +* counter cannot underflow when @order is 0; +* the previous signed counter relied on the +* mixed signed/unsigned comparison wrapping +* to a huge value, which UBSAN flagged and +* which let the loop walk free_area[-1]. +*/ +for (o = pageblock_order; o-- > order; ) { +struct free_area *area; + + area = &sb->free_area[o]; + page =get_page_from_free_area ( + area, migratetype); +if (page) { + found_order = o; +break ; + } + } +if (found_order <0 ) +continue ; + +/* +* Found a free fragment in a tainted SPB. Take +* it from the buddy. +* +* If the source pageblock is unowned, claim it: +* mark our pages PagePCPBuddy and register the +* block on owned_blocks so Pass 0 can recover +* remaining fragments on future refills. +* +* If the source pageblock is already owned by +* some CPU (us or another), take the page as a +* plain non-PCPBuddy fragment -- the same way +* Phase 3 / __rmqueue_smallest would. Setting +* PagePCPBuddy here would let two CPUs hold +* PCPBuddy pages from the same pageblock, and +* the PCP merge pass could then corrupt the +* other CPU's PCP list. +* +* Set PB_has_<migratetype> either way (bypasses +* page_del_and_expand which normally does the +* PB_has tracking); idempotent if already set. +*/ + pbd =pfn_to_pageblock (page, +page_to_pfn (page)); + claim_pb = (pbd->cpu ==0 ); + +del_page_from_free_list (page, zone, + found_order, + migratetype); +__spb_set_has_type (page, migratetype); +if (claim_pb) { +set_pcpblock_owner (page, cpu); +__SetPagePCPBuddy (page); + } +pcp_enqueue_tail (pcp, page, migratetype, + found_order); + refilled +=1 << found_order; + +/* +* Register for Phase 0 recovery so future +* drains from this pageblock can be swept +* back efficiently. Only meaningful when we +* actually claimed ownership above. +*/ +if (claim_pb &&list_empty (&pbd->cpu_node)) +list_add (&pbd->cpu_node, + &pcp->owned_blocks); + +if (refilled >= pages_needed) + goto out; + } + } + }/* * Phase 3: Last resort. Use __rmqueue() which does
Signature · 1 line
2.54.0
RFC PATCH 22/40 mm: page_alloc: add CONFIG_DEBUG_VM sanity checks for SPB counters
In reply to Rik van RielAdd spb_debug_check() and call it after every site that mutates the per-superpageblock type counters (nr_free / nr_unmovable / nr_reclaimable / nr_movable). Each counter must be <= total_pageblocks; a violation indicates that a PB_has_<mt> bit transition was missed by one of the allocation, free, claim, or evacuation paths and the counter has drifted out of sync with the bits.
VM_WARN_ONCE keeps the production cost zero (CONFIG_DEBUG_VM only) while giving us a single place to catch counter drift early during stress testing instead of debugging it from a much later misaccounting symptom.
Relax three pre-existing VM_WARN_ONCE checks in __add_to_free_list, move_to_free_list, and __del_page_from_free_list so they no longer warn for MIGRATE_ISOLATE / MIGRATE_CMA pageblocks. Those legitimately carry stale per-type counters from the isolation/un-isolation flow, and the warnings would fire spuriously once spb_debug_check() exposes that path under load.
--- mm/page_alloc.c | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-)
mm/page_alloc.c +38 -3
@@ -477,6 +477,32 @@ static inline int migratetype_to_has_bit(int migratetype) } } +#ifdef CONFIG_DEBUG_VM +static void spb_debug_check (struct superpageblock *sb,const char *caller) +{ +u16 total = sb->total_pageblocks; + +VM_WARN_ONCE (sb->nr_free > total, +"%s: nr_free %u > total %u (zone=%s sb=%lu)\n" , + caller, sb->nr_free, total, sb->zone->name, + (unsigned long )(sb - sb->zone->superpageblocks)); +VM_WARN_ONCE (sb->nr_unmovable > total, +"%s: nr_unmovable %u > total %u (zone=%s sb=%lu)\n" , + caller, sb->nr_unmovable, total, sb->zone->name, + (unsigned long )(sb - sb->zone->superpageblocks)); +VM_WARN_ONCE (sb->nr_reclaimable > total, +"%s: nr_reclaimable %u > total %u (zone=%s sb=%lu)\n" , + caller, sb->nr_reclaimable, total, sb->zone->name, + (unsigned long )(sb - sb->zone->superpageblocks)); +VM_WARN_ONCE (sb->nr_movable > total, +"%s: nr_movable %u > total %u (zone=%s sb=%lu)\n" , + caller, sb->nr_movable, total, sb->zone->name, + (unsigned long )(sb - sb->zone->superpageblocks)); +} +#else +static inline void spb_debug_check (struct superpageblock *sb,const char *caller) {} +#endif +/* * __spb_set_has_type - set PB_has_* and increment type counter *
@@ -508,6 +534,7 @@ static void __spb_set_has_type(struct page *page, int migratetype) sb->nr_movable++;break ; } +spb_debug_check (sb,"__spb_set_has_type" ); } }
@@ -545,6 +572,7 @@ static void __spb_clear_has_type(struct page *page, int migratetype) sb->nr_movable--;break ; } +spb_debug_check (sb,"__spb_clear_has_type" ); } }
@@ -778,6 +806,7 @@ static void superpageblock_pb_now_free(struct page *page)return ; sb->nr_free++; +spb_debug_check (sb,"pb_now_free" );spb_update_list (sb); }
@@ -800,6 +829,7 @@ static void superpageblock_pb_now_used(struct page *page)if (sb->nr_free) sb->nr_free--; +spb_debug_check (sb,"pb_now_used" );spb_update_list (sb); }
@@ -1265,7 +1295,9 @@ static inline void __add_to_free_list(struct page *page, struct zone *zone,struct free_area *area =pfn_sb_free_area (zone, pfn, order, &sb);int nr_pages =1 << order; -VM_WARN_ONCE (get_pageblock_migratetype (page) != migratetype, +VM_WARN_ONCE (get_pageblock_migratetype (page) != migratetype && + !is_migrate_isolate (get_pageblock_migratetype (page)) && + !is_migrate_cma (get_pageblock_migratetype (page)),"page type is %d, passed migratetype is %d (nr=%d)\n" ,get_pageblock_migratetype (page), migratetype, nr_pages);
@@ -1299,7 +1331,8 @@ static inline void move_to_free_list(struct page *page, struct zone *zone,int nr_pages =1 << order;/* Free page moving can fail, so it happens before the type update */ -VM_WARN_ONCE (get_pageblock_migratetype (page) != old_mt, +VM_WARN_ONCE (get_pageblock_migratetype (page) != old_mt && + !is_migrate_cma (get_pageblock_migratetype (page)),"page type is %d, passed migratetype is %d (nr=%d)\n" ,get_pageblock_migratetype (page), old_mt, nr_pages);
@@ -1324,7 +1357,9 @@ static inline void __del_page_from_free_list(struct page *page, struct zone *zonstruct free_area *area =pfn_sb_free_area (zone, pfn, order, &sb);int nr_pages =1 << order; -VM_WARN_ONCE (get_pageblock_migratetype (page) != migratetype, +VM_WARN_ONCE (get_pageblock_migratetype (page) != migratetype && + !is_migrate_isolate (get_pageblock_migratetype (page)) && + !is_migrate_cma (get_pageblock_migratetype (page)),"page type is %d, passed migratetype is %d (nr=%d)\n" ,get_pageblock_migratetype (page), migratetype, nr_pages);
Signature · 1 line
2.54.0
RFC PATCH 23/40 mm: page_alloc: targeted evacuation and dynamic reserves for tainted SPBs
In reply to Rik van RielReduce tainted-superpageblock proliferation with three changes:
1. Dynamic SPB_TAINTED_RESERVE. Scale the movable-steering reserve with SPB size (~3% of pageblocks, minimum 4). For a 512-pageblock SPB this gives 16 reserved pageblocks instead of the previous flat 4, triggering async defrag 4x earlier and keeping more headroom for unmovable claims.
2. Targeted evacuation before NOFRAGMENT drop. When the slowpath is about to drop ALLOC_NOFRAGMENT for an unmovable/reclaimable allocation, first try evacuating movable pages from tainted SPBs so the retry can satisfy via Pass 2 (claim_whole_block) without forcing __rmqueue_claim to taint a clean SPB.
3. Single-pass evacuation with a relaxed source-PB filter, sized for the slowpath.
Stack impact: sb_pfns[] grows from 32 bytes to 128 bytes -- trivial for an 8K/16K kernel stack.
--- mm/page_alloc.c | 334 +++++++++++++++++++++++++++++++----------------- 1 file changed, 219 insertions(+), 115 deletions(-)
mm/page_alloc.c +219 -115
@@ -2691,8 +2691,16 @@ static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags* fewer than this many free pageblocks, ensuring that unmovable claims * always find room in existing tainted superpageblocks instead of spilling * into clean ones. +* +* Scale with SPB size: reserve ~3% of pageblocks (minimum 4). +* For a 512-pageblock SPB this gives 16 reserved pageblocks. */ -#define SPB_TAINTED_RESERVE 4 +#define SPB_TAINTED_RESERVE_MIN 4 + +static inline u16 spb_tainted_reserve (const struct superpageblock *sb) +{ +return max_t (u16,SPB_TAINTED_RESERVE_MIN , sb->total_pageblocks /32 ); +}/* * On systems with many superpageblocks, we can afford to "write off"
@@ -3005,7 +3013,7 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,* with few free pageblocks to reserve space * for future unmovable/reclaimable claims. */ -if (sb->nr_free <=SPB_TAINTED_RESERVE ) +if (sb->nr_free <=spb_tainted_reserve (sb))continue ; for (current_order = order; current_order < NR_PAGE_ORDERS;
@@ -3582,7 +3590,7 @@ __rmqueue_sb_find_fallback(struct zone *zone, unsigned int order, &sb->free_area[order];if (movable && cat ==SB_TAINTED && - sb->nr_free <=SPB_TAINTED_RESERVE ) + sb->nr_free <=spb_tainted_reserve (sb))continue ;for (i =0 ; i <MIGRATE_PCPTYPES -1 ; i++) {
@@ -3631,7 +3639,7 @@ __rmqueue_sb_find_fallback(struct zone *zone, unsigned int order, &sb->free_area[order];if (movable && cat ==SB_TAINTED && - sb->nr_free <=SPB_TAINTED_RESERVE ) + sb->nr_free <=spb_tainted_reserve (sb))continue ;for (i =0 ; i <MIGRATE_PCPTYPES -1 ; i++) {
@@ -6744,9 +6752,33 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,/* * Reclaim and compaction have been tried but could not free enough -* pages in already-tainted superpageblocks. Drop NOFRAGMENT as a -* last resort to allow claiming from clean/empty SPBs and stealing -* across migratetype boundaries. This is better than OOM-killing. +* pages in already-tainted superpageblocks. Before dropping +* NOFRAGMENT, try targeted evacuation of movable pages from +* tainted SPBs to create free pageblocks for unmovable claims. +*/ +if ((alloc_flags &ALLOC_NOFRAGMENT ) && + (ac->migratetype ==MIGRATE_UNMOVABLE || + ac->migratetype ==MIGRATE_RECLAIMABLE )) { +struct zoneref *z; +struct zone *zone; + +for_each_zone_zonelist_nodemask (zone, z, ac->zonelist, + ac->highest_zoneidx, + ac->nodemask) { +if (spb_evacuate_for_order (zone, order, + ac->migratetype)) { + page =get_page_from_freelist (gfp_mask, order, + alloc_flags, ac); +if (page) + goto got_pg; + } + } + } + +/* +* Targeted evacuation could not free enough either. Drop +* NOFRAGMENT as a last resort to allow claiming from clean/empty +* SPBs. This is better than OOM-killing. */ if (alloc_flags &ALLOC_NOFRAGMENT ) { alloc_flags &= ~ALLOC_NOFRAGMENT ;
@@ -8819,7 +8851,7 @@ static bool spb_needs_defrag(struct superpageblock *sb)*/ if (spb_get_category (sb) ==SB_TAINTED )return sb->nr_movable >0 && - sb->nr_free <SPB_TAINTED_RESERVE ; + sb->nr_free <spb_tainted_reserve (sb);/* Clean SPBs: kcompactd handles consolidation; nothing to do here. */ return false;
@@ -8841,7 +8873,7 @@ static bool spb_defrag_done(struct superpageblock *sb)*/ if (spb_get_category (sb) ==SB_TAINTED )return !sb->nr_movable || - sb->nr_free >=SPB_TAINTED_RESERVE ; + sb->nr_free >=spb_tainted_reserve (sb);/* Clean SPBs should not be handled here. */ return true;
@@ -9077,6 +9109,184 @@ void init_superpageblock_defrag(struct superpageblock *sb)INIT_WORK (&sb->defrag_work, spb_defrag_work_fn); init_irq_work(&sb->defrag_irq_work, spb_defrag_irq_work_fn); } + +/* +* Maximum tainted superpageblock candidates per spb_evacuate_for_order call. +* Collected under zone->lock, then evacuated without it. Larger than the +* contig-allocation candidate cap because evacuation runs from the slowpath +* after reclaim/compaction failed: we need a meaningful chance of freeing a +* non-MOV-claimable pageblock before the slowpath escalates to dropping +* ALLOC_NOFRAGMENT (which lets __rmqueue_claim taint clean SPBs). Sized to +* scan a meaningful fraction of a typical tainted-pool population. +*/ +#define SPB_EVACUATE_MAX_CANDIDATES 16 + +/* +* Maximum pageblocks to evacuate per candidate SPB inside +* spb_evacuate_for_order. Each evacuation triggers page migration which is +* O(pages_per_pageblock) wall-clock cost, so this caps per-call latency. +* Bumped from 3 to 8 to free more capacity per slowpath escalation pass. +* Combined cap: SPB_EVACUATE_MAX_CANDIDATES * SPB_EVACUATE_MAX_PB_PER_SB +* pageblocks per call (16 * 8 = 128 = 256 MiB on x86 max migration budget). +*/ +#define SPB_EVACUATE_MAX_PB_PER_SB 8 + +/** +* sb_collect_evacuate_candidates - Find tainted SPBs for targeted evacuation +* @zone: zone to search (must hold zone->lock) +* @sb_pfns: output array of tainted superpageblock start PFNs +* @max: maximum candidates to collect +* +* Walk the per-zone tainted SPB lists and collect the start PFNs of +* superpageblocks that still hold movable pages, up to @max entries. +* The caller (spb_evacuate_for_order) drops zone->lock before actually +* evacuating each candidate. +* +* Returns number of candidate superpageblock PFNs found. +*/ +static int sb_collect_evacuate_candidates (struct zone *zone, +unsigned long *sb_pfns,int max) +{ +struct superpageblock *sb; +int full, n =0 ; + +lockdep_assert_held (&zone->lock); + +for (full =0 ; full < __NR_SB_FULLNESS; full++) { +list_for_each_entry (sb, &zone->spb_lists[SB_TAINTED ][full], + list) { +if (!sb->nr_movable) +continue ; + + sb_pfns[n++] = sb->start_pfn; +if (n >= max) +return n; + } + } +return n; +} + +/* +* Evacuate MOV content out of any pageblock in the given range that has it. +* +* The previous version filtered on the source pageblock's migratetype tag, +* which made evacuation blind to MOV stragglers living in PBs whose tag did +* not match the current allocation's requesting type: +* +* - PASS_2C / PASS_2D borrows set PB_has_<requesting_mt> on a MOV-tagged +* PB without changing the tag. The borrowed pages return to the MOV +* free list when freed, so a MOV-tagged PB can host non-MOV PB_has bits +* and MOV content simultaneously. +* +* - When __spb_set_has_type adds a non-MOV bit on a PB, the PB tag is not +* re-evaluated. PBs accumulate has-bits over time without their tag +* necessarily reflecting current content. +* +* Drop the migratetype tag filter and accept any PB with PB_has_movable set. +* Skip only the cases whose semantics forbid touching them here: +* - MIGRATE_ISOLATE under quarantine +* - CMA own allocator +* - MIGRATE_HIGHATOMIC reserve, evac would race the reservation logic +* +* Returns number of pageblocks evacuated. +*/ +static int evacuate_pb_range (struct zone *zone,unsigned long start_pfn, +unsigned long end_pfn,int max) +{ +unsigned long pfn; +int nr_evacuated =0 ; + +for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) { +struct page *page; +int pb_mt; + +if (!pfn_valid (pfn)) +continue ; + +if (!zone_spans_pfn (zone, pfn)) +continue ; + + page =pfn_to_page (pfn); + +if (!get_pfnblock_bit (page, pfn, PB_has_movable)) +continue ; + + pb_mt =get_pfnblock_migratetype (page, pfn); +if (is_migrate_isolate (pb_mt) || +is_migrate_cma (pb_mt) || + pb_mt ==MIGRATE_HIGHATOMIC ) +continue ; + +evacuate_pageblock (zone, pfn, true); +if (++nr_evacuated >= max) +break ; + } +return nr_evacuated; +} + +/** +* spb_evacuate_for_order - Targeted evacuation of movable pages from +* tainted superpageblocks +* @zone: zone to work on +* @order: allocation order that failed +* @migratetype: requesting migratetype (informational; the evacuation +* loop itself is migratetype-independent) +* +* Collect tainted superpageblocks with movable content under zone->lock, +* then drop the lock and walk each candidate's pageblocks, evacuating +* any PB that has PB_has_movable set and does not have a special tag +* (ISOLATE, CMA, HIGHATOMIC). PBs that are pure MOV become empty whole +* pageblocks for Pass 2 / claim_whole_block on retry; mixed PBs lose +* their MOV stragglers so future allocations of the dominant type stop +* competing with MOV residue. +* +* Returns true if evacuation was performed (caller should retry allocation). +*/ +static bool spb_evacuate_for_order (struct zone *zone,unsigned int order, +int migratetype) +{ +unsigned long sb_pfns[SPB_EVACUATE_MAX_CANDIDATES ]; +unsigned long flags; +int nr_sbs, i; +unsigned int attempts =0 ; +bool did_evacuate = false; + +/* +* Single-pass evacuation: collect candidate tainted SPBs (anything +* with MOV content), then walk each one's pageblocks evacuating MOV +* content from any non-special PB. evacuate_pb_range filters by +* PB_has_movable, so this is a no-op on PBs that have no MOV content. +* +* Two effects accumulate: +* - PBs that are pure MOV become empty -> free MOV pageblock, +* claimable by Pass 2 / claim_whole_block on the retry. +* - PBs that are mixed (e.g., UNMOV + MOV stragglers) lose the MOV +* stragglers, so future allocations of the dominant type can use +* the PB without competing with the MOV residue. +* +* The previous two-phase design tried to do these separately and +* filtered evacuation by source PB tag. That left MOV content +* stranded in PBs whose tag did not match either phase, and gave up +* after one phase even though the other phase could have helped. +*/ +spin_lock_irqsave (&zone->lock, flags); + nr_sbs =sb_collect_evacuate_candidates (zone, sb_pfns, +SPB_EVACUATE_MAX_CANDIDATES ); +spin_unlock_irqrestore (&zone->lock, flags); + +for (i =0 ; i < nr_sbs; i++) { +unsigned long end_pfn = sb_pfns[i] +SUPERPAGEBLOCK_NR_PAGES ; +int n; + + n =evacuate_pb_range (zone, sb_pfns[i], end_pfn, +SPB_EVACUATE_MAX_PB_PER_SB ); + attempts += n; +if (n) + did_evacuate = true; + } + +return did_evacuate; +}#endif /* CONFIG_COMPACTION */ #ifdef CONFIG_CONTIG_ALLOC
@@ -9655,112 +9865,6 @@ static struct page *spb_try_alloc_contig(struct zone *zone, return NULL; } -/** -* sb_collect_evacuate_candidates - Find pageblocks for targeted evacuation -* @zone: zone to search (must hold zone->lock) -* @migratetype: desired migratetype (MIGRATE_UNMOVABLE or MIGRATE_RECLAIMABLE) -* @sb_pfns: output array of tainted superpageblock start PFNs -* @max: maximum candidates to collect -* -* Find tainted superpageblocks containing pageblocks of the desired migratetype -* that also have movable pages to evacuate. Evacuating movable pages from -* these pageblocks creates buddy coalescing opportunities for high-order -* allocations of the desired migratetype. -* -* Returns number of candidate superpageblock PFNs found. -*/ -static int sb_collect_evacuate_candidates (struct zone *zone,int migratetype, -unsigned long *sb_pfns,int max) -{ -struct superpageblock *sb; -int full, n =0 ; - -lockdep_assert_held (&zone->lock); - -for (full =0 ; full < __NR_SB_FULLNESS; full++) { -list_for_each_entry (sb, &zone->spb_lists[SB_TAINTED ][full], - list) { -bool has_matching; - -if (!sb->nr_movable) -continue ; - -if (migratetype ==MIGRATE_UNMOVABLE ) - has_matching = sb->nr_unmovable >0 ; -else if (migratetype ==MIGRATE_RECLAIMABLE ) - has_matching = sb->nr_reclaimable >0 ; -else -continue ; - -if (!has_matching) -continue ; - - sb_pfns[n++] = sb->start_pfn; -if (n >= max) -return n; - } - } -return n; -} - -/** -* spb_evacuate_for_order - Targeted evacuation of movable pages from -* unmovable/reclaimable pageblocks -* @zone: zone to work on -* @order: allocation order that failed -* @migratetype: desired migratetype (MIGRATE_UNMOVABLE or MIGRATE_RECLAIMABLE) -* -* Instead of blind compaction, use superpageblock metadata to find pageblocks -* of the right migratetype in tainted superpageblocks and evacuate their -* movable pages. This creates buddy coalescing opportunities within -* the pageblock, enabling higher-order allocations. -* -* Returns true if evacuation was performed (caller should retry allocation). -*/ -static bool spb_evacuate_for_order (struct zone *zone,unsigned int order, -int migratetype) -{ -unsigned long sb_pfns[SPB_CONTIG_MAX_CANDIDATES ]; -unsigned long flags; -int nr_sbs, i; -bool did_evacuate = false; - -spin_lock_irqsave (&zone->lock, flags); - nr_sbs =sb_collect_evacuate_candidates (zone, migratetype, - sb_pfns, -SPB_CONTIG_MAX_CANDIDATES ); -spin_unlock_irqrestore (&zone->lock, flags); - -for (i =0 ; i < nr_sbs && !did_evacuate; i++) { -unsigned long pfn, end_pfn; - - end_pfn = sb_pfns[i] +SUPERPAGEBLOCK_NR_PAGES ; -for (pfn = sb_pfns[i]; pfn < end_pfn; - pfn += pageblock_nr_pages) { -struct page *page; - -if (!pfn_valid (pfn)) -continue ; - -/* Superpageblocks can straddle zone boundaries. */ -if (!zone_spans_pfn (zone, pfn)) -continue ; - - page =pfn_to_page (pfn); - -if (get_pfnblock_migratetype (page, pfn) != migratetype) -continue ; - -if (!get_pfnblock_bit (page, pfn, PB_has_movable)) -continue ; - -evacuate_pageblock (zone, pfn, true); - did_evacuate = true; -break ; - } - } -return did_evacuate; -}#endif /* CONFIG_COMPACTION */ /**
Signature · 1 line
2.54.0
RFC PATCH 24/40 mm: page_alloc: prevent UNMOVABLE/RECLAIMABLE mixing in pageblocks
In reply to Rik van RielInside a tainted SPB, free pages of UNMOVABLE and RECLAIMABLE allocations cannot be told apart by the buddy allocator's compatibility heuristic (alike_pages == 0 between the two non-movable types in try_to_claim_block). Once a pageblock holds in-use pages of both, any sticky UNMOVABLE pinhole prevents the RECLAIMABLE pages from coalescing into useful higher-order chunks when they drain back to the buddy. The PB's free capacity is permanently capped at order-1 dust regardless of how much of it actually returns. Sticky recl pages (active dentries, locked btrfs eb folios, NOFS slab) are unavoidable; the cost is paid in internal fragmentation.
Two paths in the page allocator create UNMOVABLE<->RECLAIMABLE mixing today:
1. try_to_claim_block() relabels a partial PB whenever the 50% threshold "free_pages + alike_pages >= pageblock_nr_pages/2" passes. For UNMOV<->RECL, alike_pages == 0, so the rule degenerates to free_pages >= 256. A PB with 256 in-use UNMOV pages plus 256 free pages passes and is relabeled RECL. Both PB_has_unmovable and PB_has_reclaimable are then set.
2. __rmqueue_steal() takes a single foreign-type page out of a PB without relabeling the PB. A UNMOVABLE allocation stealing from a RECLAIMABLE-labeled PB sets PB_has_unmovable on top of the existing PB_has_reclaimable.
Tighten both paths:
- Add noncompatible_cross_type() helper that detects the UNMOV<->RECL pair (MOVABLE may still mix with either since movable pages can be migrated out).
- In try_to_claim_block(), require a fully-free PB (free_pages == pageblock_nr_pages) for any cross-type relabel, regardless of from_tainted_spb. The other-type bit inherited from the prior label is stale on a fully-free PB (no in-use pages of either type) so clear it during the relabel rather than leaving the PB visibly mixed in PB_has_* state.
- In __rmqueue_steal(), pass a new SB_SKIP_CROSS_TYPE flag to __rmqueue_sb_find_fallback() so the cross-type fallback entry in fallbacks[] is skipped. Steal then falls through to the MIGRATE_MOVABLE second fallback instead of single-page-stealing into a foreign non-movable PB.
The from_tainted_spb=true caller of try_to_claim_block() is unaffected because it hardcodes block_type=MIGRATE_MOVABLE. The claim_whole_block() branch (current_order >= pageblock_order) is also unaffected: it requires PB_all_free, so the PB is fully free of any prior type.
Existing mixed PBs from before this change won't unmix; the win is for PBs created after.
--- mm/page_alloc.c | 108 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 83 insertions(+), 25 deletions(-)
mm/page_alloc.c +83 -25
@@ -3073,6 +3073,23 @@ static int fallbacks[MIGRATE_PCPTYPES][MIGRATE_PCPTYPES - 1] = { [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE }, }; +/* +* UNMOVABLE and RECLAIMABLE allocations should not share the same +* pageblock. Their free pages are interchangeable on the buddy free +* lists (alike_pages == 0 between them), so once a PB holds both +* types the buddy can no longer tell them apart and any sticky +* UNMOVABLE pinhole prevents the RECLAIMABLE pages from coalescing +* into useful higher-order chunks when they drain back. MOVABLE may +* mix with either, since MOVABLE pages can be migrated out. +*/ +static inline bool noncompatible_cross_type (int start_type,int fallback_type) +{ +return (start_type ==MIGRATE_UNMOVABLE && + fallback_type ==MIGRATE_RECLAIMABLE ) || + (start_type ==MIGRATE_RECLAIMABLE && + fallback_type ==MIGRATE_UNMOVABLE ); +} +#ifdef CONFIG_CMA static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,unsigned int order)
@@ -3450,11 +3467,10 @@ try_to_claim_block(struct zone *zone, struct page *page, bool from_tainted_spb) {int free_pages, movable_pages, alike_pages; -unsigned long start_pfn;#ifdef CONFIG_COMPACTION -struct page *start_page;struct superpageblock *sb;#endif +unsigned long start_pfn;/* * Don't steal from pageblocks that are isolated for
@@ -3512,32 +3528,48 @@ try_to_claim_block(struct zone *zone, struct page *page,* allocations. Inside a tainted SPB the protection is unnecessary: * fragmentation has already been accepted at the SPB level, and * relabeling is much cheaper than tainting a fresh clean SPB. -*/ -if (from_tainted_spb || - free_pages + alike_pages >= (1 << (pageblock_order-1 )) || - page_group_by_mobility_disabled) { -__move_freepages_block (zone, start_pfn, block_type, start_type); -set_pageblock_migratetype (pfn_to_page (start_pfn), start_type); -#ifdef CONFIG_COMPACTION -/* -* Track actual page contents in pageblock flags and -* update superpageblock counters so the SPB moves to -* the correct fullness list for steering. -*/ - start_page =pfn_to_page (start_pfn); -__spb_set_has_type (start_page, start_type); -if (block_type != start_type) -__spb_set_has_type (start_page, block_type); - - sb =pfn_to_superpageblock (zone, start_pfn); -if (sb) -spb_update_list (sb); +* +* UNMOVABLE<->RECLAIMABLE cross-type claims override these rules: +* once mixed, sticky pinholes of one type prevent the other from +* coalescing into useful higher-order free chunks even after drain. +* Only relabel a fully-free PB in that case, regardless of whether +* the SPB is tainted. +*/ +if (noncompatible_cross_type (start_type, block_type)) { +if (free_pages != pageblock_nr_pages) +return NULL ; + }else if (!from_tainted_spb && + free_pages + alike_pages < (1 << (pageblock_order-1 )) && + !page_group_by_mobility_disabled) { +return NULL ; + } -#endif -return __rmqueue_smallest (zone, order, start_type); +__move_freepages_block (zone, start_pfn, block_type, start_type); +set_pageblock_migratetype (pfn_to_page (start_pfn), start_type); +#ifdef CONFIG_COMPACTION +/* +* Track actual page contents in pageblock flags and update +* superpageblock counters so the SPB moves to the correct +* fullness list for steering. +* +* For cross-type UNMOVABLE<->RECLAIMABLE relabel (which by the +* predicate above only fires on a fully-free PB), the inherited +* PB_has_<block_type> bit is stale -- there are no in-use pages +* of that type. Clear it so the resulting PB is unmixed. +*/ +__spb_set_has_type (pfn_to_page (start_pfn), start_type); +if (block_type != start_type) { +if (noncompatible_cross_type (start_type, block_type)) +__spb_clear_has_type (pfn_to_page (start_pfn), block_type); +else +__spb_set_has_type (pfn_to_page (start_pfn), block_type); } -return NULL ; + sb =pfn_to_superpageblock (zone, start_pfn); +if (sb) +spb_update_list (sb); +#endif +return __rmqueue_smallest (zone, order, start_type); }/*
@@ -3561,6 +3593,13 @@ try_to_claim_block(struct zone *zone, struct page *page,#define SB_SEARCH_EMPTY (1 << 1)#define SB_SEARCH_FALLBACK (1 << 2)#define SB_SEARCH_ALL (SB_SEARCH_PREFERRED | SB_SEARCH_EMPTY | SB_SEARCH_FALLBACK) +/* +* Skip UNMOVABLE<->RECLAIMABLE cross-type fallback. Used by the steal +* path to prevent landing single foreign-type pages into a PB labeled +* with the other non-movable type -- a steal does not relabel the PB +* so cross-type stealing creates permanent mixing. +*/ +#define SB_SKIP_CROSS_TYPE (1 << 3)static struct page * __rmqueue_sb_find_fallback(struct zone *zone, unsigned int order,
@@ -3597,6 +3636,10 @@ __rmqueue_sb_find_fallback(struct zone *zone, unsigned int order,int fmt = fallbacks[start_migratetype][i];struct page *page; +if ((search_cats &SB_SKIP_CROSS_TYPE ) && +noncompatible_cross_type (start_migratetype, fmt)) +continue ; + page =get_page_from_free_area (area, fmt);if (page) {
@@ -3618,6 +3661,10 @@ __rmqueue_sb_find_fallback(struct zone *zone, unsigned int order,int fmt = fallbacks[start_migratetype][i];struct page *page; +if ((search_cats &SB_SKIP_CROSS_TYPE ) && +noncompatible_cross_type (start_migratetype, fmt)) +continue ; + page =get_page_from_free_area (area, fmt);if (page) {
@@ -3646,6 +3693,10 @@ __rmqueue_sb_find_fallback(struct zone *zone, unsigned int order,int fmt = fallbacks[start_migratetype][i];struct page *page; +if ((search_cats &SB_SKIP_CROSS_TYPE ) && +noncompatible_cross_type (start_migratetype, fmt)) +continue ; + page =get_page_from_free_area (area, fmt);if (page) {
@@ -3782,11 +3833,18 @@ __rmqueue_steal(struct zone *zone, int order, int start_migratetype,/* * When ALLOC_NOFRAG_TAINTED_OK is set, only steal from tainted * SPBs to avoid tainting clean ones. Otherwise search all categories. +* +* Always skip UNMOVABLE<->RECLAIMABLE cross-type fallback. The steal +* path takes a single page without relabeling its PB, so a cross-type +* steal would land an UNMOVABLE page in a RECLAIMABLE-labeled PB +* (or vice versa) and create permanent mixing. Falling through to +* MIGRATE_MOVABLE (the second fallback) is preferable. */ if (alloc_flags &ALLOC_NOFRAG_TAINTED_OK ) search_cats =SB_SEARCH_PREFERRED ;else search_cats =SB_SEARCH_PREFERRED |SB_SEARCH_FALLBACK ; + search_cats |=SB_SKIP_CROSS_TYPE ;/* * Search per-superpageblock free lists for fallback migratetypes.
Signature · 1 line
2.54.0
RFC PATCH 25/40 mm: trigger deferred SPB evac when atomic allocs would taint a clean SPB
In reply to Rik van RielHook queue_spb_evacuate() into __rmqueue_claim() so that whenever a non-movable allocation is about to claim a pageblock from an empty or clean superpageblock as a fallback (i.e. cat_search[c] is not SB_SEARCH_PREFERRED), a deferred spb_evacuate_for_order() is scheduled on the zone's pgdat workqueue.
The current allocation still proceeds and taints the clean SPB this time, but the deferred evacuation creates free pageblocks inside existing tainted SPBs so the next caller hitting the same trigger can claim from the tainted pool instead of tainting another clean SPB.
Movable allocations are excluded because their preferred category is SB_CLEAN; falling back from clean to tainted does not taint anything new and so does not need the hint.
The trigger is gated by single-flight, throttle, and tainted-pool precheck inside queue_spb_evacuate(), so it is safe to fire from this hot path without storming the workqueue.
--- include/linux/mmzone.h | 18 ++++ mm/page_alloc.c | 198 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 215 insertions(+), 1 deletion(-)
include/linux/mmzone.h +18 -0
@@ -1236,6 +1236,22 @@ struct zone {unsigned int compact_considered;unsigned int compact_defer_shift;int compact_order_failed; + +/* +* Atomic-context SPB evacuation deferral state. +* +* spb_evac_in_flight: bitmap indexed by +* migratetype * NR_PAGE_ORDERS + order, set on enqueue and +* cleared by the worker after spb_evacuate_for_order returns. +* Provides single-flight gating per (migratetype, order). +* +* spb_evac_last: jiffies of the last enqueue per migratetype, +* used as a 10ms throttle to prevent wakeup storms from +* concurrent atomic allocations. +*/ +DECLARE_BITMAP (spb_evac_in_flight, +MIGRATE_PCPTYPES *NR_PAGE_ORDERS ); +unsigned long spb_evac_last[MIGRATE_PCPTYPES ];#endif #if definedCONFIG_COMPACTION || definedCONFIG_CMA
@@ -1652,6 +1668,8 @@ typedef struct pglist_data {struct task_struct *kcompactd;bool proactive_compact_trigger;struct workqueue_struct *evacuate_wq; +struct llist_head spb_evac_pending; +struct irq_work spb_evac_irq_work;#endif /* * This is a per-node reserve of pages that are not available
mm/page_alloc.c +197 -1
234 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 26/40 mm: page_alloc: refuse fragmenting fallback for callers with cheap fallback
In reply to Rik van RielA coarse bail-out gate in get_page_from_freelist's slowpath retry, returning NULL to keep atomic-shape allocations from tainting clean SPBs, would break early-boot in QEMU: cred_init's slab cache create reaches the slowpath with gfp = __GFP_COMP (gfp_allowed_mask = GFP_BOOT_MASK strips __GFP_RECLAIM from GFP_KERNEL during boot), has no fallback path, and panics when a coarse gate refuses the allocation.
Add a finer-grained refusal anchored in __rmqueue, where the SPB-aware free-list walk already runs:
- Add ALLOC_HIGHORDER_OPTIONAL, set in gfp_to_alloc_flags() for two shapes:
1. Explicit fallback declaration: __GFP_NORETRY without __GFP_RETRY_MAYFAIL. Used by THP, slab high-order refill, skb_page_frag_refill on full sockets, etc.
2. Atomic-context shape: no __GFP_DIRECT_RECLAIM, no __GFP_NOMEMALLOC, no __GFP_NOFAIL. Catches GFP_ATOMIC, GFP_NOWAIT, including ALLOC_HIGHATOMIC consumers (which still get a second crack at the dedicated MIGRATE_HIGHATOMIC reserve in rmqueue_buddy after __rmqueue returns NULL).
__GFP_MEMALLOC and __GFP_NOFAIL never get the flag -- they must succeed even at the cost of fresh-SPB taint.
- Add struct spb_tainted_walk to record what __rmqueue_smallest's Pass 1 saw on the SB_TAINTED list (any free pages, any free PB, below-reserve pageblock count). Thread it through the function's new fourth argument; non-walking call sites pass NULL.
- In __rmqueue, allocate the walk on the stack for callers with ALLOC_HIGHORDER_OPTIONAL set on a non-movable, non-CMA migratetype. Force *mode back to RMQUEUE_NORMAL on every call so rmqueue_bulk Phase 3 can't reuse a memoised RMQUEUE_CLAIM/STEAL state to skip the gate across iterations.
- After __rmqueue_smallest returns NULL, check the walk: if a tainted SPB has free pages or a free pageblock that could absorb this allocation after evacuation, return NULL and bump SPB_HIGHORDER_REFUSED. Skip RMQUEUE_CLAIM and RMQUEUE_STEAL entirely (both can taint clean SPBs). The slowpath will eventually drop NOFRAGMENT and let the allocation proceed only for the callers that lack ALLOC_HIGHORDER_OPTIONAL -- i.e. the truly must-not-fail consumers.
- Before falling through to Pass 3 (empty SPBs) inside __rmqueue_smallest, kick queue_spb_evacuate() when the walk saw a tainted SPB below its reserve threshold, so future allocations have a movable-evicted home in an already-tainted SPB.
- Add SPB_HIGHORDER_REFUSED vm event counter (events, not refused
allocations: a single high-level alloc that retries can be counted multiple times across per-zone attempts).
The early-boot SB_TAINTED list is empty, so the walk records nothing, the refusal does not engage, and __rmqueue falls through to RMQUEUE_CLAIM which taints the first SPB normally (the first taint is unavoidable). cred_init's slab create succeeds, boot succeeds.
Tested in a 16 GB QEMU VM under combined sb-stress + UDP-loopback + fork/mmap storms (~480s); 2 tainted Normal SPBs out of 13 (boot baseline 1, +1 during stress); 11 clean SPBs distributed movable load; no kernel BUG, oops, hang, or panic.
--- include/linux/vm_event_item.h | 5 ++ mm/internal.h | 1 + mm/page_alloc.c | 115 ++++++++++++++++++++++++++++++++-- mm/vmstat.c | 1 + 4 files changed, 116 insertions(+), 6 deletions(-)
include/linux/vm_event_item.h +5 -0
@@ -76,6 +76,11 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,CMA_ALLOC_SUCCESS ,CMA_ALLOC_FAIL , #endif +SPB_HIGHORDER_REFUSED ,/* +* refused fragmenting fallback to keep +* a clean SPB clean when a tainted SPB +* still has free pageblocks +*/ UNEVICTABLE_PGCULLED ,/* culled to noreclaim list */ UNEVICTABLE_PGSCANNED ,/* scanned for reclaimability */ UNEVICTABLE_PGRESCUED, /* rescued from noreclaim list */
mm/internal.h +1 -0
@@ -1512,6 +1512,7 @@ unsigned int reclaim_clean_pages_from_list(struct zone *zone,#define ALLOC_TRYLOCK 0x400/* Only use spin_trylock in allocation path */ #define ALLOC_KSWAPD 0x800/* allow waking of kswapd, __GFP_KSWAPD_RECLAIM set */ #define ALLOC_NOFRAG_TAINTED_OK 0x1000/* NOFRAGMENT, but allow steal from tainted SPBs */ +#define ALLOC_HIGHORDER_OPTIONAL 0x2000/* caller can fall back to a lower order */ /* Flags that allow allocations below the min watermark. */ #define ALLOC_RESERVES (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM)
mm/page_alloc.c +109 -6
181 lines not on this page · raw message
mm/vmstat.c +1 -0
@@ -1388,6 +1388,7 @@ const char * const vmstat_text[] = { [I(CMA_ALLOC_SUCCESS)] = "cma_alloc_success", [I(CMA_ALLOC_FAIL)] = "cma_alloc_fail", #endif + [I(SPB_HIGHORDER_REFUSED)] = "spb_highorder_refused", [I(UNEVICTABLE_PGCULLED)] = "unevictable_pgs_culled", [I(UNEVICTABLE_PGSCANNED)] = "unevictable_pgs_scanned", [I(UNEVICTABLE_PGRESCUED)] = "unevictable_pgs_rescued",
Signature · 1 line
2.54.0
RFC PATCH 27/40 mm: page_alloc: cross-migratetype buddy borrow within tainted SPBs
In reply to Rik van RielWhen pages are freed via __free_one_page they're placed on the per-SPB free_list determined by their pageblock's migratetype, not the original allocation's migratetype. Slab-heavy and cache-heavy workloads both expose structural mismatches that leave non-movable allocations stranded:
- RECLAIMABLE pageblocks fill up densely with live slab objects (e.g. btrfs_inode caches), leaving very few sub-pageblock free fragments on the RECL free list.
- UNMOVABLE pageblocks accumulate sparse free space from vmalloc and raw-alloc churn -- tens of thousands of free pages, all on the UNMOV free list.
- MOVABLE-tagged pageblocks in tainted SPBs absorb freed page-cache and anon-LRU pages, accumulating large pools all on the MOVABLE free list -- invisible to non-movable demand even though the tainted SPB has plenty of unused space.
Add two new passes between Pass 2b and Pass 3 of __rmqueue_smallest, both restricted to SB_TAINTED (clean SPBs must not be polluted with cross-type mixing) and both purely transient borrows (no pageblock relabel; the borrowed page returns to its source list when freed):
Pass 2c -- cross-non-movable borrow. UNMOV alloc tries the RECL free list; RECL alloc tries the UNMOV free list. Restricted to UNMOV <-> RECL.
Pass 2d -- cross-MOV borrow. Non-movable alloc tries the MOVABLE free list of a tainted SPB. Tradeoff: the borrowed UNMOV/RECL content blocks compaction of its source pageblock until freed; restricted to SB_TAINTED so contamination is bounded to one pageblock inside an already-tainted SPB. The alternative -- Pass 3 tainting a fresh clean SPB -- removes a 1 GiB region from the clean pool, which is strictly worse for the anti- fragmentation invariant the series is built around.
PB_has_<requested_type> is set via __spb_set_has_type so spb_defrag accounting reflects that the pageblock now hosts our type's content. PB_has_<source_type> stays set since other buddies of that type remain.
Movable allocations don't participate (they have Pass 4) and CMA is skipped. Observable as SPB_ALLOC_OUTCOME_PASS_2C and SPB_ALLOC_OUTCOME_PASS_2D on the spb_alloc_walk tracepoint.
Live measurement on a 250 GB system with btrfs root (Stage 1 + simplified Stage 2a) at boot+7min: 12 tainted Normal- zone SPBs grew from 4 baseline despite the existing 11 having between 825 and 87,062 free pages each, ALL on the UNMOV list while the workload kept allocating RECL btrfs_inode slab pages. Pass 2c lets those allocs absorb into the existing UNMOV-listed free pool rather than creating fresh tainted SPBs; Pass 2d extends the same idea to the MOV-listed free pool that page- cache reclaim leaves behind.
--- mm/page_alloc.c | 156 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+)
mm/page_alloc.c +156 -0
@@ -2820,6 +2820,7 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,struct page *page;int full;struct superpageblock *sb; +int opposite_mt;/* * Category search order: 2 passes. * Movable: clean first, then tainted (pack into clean SBs).
@@ -2999,6 +3000,161 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, } } } + +/* +* Pass 2c: cross-non-movable borrow within tainted SPBs. +* +* If we're a non-movable alloc and Pass 1/2/2b couldn't find a +* buddy on our migratetype's free list anywhere, but tainted +* SPBs have free buddies on the *opposite* non-movable type's +* free list, take one of those. +* +* Why this happens: when pages are freed, __free_one_page puts +* them on the free_list determined by their pageblock's tag, +* not the original allocation's migratetype. Slab caches tend +* to be dense (RECL pageblocks fill up; few sub-PB fragments), +* while UNMOV pageblocks accumulate sparse free space from +* vmalloc/raw alloc churn. Net effect: tainted SPBs frequently +* have tens of thousands of free pages all on the UNMOV list, +* invisible to RECL allocs (or vice versa). Without this pass, +* the alloc falls through to Pass 3 and taints a fresh clean +* SPB even though the existing tainted ones have plenty of +* unused space. +* +* We do NOT relabel the source pageblock. The buddy is taken +* from @opposite_mt's free list and the splits go back on +* @opposite_mt's list (page_del_and_expand uses the same mt +* for delete and expand). The pageblock tag is unchanged, so +* the page returns to @opposite_mt's list when freed via +* __free_one_page. Effectively a borrow: the alloc takes a +* physical page from a UNMOV-tagged pageblock for a RECL +* use, and the page cycles back to UNMOV's list on free. +* +* We do set PB_has_<migratetype> via __spb_set_has_type so +* spb_defrag accounting reflects that this pageblock now hosts +* our migratetype's content too. PB_has_<opposite_mt> stays +* set since other buddies of that type remain. +* +* Restricted to UNMOV ↔ RECL. Movable allocations don't +* participate (they have their own Pass 4 fallback path). +* +* Restricted to SB_TAINTED to avoid spreading mixing into +* clean SPBs. +*/ + opposite_mt =-1 ; +if (migratetype ==MIGRATE_UNMOVABLE ) + opposite_mt =MIGRATE_RECLAIMABLE ; +else if (migratetype ==MIGRATE_RECLAIMABLE ) + opposite_mt =MIGRATE_UNMOVABLE ; + +if (opposite_mt >=0 ) { +for (full =SB_FULL ; full < __NR_SB_FULLNESS; full++) { +list_for_each_entry (sb, + &zone->spb_lists[SB_TAINTED ][full], list) { +int co; + +if (!sb->nr_free_pages) +continue ; +for (co =min_t (int, pageblock_order -1 , +NR_PAGE_ORDERS -1 ); + co >= (int )order; + --co) { + current_order = co; + area = &sb->free_area[current_order]; + page =get_page_from_free_area ( + area, opposite_mt); +if (!page) +continue ; +if (get_pageblock_isolate (page)) +continue ; +if (is_migrate_cma ( +get_pageblock_migratetype (page))) +continue ; +page_del_and_expand (zone, page, + order, current_order, + opposite_mt); +__spb_set_has_type (page, + migratetype); +trace_mm_page_alloc_zone_locked ( + page, order, migratetype, +pcp_allowed_order (order) && + migratetype <MIGRATE_PCPTYPES ); +return page; + } + } + } + } + +/* +* Pass 2d: cross-MOV borrow within tainted SPBs. +* +* If Pass 1/2/2b/2c all failed, the next step is Pass 3 +* which would taint a fresh clean SPB. Before that, try +* to borrow an individual buddy from a tainted SPB's +* MIGRATE_MOVABLE free list. +* +* Tainted SPBs accumulate large amounts of free space on +* the MOV free list (e.g. reclaimed page-cache pages +* whose pageblock tag is MOVABLE). Pass 1 cannot see +* those for non-movable allocs, Pass 2/2b cannot claim a +* whole pageblock when sb->nr_free == 0, and Pass 2c is +* restricted to UNMOV<->RECL. The result is a tainted +* SPB with tens to hundreds of thousands of free pages +* all unreachable from non-movable demand. +* +* Borrow semantics mirror Pass 2c: take a buddy from the +* MOVABLE free list without relabeling the source +* pageblock. The page is used for the requesting non- +* movable mt for the lifetime of the allocation, then on +* free returns to the MOVABLE list. +* +* Cost: the borrowed UNMOV/RECL content blocks +* compaction of its source pageblock until freed. +* Restricted to SB_TAINTED so the contamination is +* bounded to an already-tainted SPB; the alternative +* (Pass 3) taints a fresh clean SPB and removes a 1 GiB +* region from the clean pool, which is strictly worse. +* +* Skipped for movable allocs (they have Pass 4) and for +* CMA allocs. +*/ +if (!movable && !is_migrate_cma (migratetype)) { +for (full =SB_FULL ; full < __NR_SB_FULLNESS; full++) { +list_for_each_entry (sb, + &zone->spb_lists[SB_TAINTED ][full], list) { +int co; + +if (!sb->nr_free_pages) +continue ; +for (co =min_t (int, pageblock_order -1 , +NR_PAGE_ORDERS -1 ); + co >= (int )order; + --co) { + current_order = co; + area = &sb->free_area[current_order]; + page =get_page_from_free_area ( + area,MIGRATE_MOVABLE ); +if (!page) +continue ; +if (get_pageblock_isolate (page)) +continue ; +if (is_migrate_cma ( +get_pageblock_migratetype (page))) +continue ; +page_del_and_expand (zone, page, + order, current_order, +MIGRATE_MOVABLE ); +__spb_set_has_type (page, + migratetype); +trace_mm_page_alloc_zone_locked ( + page, order, migratetype, +pcp_allowed_order (order) && + migratetype <MIGRATE_PCPTYPES ); +return page; + } + } + } + } }/*
Signature · 1 line
2.54.0
RFC PATCH 28/40 mm: page_alloc: drive slab shrink from SPB anti-fragmentation pressure
In reply to Rik van RielGFP_KERNEL slab callers (dentry/inode/page-table caches) have no "cheap fallback" the ALLOC_HIGHORDER_OPTIONAL refusal gate can use to return NULL, and reach __rmqueue_claim/_steal whenever the tainted-SPB pool runs out of headroom. Without an external pressure release valve, sustained slab growth eventually drains the tainted pool, every clean SPB starts absorbing one taint, and fragmentation grows until equilibrium at a much higher tainted-SPB count than the workload memory-footprint warrants.
The pageblock-evacuation worker (spb_evacuate_for_order / queue_spb_evacuate) already runs from these pressure points, but it can only consolidate movable pages out of tainted SPBs. Slab content stranded in tainted SPBs blocks free pageblocks from re-coalescing and forces new taints when movable supply runs out.
Add a parallel slab-shrink mechanism that mirrors the evacuation
infrastructure: a per-pgdat irq_work that bridges from allocator-lock context out to a workqueue, a pool of request descriptors, and queue_spb_slab_shrink() with queue_work()-native single-flight semantics (queue_work() absorbs per-alloc bursts at near-zero cost via test-and-set on WORK_STRUCT_PENDING_BIT). The worker calls shrink_slab() with the zone's nid, walking node-local shrinkers from DEF_PRIORITY toward 0 until either no shrinker reports progress or a pageblock-sized batch of objects has been freed.
Trigger sites:
* Demand, alongside the existing queue_spb_evacuate calls:
__rmqueue_smallest pre-Pass-3 when spb_tainted_walk reports saw_below_reserve; __rmqueue_claim when a non-movable claim is about to taint a clean SPB.
* Supply, unconditional at the end of spb_evacuate_for_order:
keeps headroom for the next burst when MOV supply runs out.
* Proactive high-water, on the success paths of Pass 1 SB_TAINTED / Pass 2 / 2b / 2c / 2d: when a non-movable allocation consumes from a tainted SPB whose nr_free_pages has fallen below spb_tainted_reserve worth of pages. Demand-trigger placement alone is too late -- tainted SPBs can keep absorbing pressure for tens of minutes before exhaustion, by which point the only option left is to taint a fresh SPB.
The proactive high-water and end-of-spb_evacuate_for_order triggers share a helper, spb_react_to_tainted_alloc(), with the per-SPB defrag worker -- since both pressure-release mechanisms apply to the same tainted-SPB state, the helper invokes spb_maybe_start_defrag() alongside queue_spb_slab_shrink() under the same high-water gate. The defrag worker's own cooldown gate inside spb_needs_defrag() makes this cheap to call from every relevant success path.
A last-chance defrag walk runs just before the Pass 3 fall-through to a clean SPB: list_for_each_entry over zone->spb_lists[SB_TAINTED] calling spb_maybe_start_defrag() on each. This catches tainted SPBs that are stuck in expired-cooldown state because no allocator activity recently touched them (spb_update_list, the routine event-driven trigger, only fires on bucket transitions).
Per-pgdat init (init_pgdat_spb_state) wires irq_work and work_struct fields at boot via the pageblock_evacuate_init late_initcall and lazily on the memory-hotplug path; without it the trigger sites' .func != NULL gate would leave the mechanism inert system-wide.
shrink_slab is location-agnostic -- it doesn't know about SPBs -- but since slab pages live in already-tainted SPBs (that is where they were allocated), the freed pages naturally land back in the tainted pool, restoring headroom without spreading the taint to clean SPBs.
--- include/linux/mmzone.h | 12 ++ include/linux/vm_event_item.h | 5 + mm/internal.h | 2 + mm/mm_init.c | 8 + mm/page_alloc.c | 281 +++++++++++++++++++++++++++++++--- mm/vmstat.c | 2 + 6 files changed, 290 insertions(+), 20 deletions(-)
include/linux/mmzone.h +12 -0
@@ -1670,6 +1670,18 @@ typedef struct pglist_data {struct workqueue_struct *evacuate_wq;struct llist_head spb_evac_pending;struct irq_work spb_evac_irq_work; + +/* +* SPB-driven slab reclaim: single work item per pgdat (shrink_slab +* is node-scoped, so one work in-flight per node is the max). +* queue_work() gives us single-flight semantics for free -- fresh +* triggers no-op while a pass is in progress. +* +* irq_work defers the queue_work() call outside the allocator's +* lock context to avoid pool->lock vs hrtimer_bases.lock inversion. +*/ +struct irq_work spb_slab_shrink_irq_work; +struct work_struct spb_slab_shrink_work;#endif /* * This is a per-node reserve of pages that are not available
include/linux/vm_event_item.h +5 -0
@@ -81,6 +81,11 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,* a clean SPB clean when a tainted SPB * still has free pageblocks */ +SPB_SLAB_SHRINK_QUEUED ,/* +* queued a deferred slab shrink to +* reclaim space inside tainted SPBs +*/ +SPB_SLAB_SHRINK_RAN ,/* slab shrink worker ran a pass */ UNEVICTABLE_PGCULLED ,/* culled to noreclaim list */ UNEVICTABLE_PGSCANNED ,/* scanned for reclaimability */ UNEVICTABLE_PGRESCUED, /* rescued from noreclaim list */
mm/internal.h +2 -0
@@ -1103,10 +1103,12 @@ void init_cma_reserved_pageblock(struct page *page);#ifdef CONFIG_COMPACTION void init_superpageblock_defrag (struct superpageblock *sb); +void init_pgdat_spb_state (pg_data_t *pgdat);void superpageblock_clear_has_movable (struct zone *zone,struct page *page);void superpageblock_set_has_movable (struct zone *zone,struct page *page);#else static inline void init_superpageblock_defrag (struct superpageblock *sb) {} +static inline void init_pgdat_spb_state (pg_data_t *pgdat) {}static inline void superpageblock_clear_has_movable (struct zone *zone,struct page *page) {} static inline void superpageblock_set_has_movable(struct zone *zone,
mm/mm_init.c +8 -0
@@ -1695,6 +1695,14 @@ void __meminit resize_zone_superpageblocks(struct zone *zone)if (!zone->superpageblocks)init_zone_spb_lists (zone); +/* +* Lazily initialize pgdat-level SPB state (evacuate_wq, evac llist, +* shrink work). pageblock_evacuate_init() is a late_initcall and +* only walks for_each_online_node, so a node that gets its first +* memory via hotplug needs this here. Idempotent. +*/ +init_pgdat_spb_state (zone->zone_pgdat); + alloc_size = new_nr_sbs *sizeof (struct superpageblock ); new_sbs =kvmalloc_node (alloc_size,GFP_KERNEL | __GFP_ZERO, nid);if (!new_sbs) {
mm/page_alloc.c +261 -20
388 lines not on this page · raw message
mm/vmstat.c +2 -0
@@ -1389,6 +1389,8 @@ const char * const vmstat_text[] = { [I(CMA_ALLOC_FAIL)] = "cma_alloc_fail", #endif [I(SPB_HIGHORDER_REFUSED)] = "spb_highorder_refused", + [I(SPB_SLAB_SHRINK_QUEUED)] = "spb_slab_shrink_queued", + [I(SPB_SLAB_SHRINK_RAN)] = "spb_slab_shrink_ran", [I(UNEVICTABLE_PGCULLED)] = "unevictable_pgs_culled", [I(UNEVICTABLE_PGSCANNED)] = "unevictable_pgs_scanned", [I(UNEVICTABLE_PGRESCUED)] = "unevictable_pgs_rescued",
Signature · 1 line
2.54.0
RFC PATCH 29/40 mm: page_reporting: walk per-superpageblock free lists
In reply to Rik van RielAfter the SPB rework, free pages live on per-superpageblock free lists (zone->superpageblocks[i].free_area[order].free_list[mt]) rather than on a single zone-level list. page_reporting_cycle() was still walking the now-empty zone-level list, so virtio-balloon free page reporting silently became a no-op on systems with superpageblocks: no pages were ever isolated, no MADV_DONTNEED hints reached the host, and any guest memory backing balloon-eligible pages stayed resident on the host.
Refactor the per-list walk into page_reporting_cycle_list() taking an explicit list_head and a pointer to the shared budget, then have page_reporting_cycle() iterate every SPB in the zone for the requested (order, mt). The budget is shared across the whole walk so a fragmented zone does not multiply the rate-limit. The zone-level shadow nr_free (maintained by __add_to_free_list / __del_page_from_free_list) is used both for the early-out and for the budget total; that shadow already sums all SPBs.
Hold the memory hotplug read lock around the SPB walk. resize_zone_superpageblocks() swaps zone->superpageblocks under zone->lock and immediately kvfree()s the old array with no RCU grace period. The helper drops zone->lock during prdev->report() (which can sleep) and resumes operating on a list_head pointer that lives inside an SPB; without get_online_mems(), that pointer can become a dangling reference if hotplug runs in the unlock window.
The zone-level fallback path is retained for zones whose SPB array has not yet been allocated (e.g. unpopulated hotplug zones).
--- mm/page_reporting.c | 149 ++++++++++++++++++++++++++------------------ 1 file changed, 90 insertions(+), 59 deletions(-)
mm/page_reporting.c +90 -59
@@ -6,6 +6,7 @@#include <linux/export.h> #include <linux/module.h> #include <linux/delay.h> +#include <linux/memory_hotplug.h> #include <linux/scatterlist.h> #include "page_reporting.h"
@@ -138,116 +139,68 @@ page_reporting_drain(struct page_reporting_dev_info *prdev, }/* -* The page reporting cycle consists of 4 stages, fill, report, drain, and -* idle. We will cycle through the first 3 stages until we cannot obtain a -* full scatterlist of pages, in that case we will switch to idle. +* Walk a single free_list (zone-level or per-superpageblock), pulling +* unreported pages into the scatterlist and calling prdev->report() each +* time the scatterlist fills. Updates *budget and *offset across calls so +* the caller can spread one budget across multiple lists (e.g. one per SPB). */ static int -page_reporting_cycle (struct page_reporting_dev_info *prdev,struct zone *zone, -unsigned int order,unsigned int mt, -struct scatterlist *sgl,unsigned int *offset) +page_reporting_cycle_list (struct page_reporting_dev_info *prdev, +struct zone *zone,struct list_head *list, +unsigned int order,struct scatterlist *sgl, +unsigned int *offset,long *budget) { -struct free_area *area = &zone->free_area[order]; -struct list_head *list = &area->free_list[mt];unsigned int page_len =PAGE_SIZE << order;struct page *page, *next; -long budget;int err =0 ; -/* -* Perform early check, if free area is empty there is -* nothing to process so we can skip this free_list. -*/ if (list_empty (list)) -return err; +return 0 ;spin_lock_irq (&zone->lock); -/* -* Limit how many calls we will be making to the page reporting -* device for this list. By doing this we avoid processing any -* given list for too long. -* -* The current value used allows us enough calls to process over a -* sixteenth of the current list plus one additional call to handle -* any pages that may have already been present from the previous -* list processed. This should result in us reporting all pages on -* an idle system in about 30 seconds. -* -* The division here should be cheap since PAGE_REPORTING_CAPACITY -* should always be a power of 2. -*/ - budget =DIV_ROUND_UP (area->nr_free,PAGE_REPORTING_CAPACITY *16 ); - -/* loop through free list adding unreported pages to sg list */ list_for_each_entry_safe (page, next, list, lru) { -/* We are going to skip over the reported pages. */ if (PageReported (page))continue ; -/* -* If we fully consumed our budget then update our -* state to indicate that we are requesting additional -* processing and exit this list. -*/ -if (budget <0 ) { +if (*budget <0 ) {atomic_set (&prdev->state,PAGE_REPORTING_REQUESTED ); next = page;break ; } -/* Attempt to pull page from list and place in scatterlist */ if (*offset) {if (!__isolate_free_page (page, order)) { next = page;break ; } -/* Add page to scatter list */ --(*offset);sg_set_page (&sgl[*offset], page, page_len,0 );continue ; } -/* -* Make the first non-reported page in the free list -* the new head of the free list before we release the -* zone lock. -*/ if (!list_is_first (&page->lru, list))list_rotate_to_front (&page->lru, list); -/* release lock before waiting on report processing */ spin_unlock_irq (&zone->lock); -/* begin processing pages in local list */ err = prdev->report (prdev, sgl,PAGE_REPORTING_CAPACITY ); -/* reset offset since the full list was reported */ *offset =PAGE_REPORTING_CAPACITY ; + (*budget)--; -/* update budget to reflect call to report function */ - budget--; - -/* reacquire zone lock and resume processing */ spin_lock_irq (&zone->lock); -/* flush reported pages from the sg list */ page_reporting_drain (prdev, sgl,PAGE_REPORTING_CAPACITY , !err); -/* -* Reset next to first entry, the old next isn't valid -* since we dropped the lock to report the pages -*/ next = list_first_entry(list, struct page, lru); -/* exit on error */ if (err)break ; } -/* Rotate any leftover pages to the head of the freelist */ if (!list_entry_is_head (next, list, lru) && !list_is_first (&next->lru, list))list_rotate_to_front (&next->lru, list);
@@ -256,6 +209,84 @@ page_reporting_cycle(struct page_reporting_dev_info *prdev, struct zone *zone,return err; } +/* +* The page reporting cycle consists of 4 stages, fill, report, drain, and +* idle. We will cycle through the first 3 stages until we cannot obtain a +* full scatterlist of pages, in that case we will switch to idle. +* +* With superpageblocks, free pages live on per-SPB free_lists rather than a +* single zone-level list, so the cycle iterates every SPB for the requested +* (order, mt). The budget is shared across the entire walk so that +* fragmented zones do not produce a budget multiplier. +*/ +static int +page_reporting_cycle (struct page_reporting_dev_info *prdev,struct zone *zone, +unsigned int order,unsigned int mt, +struct scatterlist *sgl,unsigned int *offset) +{ +long budget; +int err =0 ; + +/* +* Early exit if the per-zone shadow says there is nothing free at +* this order in any SPB. Avoids touching every SPB's list head. +*/ +if (!data_race (zone->free_area[order].nr_free)) +return 0 ; + +/* +* Limit how many calls we will be making to the page reporting +* device. By doing this we avoid processing any given (order, mt) +* for too long. +* +* The current value used allows us enough calls to process over a +* sixteenth of the current free pool plus one additional call to +* handle any pages that may have already been present from the +* previous list processed. This should result in us reporting all +* pages on an idle system in about 30 seconds. +* +* The division here should be cheap since PAGE_REPORTING_CAPACITY +* should always be a power of 2. +*/ + budget =DIV_ROUND_UP (data_race (zone->free_area[order].nr_free), +PAGE_REPORTING_CAPACITY *16 ); + +/* +* Block memory hotplug for the SPB walk. resize_zone_superpageblocks() +* swaps zone->superpageblocks under zone->lock and immediately +* kvfree()s the old array, with no RCU grace period. The helper drops +* zone->lock during prdev->report() and resumes using a list_head +* pointer into an SPB; without holding mem_hotplug_lock for read, +* that pointer can become a dangling reference into freed memory. +*/ +get_online_mems (); + +if (zone->nr_superpageblocks) { +unsigned long sb_idx, nr_sbs = zone->nr_superpageblocks; + +for (sb_idx =0 ; sb_idx < nr_sbs; sb_idx++) { +struct list_head *list = + &zone->superpageblocks[sb_idx].free_area[order].free_list[mt]; + + err =page_reporting_cycle_list (prdev, zone, list, + order, sgl, offset, + &budget); +if (err || budget <0 ) +break ; + } + }else { +/* No SPBs (e.g. unpopulated zone); fall back to zone-level list. */ +struct list_head *list = &zone->free_area[order].free_list[mt]; + + err =page_reporting_cycle_list (prdev, zone, list, order, + sgl, offset, &budget); + } + +put_online_mems (); + +return err; +} +static int page_reporting_process_zone (struct page_reporting_dev_info *prdev,struct scatterlist *sgl,struct zone *zone)
Signature · 1 line
2.54.0
RFC PATCH 30/40 mm: show_mem: collect migratetype letters from per-superpageblock lists
In reply to Rik van Rielshow_mem()'s per-order line includes a parenthesized set of letters (UME, etc.) indicating which migratetypes have free pages at that order. This was computed by checking free_area_empty() on zone->free_area[order].free_list[type]. After the SPB rework, those zone-level list heads are always empty -- free pages live on per- superpageblock lists -- so the migratetype letters never appeared.
Iterate every SPB in the zone for each order, OR'ing in any non-empty migratetype lists, with an early exit once all migratetypes have been seen. The shadow nr_free count remains correct (zone->free_area[]. nr_free is updated by __add_to_free_list / __del_page_from_free_list to sum across all SPBs).
Falls back to the zone-level free_area for zones whose SPB array has not yet been allocated.
The whole loop runs under spin_lock_irqsave(&zone->lock) without drops, so no hotplug race. Worst case work is bounded (NR_PAGE_ORDERS * MIGRATE_TYPES * nr_superpageblocks list_empty pointer compares per zone) and acceptable for a diagnostic path.
--- mm/show_mem.c | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-)
mm/show_mem.c +20 -5
@@ -367,16 +367,31 @@ static void show_free_areas(unsigned int filter, nodemask_t *nodemask, int max_zspin_lock_irqsave (&zone->lock, flags);for (order =0 ; order <NR_PAGE_ORDERS ; order++) { -struct free_area *area = &zone->free_area[order]; +unsigned long sb_idx; +unsigned long nr_lists = zone->nr_superpageblocks ? :1 ;int type; - nr[order] = area->nr_free; + nr[order] = zone->free_area[order].nr_free; total += nr[order] << order; +/* +* Collect the migratetypes present at this order. After +* the SPB rework, free pages live on per-superpageblock +* free lists, so check each SPB. Stop early once all +* migratetypes have been observed. +*/ types[order] =0 ; -for (type =0 ; type <MIGRATE_TYPES ; type++) { -if (!free_area_empty (area, type)) - types[order] |=1 << type; +for (sb_idx =0 ; sb_idx < nr_lists; sb_idx++) { +struct free_area *area = zone->nr_superpageblocks ? + &zone->superpageblocks[sb_idx].free_area[order] : + &zone->free_area[order]; + +for (type =0 ; type <MIGRATE_TYPES ; type++) { +if (!free_area_empty (area, type)) + types[order] |=1 << type; + } +if (types[order] == (1 <<MIGRATE_TYPES ) -1 ) +break ; } }spin_unlock_irqrestore (&zone->lock, flags);
Signature · 1 line
2.54.0
RFC PATCH 31/40 mm: page_alloc: per-(zone, order, mt) PASS_1 hint cache
In reply to Rik van RielPASS_1 of __rmqueue_smallest walks &zone->spb_lists[cat][full] linearly. Under steady workload on a 250 GB test system, the median walk depth was ~50 SPBs and 20-57% of allocations visited 100+ SPBs.
Cache the SPB that last satisfied a PASS_1 alloc for each (zone, order, migratetype) tuple, in two layers:
- per-zone hint (zone->sb_hint[order][mt]) -- visible to all CPUs,
serialized by zone->lock.
- per-CPU hint indexed by zone_idx -- cache-hot, contention-free. Each slot stores (zone *, sb *) because zone_idx is per-pgdat (not globally unique on NUMA); the zone-pointer check on read prevents a cross-node SPB from being handed back to the wrong zone's accounting.
Stale hints are harmless: try_alloc_from_sb_pass1() returns NULL and the standard list walk runs as before. On PASS_1 success both hints are refreshed. spb_invalidate_warm_hints() clears both arrays from resize_zone_superpageblocks() under zone->lock to prevent UAF across memory hotplug-add.
Hint hits show up in tracepoint:kmem:spb_alloc_walk as the [0, 5) bucket because n_spbs_visited stays 0; no new tracepoint needed. Skipped for migratetype >= MIGRATE_PCPTYPES (HIGHATOMIC/CMA/ISOLATE are already cheap or rare).
Measurement on the same test system with this commit applied:
median walk depth: ~50 SPBs -> ~5 tail (>=100 SPB visits): 20-57% -> 0.4% hint hit rate (n=0): -> 99%
Memory cost: ~320 B per zone + ~2.6 KB per CPU (MAX_NR_ZONES * NR_PAGE_ORDERS * MIGRATE_PCPTYPES * sizeof(slot)).
--- include/linux/mmzone.h | 11 +++ mm/internal.h | 2 + mm/mm_init.c | 8 ++ mm/page_alloc.c | 173 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 194 insertions(+)
include/linux/mmzone.h +11 -0
@@ -1111,6 +1111,17 @@ struct zone {struct list_head spb_isolated;/* fully isolated (1GB contig alloc) */ struct list_head spb_lists[__NR_SB_CATEGORIES][__NR_SB_FULLNESS]; +/* +* PASS_1 fast-path hint: most-recent SPB that satisfied a +* (order, mt) PASS_1 allocation. Stale hints are harmless -- the hint +* try-alloc just falls through to the standard list walk on miss. +* Sized for [0..NR_PAGE_ORDERS) x PCPTYPES; HIGHATOMIC/CMA/ISOLATE +* skip the hint (already cheap or rare). Invalidated by +* spb_invalidate_warm_hints() when the SPB array is resized +* (memory hotplug add). +*/ +struct superpageblock *sb_hint[NR_PAGE_ORDERS ][MIGRATE_PCPTYPES ]; +/* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */ unsigned long zone_start_pfn;
mm/internal.h +2 -0
@@ -1119,6 +1119,8 @@ static inline void superpageblock_set_has_movable(struct zone *zone,void resize_zone_superpageblocks (struct zone *zone);#endif +void spb_invalidate_warm_hints (struct zone *zone); +struct cma ;#ifdef CONFIG_CMA
mm/mm_init.c +8 -0
@@ -1837,6 +1837,14 @@ void __meminit resize_zone_superpageblocks(struct zone *zone) zone->superpageblock_base_pfn = new_sb_base; zone->spb_kvmalloced = true; +/* +* Invalidate PASS_1 hints under zone->lock so that no +* concurrent allocator (also entering __rmqueue_smallest under +* zone->lock) can dereference an old SPB pointer that is about +* to be freed below. +*/ +spb_invalidate_warm_hints (zone); +spin_unlock_irqrestore (&zone->lock, flags);/*
mm/page_alloc.c +173 -0
197 lines not on this page · raw message
Signature · 1 line
2.54.0
RFC PATCH 32/40 mm: debug: prevent infinite recursion in dump_page() with CMA
In reply to Rik van Rieldump_page() calls is_migrate_cma_folio() which expands to get_pfnblock_migratetype(&folio->page, pfn). That helper resolves the pageblock via pfn_to_pageblock(), and on !CONFIG_SPARSEMEM configurations pfn_to_pageblock() reads page_zone(page) to compute the per-zone pageblock_data offset.
When dump_page() is invoked on a page whose zone is not initialised (unavailable PFN ranges, very early boot, or a poisoned struct page), the page_zone() dereference returns garbage and a downstream VM_BUG_ON_PAGE in dump_page()'s own consistency checks fires. The BUG handler then calls dump_page() on the same page, which re-enters the same code path, hits the same BUG, and recurses until the kernel runs out of stack.
Guard the is_migrate_cma_folio() call with pfn_valid() and only resolve page_zone() once that has succeeded; only then run zone_spans_pfn() before classifying the page. dump_page() can now safely report on pages without a meaningful zone, and the "CMA" suffix is only printed if the page is genuinely in a CMA pageblock.
Found by: dump_page() called from a VM_BUG_ON_PAGE in early boot hitting a page in an unavailable range, recursing until stack exhaustion.
--- mm/debug.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-)
mm/debug.c +17 -1
@@ -73,6 +73,7 @@ static void __dump_folio(const struct folio *folio, const struct page *page, {struct address_space *mapping =folio_mapping (folio);int mapcount =atomic_read (&page->_mapcount) +1 ; +bool cma = false;char *type ="" ;if (page_mapcount_is_type (mapcount))
@@ -112,9 +113,24 @@ static void __dump_folio(const struct folio *folio, const struct page *page,* "isolate" again in the meantime, but since we are just dumping the * state for debugging, it should be fine to accept a bit of * inaccuracy here due to racing. +* +* Guard the is_migrate_cma_folio() call with pfn_valid() and +* zone_spans_pfn(). The macro calls get_pfnblock_migratetype() +* which calls get_pfnblock_flags_word() which has a VM_BUG_ON_PAGE +* for !zone_spans_pfn(). If that fires, dump_page() recurses +* infinitely. Call page_zone() only after pfn_valid() to avoid +* dereferencing uninitialized zone data during early boot. */ +#ifdef CONFIG_CMA +if (pfn_valid (pfn)) { +struct zone *zone =page_zone (page); + +if (zone_spans_pfn (zone, pfn)) + cma =is_migrate_cma_folio (folio, pfn); + } +#endif pr_warn ("%sflags: %pGp%s\n" , type, &folio->flags, -is_migrate_cma_folio (folio, pfn) ?" CMA" :"" ); + cma ?" CMA" :"" );if (page_has_type (&folio->page))pr_warn ("page_type: %x(%s)\n" , folio->page.page_type >>24 ,page_type_name (folio->page.page_type));
Signature · 1 line
2.54.0
RFC PATCH 33/40 PM: hibernate: walk per-superpageblock free lists in mark_free_pages
In reply to Rik van Rielmark_free_pages() walks the buddy allocator's free lists and calls swsusp_set_page_free() on each free page so it is omitted from the hibernation image. After the SPB rework, free pages live on per- superpageblock free lists rather than the zone-level free list, so the existing list_for_each_entry() walk over zone->free_area[order] .free_list[t] found nothing. The hibernation snapshot then treated every free page as needing to be saved, wasting image space and risking OOM during the snapshot.
Wrap the existing per-page walk in an SPB iteration loop. When the zone has no SPBs (e.g. an unpopulated hotplug zone), fall back to the zone-level free list. The whole function still runs under spin_lock_irqsave(&zone->lock) without drops, so there are no lock- order or hotplug concerns.
Build-tested as part of the full mm series; kernel/power/snapshot.o compiles cleanly in that build. An -Werror=return-type warning in enough_free_mem() exists on some configurations but is unrelated to this change and predates the SPB series.
--- kernel/power/snapshot.c | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-)
kernel/power/snapshot.c +25 -10
@@ -1270,17 +1270,32 @@ static void mark_free_pages(struct zone *zone) }for_each_migratetype_order (order, t) { -list_for_each_entry (page, - &zone->free_area[order].free_list[t], buddy_list) { -unsigned long i; - - pfn =page_to_pfn (page); -for (i =0 ; i < (1UL << order); i++) { -if (!--page_count) { -touch_nmi_watchdog (); - page_count =WD_PAGE_COUNT ; +unsigned long sb_idx; +unsigned long nr_lists = zone->nr_superpageblocks ? :1 ; + +/* +* After the SPB rework, free pages live on per-superpageblock +* free lists. Walk every SPB's list for this (order, mt) cell. +* If the zone has no SPBs (unpopulated zone), fall back to the +* zone-level list head so that any pre-SPB pages are still +* marked. +*/ +for (sb_idx =0 ; sb_idx < nr_lists; sb_idx++) { +struct list_head *list = zone->nr_superpageblocks ? + &zone->superpageblocks[sb_idx].free_area[order].free_list[t] : + &zone->free_area[order].free_list[t]; + +list_for_each_entry (page, list, buddy_list) { +unsigned long i; + + pfn =page_to_pfn (page); +for (i =0 ; i < (1UL << order); i++) { +if (!--page_count) { +touch_nmi_watchdog (); + page_count =WD_PAGE_COUNT ; + } +swsusp_set_page_free (pfn_to_page (pfn + i)); } -swsusp_set_page_free (pfn_to_page (pfn + i)); } } }
Signature · 1 line
2.54.0
Rafael J. Wysocki
maintainerRe: [RFC PATCH 33/40] PM: hibernate: walk per-superpageblock free lists in mark_free_pages
Quoted 53 lines · Rik van Riel
mark_free_pages()walks the buddy allocator's free lists and callsswsusp_set_page_free()on each free page so it is omitted from the hibernation image. After the SPB rework, free pages live on per- superpageblock free lists rather than the zone-level free list, so the existinglist_for_each_entry()walk over zone->free_area[order] .free_list[t] found nothing. The hibernation snapshot then treated every free page as needing to be saved, wasting image space and risking OOM during the snapshot.Wrap the existing per-page walk in an SPB iteration loop. When the zone has no SPBs (e.g. an unpopulated hotplug zone), fall back to the zone-level free list. The whole function still runs under
spin_lock_irqsave(&zone->lock)without drops, so there are no lock- order or hotplug concerns.Build-tested as part of the full mm series;
kernel/power/snapshot.ocompiles cleanly in that build. An -Werror=return-type warning inenough_free_mem()exists on some configurations but is unrelated to this change and predates the SPB series.Cc Rafael J. Wysocki <[email protected]>Cc Len Brown <[email protected]>Cc Pavel Machek <[email protected]>Signed-off-by Rik van Riel <[email protected]>Assisted-by Claude:claude-opus-4.7 syzkaller--- kernel/power/snapshot.c | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-)kernel/power/snapshot.c +5
-9@@ -1270,17 +1270,32 @@ static void mark_free_pages(struct zone *zone) }for_each_migratetype_order (order, t) { -list_for_each_entry (page, - &zone->free_area[order].free_list[t], buddy_list) { -unsigned long i; - - pfn =page_to_pfn (page); -for (i =0 ; i < (1UL << order); i++) { -if (!--page_count) { -touch_nmi_watchdog (); - page_count =WD_PAGE_COUNT ; +unsigned long sb_idx; +unsigned long nr_lists = zone->nr_superpageblocks ? :1 ; + +/* +* After the SPB rework, free pages live on per-superpageblock
kernel/power/snapshot.c static void mark_free_pages(struct zone *zone) · line 1287
Quoted 10 lines
kernel/power/snapshot.c +10
-0+* free lists. Walk every SPB's list for this (order, mt) cell. +* If the zone has no SPBs (unpopulated zone), fall back to the +* zone-level list head so that any pre-SPB pages are still +* marked. +*/ +for (sb_idx =0 ; sb_idx < nr_lists; sb_idx++) { +struct list_head *list = zone->nr_superpageblocks ? + &zone->superpageblocks[sb_idx].free_area[order].free_list[t] : + &zone->free_area[order].free_list[t]; +
Suppose the code below goes into a separate function returning the current page_count value and taking list, buddy_list and page_cout as arguments. Say its name is do_mark_free_pages().
Quoted 6 lines
kernel/power/snapshot.c +6
-0+list_for_each_entry (page, list, buddy_list) { +unsigned long i; + + pfn =page_to_pfn (page); +for (i =0 ; i < (1UL << order); i++) { +if (!--page_count) {
kernel/power/snapshot.c static void mark_free_pages(struct zone *zone)
Quoted 10 lines
kernel/power/snapshot.c +4
-2+touch_nmi_watchdog (); + page_count =WD_PAGE_COUNT ; + } +swsusp_set_page_free (pfn_to_page (pfn + i)); } -swsusp_set_page_free (pfn_to_page (pfn + i)); } } } --
Then, what you seem to be wanting to do is roughly
if (zone->nr_superpageblocks == 0) {
do_mark_free_pages(&zone->free_area[order].free_list[t],
buddy_list, page_count);
} else {
for (sb_idx = 0; sb_idx < zone->nr_superpageblocks; sb_idx++) {
page_count =do_mark_free_pages(&zone->superpageblocks[sb_idx].free_area[order].free_list[t],
buddy_list, page_count);
}
}which would be kind of easier to follow.
RFC PATCH 34/40 btrfs: allocate eb-attached btree pages as movable
In reply to Rik van RielExtent buffer pages allocated by alloc_extent_buffer() are attached to btree_inode->i_mapping (the buffer_tree path), reach the LRU, and are served by the btree_migrate_folio aops in fs/btrfs/disk-io.c. They are migratable in practice once their owning extent buffer hits refs == 1, which happens naturally as tree roots rotate. The buddy allocator classifies them by GFP, however, and bare GFP_NOFS lands them in MIGRATE_UNMOVABLE pageblocks. The result: every btree_inode page we read in pins an unmovable pageblock from the page-superblock allocator's perspective, even though the page itself can be moved.
Add __GFP_MOVABLE to that one allocation site (alloc_extent_buffer's call to alloc_eb_folio_array). Plumb the flag through alloc_eb_folio_array → btrfs_alloc_page_array as a gfp_t extra_gfp parameter. All other call sites pass 0.
Three categories of caller stay on bare GFP_NOFS, deliberately:
- alloc_dummy_extent_buffer / btrfs_clone_extent_buffer: the resulting eb is EXTENT_BUFFER_UNMAPPED, folio->mapping stays NULL, the folios never enter LRU, never get migrate_folio aops. Tagging them __GFP_MOVABLE would violate the page allocator's migrability contract and they would defeat compaction in MOVABLE pageblocks where isolate_migratepages_block skips non-LRU non-movable_ops pages outright.
- btrfs_alloc_page_array callers in fs/btrfs/raid56.c (stripe pages), fs/btrfs/inode.c (encoded reads), fs/btrfs/ioctl.c (uring encoded reads), fs/btrfs/relocation.c (relocation buffers): same contract violation. raid56 stripe_pages additionally persist in the stripe cache (RBIO_CACHE_SIZE=1024) well beyond a single I/O, so they are not transient enough to hand-wave the contract.
- btrfs_alloc_folio_array caller in fs/btrfs/scrub.c (stripe folios): same -- stripe->folios[] are private buffers freed via folio_put in release_scrub_stripe.
This change targets the dominant fragmentation source observed on the page-superblock series: ~28 GB of btree_inode pages parked across many tainted superpageblocks on a 250 GB test system with btrfs root, preventing 1 GiB hugepage allocation from those regions. With the movable hint, those pages now land in MOVABLE pageblocks where the existing background defragger drains them through the standard PB_has_movable gate, no LRU-sample fallback needed.
--- fs/btrfs/extent_io.c | 69 ++++++++++++++++++++++++++++++------------- fs/btrfs/extent_io.h | 4 +-- fs/btrfs/inode.c | 2 +- fs/btrfs/ioctl.c | 2 +- fs/btrfs/raid56.c | 6 ++-- fs/btrfs/relocation.c | 2 +- fs/btrfs/scrub.c | 3 +- 7 files changed, 59 insertions(+), 29 deletions(-)
fs/btrfs/extent_io.c +49 -20
@@ -620,24 +620,33 @@ static void end_bbio_data_read(struct btrfs_bio *bbio) }/* -* Populate every free slot in a provided array with folios using GFP_NOFS. +* Populate every free slot in a provided array with folios using +* GFP_NOFS plus optional caller-supplied flags. * -* @nr_folios: number of folios to allocate -* @order: the order of the folios to be allocated -* @folio_array: the array to fill with folios; any existing non-NULL entries in -* the array will be skipped +* @nr_folios: number of folios to allocate +* @order: folio order +* @folio_array: array to fill with folios; non-NULL entries are skipped +* @extra_gfp: extra GFP flags OR'd into GFP_NOFS. The only value used +* today is __GFP_MOVABLE, which the extent-buffer real-mapping +* path (alloc_extent_buffer) passes when the resulting folios +* will be attached to btree_inode->i_mapping (added to LRU, +* served by the btree_migrate_folio aops). Pass 0 for +* everything else; folios allocated by other callers stay in +* driver-owned arrays, never reach LRU and never register +* movable_ops, so they cannot satisfy the __GFP_MOVABLE +* migrability contract. * * Return: 0 if all folios were able to be allocated; * -ENOMEM otherwise, the partially allocated folios would be freed and * the array slots zeroed */ int btrfs_alloc_folio_array (unsigned int nr_folios,unsigned int order, -struct folio **folio_array) +struct folio **folio_array,gfp_t extra_gfp) {for (int i =0 ; i < nr_folios; i++) {if (folio_array[i])continue ; - folio_array[i] =folio_alloc (GFP_NOFS , order); + folio_array[i] =folio_alloc (GFP_NOFS | extra_gfp, order);if (!folio_array[i]) goto error; }
@@ -652,21 +661,27 @@ int btrfs_alloc_folio_array(unsigned int nr_folios, unsigned int order, }/* -* Populate every free slot in a provided array with pages, using GFP_NOFS. +* Populate every free slot in a provided array with pages, using GFP_NOFS +* plus optional caller-supplied flags. * -* @nr_pages: number of pages to allocate -* @page_array: the array to fill with pages; any existing non-null entries in -* the array will be skipped -* @nofail: whether using __GFP_NOFAIL flag +* @nr_pages: number of pages to allocate +* @page_array: array to fill; non-NULL entries are skipped +* @nofail: whether to use __GFP_NOFAIL +* @extra_gfp: extra GFP flags OR'd into the base mask. The only value used +* today is __GFP_MOVABLE, which the extent-buffer real-mapping +* path passes when the resulting pages will be attached to +* btree_inode->i_mapping. See btrfs_alloc_folio_array() for +* the full migrability rationale. * * Return: 0 if all pages were able to be allocated; * -ENOMEM otherwise, the partially allocated pages would be freed and * the array slots zeroed */ int btrfs_alloc_page_array (unsigned int nr_pages,struct page **page_array, -bool nofail) +bool nofail,gfp_t extra_gfp) { -const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) :GFP_NOFS ; +const gfp_t gfp = (nofail ? (GFP_NOFS | __GFP_NOFAIL) :GFP_NOFS ) | + extra_gfp;unsigned int allocated;for (allocated =0 ; allocated < nr_pages;) {
@@ -689,14 +704,23 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,* Populate needed folios for the extent buffer. * * For now, the folios populated are always in order 0 (aka, single page). +* +* @movable: pass true only when the resulting pages will be attached to +* btree_inode->i_mapping (the alloc_extent_buffer real path). +* Cloned/dummy extent buffers (EXTENT_BUFFER_UNMAPPED) leave +* folio->mapping NULL, never enter the LRU, and never get the +* btree_migrate_folio aops, so __GFP_MOVABLE would violate the +* page-allocator's migrability contract for them. */ -static int alloc_eb_folio_array (struct extent_buffer *eb,bool nofail) +static int alloc_eb_folio_array (struct extent_buffer *eb,bool nofail, +bool movable) {struct page *page_array[INLINE_EXTENT_BUFFER_PAGES ] = {0 };int num_pages =num_extent_pages (eb);int ret; - ret =btrfs_alloc_page_array (num_pages, page_array, nofail); + ret =btrfs_alloc_page_array (num_pages, page_array, nofail, + movable ? __GFP_MOVABLE :0 );if (ret <0 )return ret;
@@ -3097,7 +3121,7 @@ struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)*/ set_bit (EXTENT_BUFFER_UNMAPPED , &new->bflags); - ret =alloc_eb_folio_array (new, false); + ret =alloc_eb_folio_array (new, false, false);if (ret) goto release_eb;
@@ -3138,7 +3162,7 @@ struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,if (!eb)return NULL ; - ret =alloc_eb_folio_array (eb, false); + ret =alloc_eb_folio_array (eb, false, false);if (ret) goto release_eb;
@@ -3491,8 +3515,13 @@ struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info, } reallocate: -/* Allocate all pages first. */ - ret =alloc_eb_folio_array (eb, true); +/* +* Allocate all pages first. These will be attached to +* btree_inode->i_mapping below (added to LRU, served by +* btree_migrate_folio), so request __GFP_MOVABLE so the +* page allocator places them in MOVABLE pageblocks. +*/ + ret =alloc_eb_folio_array (eb, true, true);if (ret <0 ) {btrfs_free_folio_state (prealloc); goto out;
fs/btrfs/extent_io.h +2 -2
@@ -387,9 +387,9 @@ void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans, struct extent_buffer *buf);int btrfs_alloc_page_array (unsigned int nr_pages,struct page **page_array, -bool nofail); +bool nofail,gfp_t extra_gfp);int btrfs_alloc_folio_array (unsigned int nr_folios,unsigned int order, -struct folio **folio_array); +struct folio **folio_array,gfp_t extra_gfp);#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS bool find_lock_delalloc_range(struct inode *inode,
fs/btrfs/inode.c +1 -1
@@ -9659,7 +9659,7 @@ ssize_t btrfs_encoded_read_regular(struct kiocb *iocb, struct iov_iter *iter, pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);if (!pages)return -ENOMEM ; - ret =btrfs_alloc_page_array (nr_pages, pages, false); + ret =btrfs_alloc_page_array (nr_pages, pages, false,0 );if (ret) { ret = -ENOMEM ; goto out;
fs/btrfs/ioctl.c +1 -1
@@ -4621,7 +4621,7 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter, pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);if (!pages)return -ENOMEM ; - ret =btrfs_alloc_page_array (nr_pages, pages,0 ); + ret =btrfs_alloc_page_array (nr_pages, pages,0 ,0 );if (ret) { ret = -ENOMEM ; goto out_fail;
fs/btrfs/raid56.c +3 -3
@@ -1123,7 +1123,7 @@ static int alloc_rbio_pages(struct btrfs_raid_bio *rbio) {int ret; - ret =btrfs_alloc_page_array (rbio->nr_pages, rbio->stripe_pages, false); + ret =btrfs_alloc_page_array (rbio->nr_pages, rbio->stripe_pages, false,0 );if (ret <0 )return ret;/* Mapping all sectors */
@@ -1138,7 +1138,7 @@ static int alloc_rbio_parity_pages(struct btrfs_raid_bio *rbio)int ret; ret =btrfs_alloc_page_array (rbio->nr_pages - data_pages, - rbio->stripe_pages + data_pages, false); + rbio->stripe_pages + data_pages, false,0 );if (ret <0 )return ret;
@@ -1732,7 +1732,7 @@ static int alloc_rbio_data_pages(struct btrfs_raid_bio *rbio)const int data_pages = rbio->nr_data * rbio->stripe_npages;int ret; - ret =btrfs_alloc_page_array (data_pages, rbio->stripe_pages, false); + ret =btrfs_alloc_page_array (data_pages, rbio->stripe_pages, false,0 );if (ret <0 )return ret;
fs/btrfs/relocation.c +1 -1
@@ -4038,7 +4038,7 @@ static int copy_remapped_data(struct btrfs_fs_info *fs_info, u64 old_addr,if (!pages)return -ENOMEM ; - ret =btrfs_alloc_page_array (nr_pages, pages,0 ); + ret =btrfs_alloc_page_array (nr_pages, pages,0 ,0 );if (ret) { ret = -ENOMEM ; goto end;
fs/btrfs/scrub.c +2 -1
@@ -369,7 +369,8 @@ static int init_scrub_stripe(struct btrfs_fs_info *fs_info,ASSERT (BTRFS_STRIPE_LEN >> min_folio_shift <=SCRUB_STRIPE_MAX_FOLIOS ); ret =btrfs_alloc_folio_array (BTRFS_STRIPE_LEN >> min_folio_shift, - fs_info->block_min_order, stripe->folios); + fs_info->block_min_order, stripe->folios, +0 );if (ret <0 ) goto error;
Signature · 1 line
2.54.0
Re: [RFC PATCH 34/40] btrfs: allocate eb-attached btree pages as movable
Quoted 5 lines · Rik van Riel
Extent buffer pages allocated by
alloc_extent_buffer()are attached tobtree_inode->i_mapping(thebuffer_treepath), reach the LRU, and are served by thebtree_migrate_folioaops infs/btrfs/disk-io.c. They are migratable in practice once their owning extent buffer hits refs == 1, which happens naturally as tree roots rotate. The buddy allocator
Small correction to a generally correct story:
every extent_buffer we have used (it is newly cowed or we have read it for some reason) will settle into a state where extent_buffer->refs == 1 and it is eligible for release_folio(). If a block gets cowed, then its extent_buffer should be fully released/freed right away, with a tricky EXTENT_BUFFER_STALE bit dance to prevent accidental reuse during this process.
So I don't think cow or trees moving around is all that relevant here.
The folios you are after are the ones which are sitting around with extent_buffer->refs == 1 and which will return 0 to release_folio(), which is any valid, non-stale extent_buffer no btrfs operation is currently using (typically referred to from a btrfs_path). These are already available to be reclaimed by memory pressure based reclaim, drop_caches, etc.
Quoted 31 lines
classifies them by GFP, however, and bare
GFP_NOFSlands them inMIGRATE_UNMOVABLEpageblocks. The result: everybtree_inodepage we read in pins an unmovable pageblock from the page-superblock allocator's perspective, even though the page itself can be moved.Add
__GFP_MOVABLEto that one allocation site (alloc_extent_buffer's call toalloc_eb_folio_array). Plumb the flag throughalloc_eb_folio_array→btrfs_alloc_page_arrayas agfp_t extra_gfpparameter. All other call sites pass 0.Three categories of caller stay on bare
GFP_NOFS, deliberately:-
alloc_dummy_extent_buffer/btrfs_clone_extent_buffer: the resulting eb isEXTENT_BUFFER_UNMAPPED,folio->mappingstays NULL, the folios never enter LRU, never getmigrate_folioaops. Tagging them__GFP_MOVABLEwould violate the page allocator's migrability contract and they would defeat compaction in MOVABLE pageblocks whereisolate_migratepages_blockskips non-LRU non-movable_ops pages outright.-
btrfs_alloc_page_arraycallers infs/btrfs/raid56.c(stripe pages),fs/btrfs/inode.c(encoded reads),fs/btrfs/ioctl.c(uring encoded reads),fs/btrfs/relocation.c(relocation buffers): same contract violation. raid56stripe_pagesadditionally persist in the stripe cache (RBIO_CACHE_SIZE=1024) well beyond a single I/O, so they are not transient enough to hand-wave the contract.-
btrfs_alloc_folio_arraycaller infs/btrfs/scrub.c(stripe folios): same -- stripe->folios[] are private buffers freed viafolio_putinrelease_scrub_stripe.
Quoted 8 lines
This change targets the dominant fragmentation source observed on the page-superblock series: ~28 GB of
btree_inodepages parked across many tainted superpageblocks on a 250 GB test system with btrfs root, preventing 1 GiB hugepage allocation from those regions. With the movable hint, those pages now land in MOVABLE pageblocks where the existing background defragger drains them through the standardPB_has_movablegate, no LRU-sample fallback needed.
I left a small code nit inline, but whether you take that suggestion or leave it, you can add:
Thanks for the patch,
Boris
Quoted 98 lines
Cc Chris Mason <[email protected]>Cc David Sterba <[email protected]>Cc Boris Burkov <[email protected]>Signed-off-by Rik van Riel <[email protected]>Assisted-by Claude:claude-opus-4.7 syzkaller--- fs/btrfs/extent_io.c | 69 ++++++++++++++++++++++++++++++------------- fs/btrfs/extent_io.h | 4 +-- fs/btrfs/inode.c | 2 +- fs/btrfs/ioctl.c | 2 +- fs/btrfs/raid56.c | 6 ++-- fs/btrfs/relocation.c | 2 +- fs/btrfs/scrub.c | 3 +- 7 files changed, 59 insertions(+), 29 deletions(-)fs/btrfs/extent_io.c +29
-14@@ -620,24 +620,33 @@ static void end_bbio_data_read(struct btrfs_bio *bbio) }/* -* Populate every free slot in a provided array with folios using GFP_NOFS. +* Populate every free slot in a provided array with folios using +* GFP_NOFS plus optional caller-supplied flags. * -* @nr_folios: number of folios to allocate -* @order: the order of the folios to be allocated -* @folio_array: the array to fill with folios; any existing non-NULL entries in -* the array will be skipped +* @nr_folios: number of folios to allocate +* @order: folio order +* @folio_array: array to fill with folios; non-NULL entries are skipped +* @extra_gfp: extra GFP flags OR'd into GFP_NOFS. The only value used +* today is __GFP_MOVABLE, which the extent-buffer real-mapping +* path (alloc_extent_buffer) passes when the resulting folios +* will be attached to btree_inode->i_mapping (added to LRU, +* served by the btree_migrate_folio aops). Pass 0 for +* everything else; folios allocated by other callers stay in +* driver-owned arrays, never reach LRU and never register +* movable_ops, so they cannot satisfy the __GFP_MOVABLE +* migrability contract. * * Return: 0 if all folios were able to be allocated; * -ENOMEM otherwise, the partially allocated folios would be freed and * the array slots zeroed */ int btrfs_alloc_folio_array (unsigned int nr_folios,unsigned int order, -struct folio **folio_array) +struct folio **folio_array,gfp_t extra_gfp) {for (int i =0 ; i < nr_folios; i++) {if (folio_array[i])continue ; - folio_array[i] =folio_alloc (GFP_NOFS , order); + folio_array[i] =folio_alloc (GFP_NOFS | extra_gfp, order);if (!folio_array[i]) goto error; }@@ -652,21 +661,27 @@ int btrfs_alloc_folio_array(unsigned int nr_folios, unsigned int order, }/* -* Populate every free slot in a provided array with pages, using GFP_NOFS. +* Populate every free slot in a provided array with pages, using GFP_NOFS +* plus optional caller-supplied flags. * -* @nr_pages: number of pages to allocate -* @page_array: the array to fill with pages; any existing non-null entries in -* the array will be skipped -* @nofail: whether using __GFP_NOFAIL flag +* @nr_pages: number of pages to allocate +* @page_array: array to fill; non-NULL entries are skipped +* @nofail: whether to use __GFP_NOFAIL +* @extra_gfp: extra GFP flags OR'd into the base mask. The only value used +* today is __GFP_MOVABLE, which the extent-buffer real-mapping +* path passes when the resulting pages will be attached to +* btree_inode->i_mapping. See btrfs_alloc_folio_array() for +* the full migrability rationale. * * Return: 0 if all pages were able to be allocated; * -ENOMEM otherwise, the partially allocated pages would be freed and * the array slots zeroed */ int btrfs_alloc_page_array (unsigned int nr_pages,struct page **page_array, -bool nofail) +bool nofail,gfp_t extra_gfp) { -const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) :GFP_NOFS ; +const gfp_t gfp = (nofail ? (GFP_NOFS | __GFP_NOFAIL) :GFP_NOFS ) | + extra_gfp;unsigned int allocated;for (allocated =0 ; allocated < nr_pages;) {@@ -689,14 +704,23 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,* Populate needed folios for the extent buffer.
fs/btrfs/extent_io.c int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array, · line 714
Quoted 10 lines
fs/btrfs/extent_io.c +7
-0* * For now, the folios populated are always in order 0 (aka, single page). +* +* @movable: pass true only when the resulting pages will be attached to +* btree_inode->i_mapping (the alloc_extent_buffer real path). +* Cloned/dummy extent buffers (EXTENT_BUFFER_UNMAPPED) leave +* folio->mapping NULL, never enter the LRU, and never get the +* btree_migrate_folio aops, so __GFP_MOVABLE would violate the +* page-allocator's migrability contract for them. */
My gut says it is nicer to just transparently pass along a gfp flag rather than a carefully documented movable boolean and let the callers do the right thing. Just a nit, I don't care strongly about it.
Quoted 34 lines
fs/btrfs/extent_io.c +6
-4-static int alloc_eb_folio_array (struct extent_buffer *eb,bool nofail) +static int alloc_eb_folio_array (struct extent_buffer *eb,bool nofail, +bool movable) {struct page *page_array[INLINE_EXTENT_BUFFER_PAGES ] = {0 };int num_pages =num_extent_pages (eb);int ret; - ret =btrfs_alloc_page_array (num_pages, page_array, nofail); + ret =btrfs_alloc_page_array (num_pages, page_array, nofail, + movable ? __GFP_MOVABLE :0 );if (ret <0 )return ret;@@ -3097,7 +3121,7 @@ struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)*/ set_bit (EXTENT_BUFFER_UNMAPPED , &new->bflags); - ret =alloc_eb_folio_array (new, false); + ret =alloc_eb_folio_array (new, false, false);if (ret) goto release_eb;@@ -3138,7 +3162,7 @@ struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,if (!eb)return NULL ; - ret =alloc_eb_folio_array (eb, false); + ret =alloc_eb_folio_array (eb, false, false);if (ret) goto release_eb;@@ -3491,8 +3515,13 @@ struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info, }
fs/btrfs/extent_io.c struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info, · line 3523
Quoted 10 lines
fs/btrfs/extent_io.c +6
-2reallocate: -/* Allocate all pages first. */ - ret =alloc_eb_folio_array (eb, true); +/* +* Allocate all pages first. These will be attached to +* btree_inode->i_mapping below (added to LRU, served by +* btree_migrate_folio), so request __GFP_MOVABLE so the +* page allocator places them in MOVABLE pageblocks. +*/
i.e., just pass GFP_MOVABLE here with a comment explaining why
Quoted 107 lines
fs/btrfs/extent_io.c +1
-0+ ret =alloc_eb_folio_array (eb, true, true);if (ret <0 ) {btrfs_free_folio_state (prealloc); goto out;fs/btrfs/extent_io.h +2
-2@@ -387,9 +387,9 @@ void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans, struct extent_buffer *buf);int btrfs_alloc_page_array (unsigned int nr_pages,struct page **page_array, -bool nofail); +bool nofail,gfp_t extra_gfp);int btrfs_alloc_folio_array (unsigned int nr_folios,unsigned int order, -struct folio **folio_array); +struct folio **folio_array,gfp_t extra_gfp);#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS bool find_lock_delalloc_range(struct inode *inode,fs/btrfs/inode.c +1
-1@@ -9659,7 +9659,7 @@ ssize_t btrfs_encoded_read_regular(struct kiocb *iocb, struct iov_iter *iter, pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);if (!pages)return -ENOMEM ; - ret =btrfs_alloc_page_array (nr_pages, pages, false); + ret =btrfs_alloc_page_array (nr_pages, pages, false,0 );if (ret) { ret = -ENOMEM ; goto out;fs/btrfs/ioctl.c +1
-1@@ -4621,7 +4621,7 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter, pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);if (!pages)return -ENOMEM ; - ret =btrfs_alloc_page_array (nr_pages, pages,0 ); + ret =btrfs_alloc_page_array (nr_pages, pages,0 ,0 );if (ret) { ret = -ENOMEM ; goto out_fail;fs/btrfs/raid56.c +3
-3@@ -1123,7 +1123,7 @@ static int alloc_rbio_pages(struct btrfs_raid_bio *rbio) {int ret; - ret =btrfs_alloc_page_array (rbio->nr_pages, rbio->stripe_pages, false); + ret =btrfs_alloc_page_array (rbio->nr_pages, rbio->stripe_pages, false,0 );if (ret <0 )return ret;/* Mapping all sectors */ @@ -1138,7 +1138,7 @@ static int alloc_rbio_parity_pages(struct btrfs_raid_bio *rbio)int ret; ret =btrfs_alloc_page_array (rbio->nr_pages - data_pages, - rbio->stripe_pages + data_pages, false); + rbio->stripe_pages + data_pages, false,0 );if (ret <0 )return ret;@@ -1732,7 +1732,7 @@ static int alloc_rbio_data_pages(struct btrfs_raid_bio *rbio)const int data_pages = rbio->nr_data * rbio->stripe_npages;int ret; - ret =btrfs_alloc_page_array (data_pages, rbio->stripe_pages, false); + ret =btrfs_alloc_page_array (data_pages, rbio->stripe_pages, false,0 );if (ret <0 )return ret;fs/btrfs/relocation.c +1
-1@@ -4038,7 +4038,7 @@ static int copy_remapped_data(struct btrfs_fs_info *fs_info, u64 old_addr,if (!pages)return -ENOMEM ; - ret =btrfs_alloc_page_array (nr_pages, pages,0 ); + ret =btrfs_alloc_page_array (nr_pages, pages,0 ,0 );if (ret) { ret = -ENOMEM ; goto end;fs/btrfs/scrub.c +2
-1@@ -369,7 +369,8 @@ static int init_scrub_stripe(struct btrfs_fs_info *fs_info,ASSERT (BTRFS_STRIPE_LEN >> min_folio_shift <=SCRUB_STRIPE_MAX_FOLIOS ); ret =btrfs_alloc_folio_array (BTRFS_STRIPE_LEN >> min_folio_shift, - fs_info->block_min_order, stripe->folios); + fs_info->block_min_order, stripe->folios, +0 );if (ret <0 ) goto error;Signature · 1 line
2.54.0
Re: [RFC PATCH 34/40] btrfs: allocate eb-attached btree pages as movable
Quoted 8 lines · Boris Burkov
Quoted 8 lines
fs/btrfs/extent_io.c +4
-0@@ -689,14 +704,23 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,* Populate needed folios for the extent buffer. * * For now, the folios populated are always in order 0 (aka, single page). +* +* @movable: pass true only when the resulting pages will be attached to +* btree_inode->i_mapping (the alloc_extent_buffer real path). +* Cloned/dummy extent buffers (EXTENT_BUFFER_UNMAPPED) leave
Quoted 8 lines
fs/btrfs/extent_io.c int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array, · line 714
Quoted 4 lines
fs/btrfs/extent_io.c +3
-0+* folio->mapping NULL, never enter the LRU, and never get the +* btree_migrate_folio aops, so __GFP_MOVABLE would violate the +* page-allocator's migrability contract for them. */ My gut says it is nicer to just transparently pass along a gfp flag rather than a carefully documented movable boolean and let the callers do the right thing. Just a nit, I don't care strongly about it.
Agreed, the GFP flags would be better and also a bit more self documenting where the functions are called. The patch is not standalone so I don't mind having the booleans, we can clean it up later to let the 40-patch series proceed.
Re: [RFC PATCH 34/40] btrfs: allocate eb-attached btree pages as movable
Quoted 26 lines · David Sterba
Quoted 16 lines · Boris Burkov
Quoted 16 lines
fs/btrfs/extent_io.c +0
-0@@ -689,14 +704,23 @@ int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array, * Populate needed folios for the extent buffer. * * For now, the folios populated are always in order 0 (aka,single page).
+ *
+ * @movable: pass true only when the resulting pages will be attached to
+ *btree_inode->i_mapping(thealloc_extent_bufferreal path).
+ * Cloned/dummy extent buffers (EXTENT_BUFFER_UNMAPPED) leave
+ *folio->mappingNULL, never enter the LRU, and never get the
+ *btree_migrate_folioaops, so__GFP_MOVABLEwouldQuoted 8 lines
Quoted 3 lines
violate the
+ * page-allocator's migrability contract for them. */My gut says it is nicer to just transparently pass along a gfp flag rather than a carefully documented movable boolean and let the callers
do the right thing. Just a nit, I don't care strongly about it.
Quoted 6 lines
Agreed, the GFP flags would be better and also a bit more self documenting where the functions are called. The patch is not standalone
so I don't mind having the booleans, we can clean it up later to let the
40-patch series proceed.
I think this patch could go in by itself. It doesn't depend on anything else in the series.
I sent it with this series mostly because it's needed to make the series work, and to provide context on why it's needed.
I'm happy to resend it with a GFP mask passed in by each caller. That would look better, indeed!
I'll send you guys a cleaned up patch this coming week.
Signature · 1 line
All Rights Reversed.
Re: [RFC PATCH 34/40] btrfs: allocate eb-attached btree pages as movable
Quoted 18 lines · Rik van Riel
Quoted 6 lines · David Sterba
Quoted 4 lines · Boris Burkov
My gut says it is nicer to just transparently pass along a gfp flag rather than a carefully documented movable boolean and let the callers
do the right thing. Just a nit, I don't care strongly about it.Quoted 6 lines
Agreed, the GFP flags would be better and also a bit more self documenting where the functions are called. The patch is not standalone
so I don't mind having the booleans, we can clean it up later to let the
40-patch series proceed.I think this patch could go in by itself. It doesn't depend on anything else in the series.
Quoted 6 lines
I sent it with this series mostly because it's needed to make the series work, and to provide context on why it's needed.
I'm happy to resend it with a GFP mask passed in by each caller. That would look better, indeed!
If you're respinning anyway ...
Every use of GFP_NOFS is a bad code smell. Filesystems should be using memalloc_nofs_save/restore. The problem is that it takes deep filesystem knowledge to understand where the memalloc_nofs_save() should start. It would be good to lift the GFP_NOFS to the callers of this function as it gets us slightly closer to being able to replace it with GFP_KERNEL in the places it's not actually needed.
ie what I'm asking for is, please don't do the 'extra_gfp' thing. Just pass in gfp from the callers and make them all pass in GFP_NOFS | __GFP_MOVABLE (or a plain GFP_NOFS) for now. Someone can come along later and change them to GFP_KERNEL later where warranted.
Re: [RFC PATCH 34/40] btrfs: allocate eb-attached btree pages as movable
Quoted 11 lines · Matthew Wilcox
Every use of
GFP_NOFSis a bad code smell. Filesystems should be using memalloc_nofs_save/restore. The problem is that it takes deep filesystem knowledge to understand where thememalloc_nofs_save()should start. It would be good to lift theGFP_NOFSto the callers of this function as it gets us slightly closer to being able to replace it withGFP_KERNELin the places it's not actually needed.ie what I'm asking for is, please don't do the '
extra_gfp' thing. Just pass in gfp from the callers and make them all pass inGFP_NOFS|__GFP_MOVABLE(or a plainGFP_NOFS) for now. Someone can come along later and change them toGFP_KERNELlater where warranted.
Note that is should be pretty trivial to just bubble it up a layer for changes like this. This will naturally gravitate to more useful places. To make it fully correct it will need manual intervention, but generally bubbling up should improve the situation.
Same for GFP_NOIO.
RFC PATCH 35/40 mm: page_alloc: refuse best-effort high-order allocs servable at lower orders
In reply to Rik van RielSeveral common high-order allocation patterns are best-effort: the caller prefers a single large page for performance but has an order-decrement fallback (or equivalent retry path) and is happy to accept failure of the high-order attempt. Examples:
kvmalloc() kmalloc attempt has a vmalloc fallback vmalloc() vm_area_alloc_pages decrements order on NULL alloc_skb_with_frags() decrements order on NULL per fragment
The convention these callers share is to strip __GFP_DIRECT_RECLAIM and set __GFP_NOWARN on the high-order attempt, signaling 'I don't want this to block on direct reclaim and I'm fine with failure being silent'.
Without further hints, get_page_from_freelist's relax sequence treats these as atomic allocs that must succeed and escalates: it adds ALLOC_NOFRAG_TAINTED_OK (allowing PASS_2/2B claim_whole_block to relabel a MOV pageblock inside a tainted SPB) and then drops ALLOC_NOFRAGMENT entirely (allowing __rmqueue_claim/_steal to taint a clean SPB). The caller's order-decrement fallback never runs because the high-order attempt 'succeeds' by tainting.
The fix at the call sites is to add __GFP_NORETRY (kmalloc_gfp_adjust already does this for kvmalloc). Generalize: in the relax sequence, before dropping NOFRAGMENT, detect the 'best-effort high-order with fallback' pattern by:
order > 0
__GFP_NOWARN set
__GFP_NOFAIL not set
__GFP_DIRECT_RECLAIM already cleared (the relax-sequence gate above)
If the tainted pool can plausibly serve a smaller (or same) order alloc on the caller's retry, refuse the current attempt instead of escalating. 'Plausibly serve' means any tainted SPB has either:
- nr_movable > 0 (MOV content exists; reclaim/migration can free pageblocks at the order the caller's retry needs, including orders >= the requested order -- e.g. four THPs in the SPB can yield an order-7 buddy for an order-7 unmovable alloc once the THPs are migrated), OR
- a free buddy on the requesting migratetype's own list at an order < requested (a smaller PASS_1 retry would succeed directly), OR
- a free buddy on the opposite non-MOV list at an order < requested (PASS_2C borrow at the smaller order would succeed) -- only relevant for UNMOV/RECL allocs.
The MOV-content check alone covers the common case cheaply (one counter read per tainted SPB) and works even when the movable memory exists at orders larger than the alloc -- which is exactly when the per-order free_list walk would miss it.
--- mm/page_alloc.c | 122 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+)
mm/page_alloc.c +122 -0
@@ -2708,6 +2708,101 @@ static inline u16 spb_tainted_reserve(const struct superpageblock *sb)return max_t (u16,SPB_TAINTED_RESERVE_MIN , sb->total_pageblocks /32 ); } +/* +* spb_tainted_can_serve_smaller - could a smaller-order @migratetype alloc +* be satisfied from any tainted SPB of @zone (now or after evac/reclaim)? +* +* "Yes" if either: +* - some tainted SPB has nr_movable > 0 (MOV content exists; reclaim or +* compaction/evac can free pageblocks at any order the caller's +* order-decrement fallback might want, including orders >= the original +* requested order -- e.g. four THPs in the SPB can yield an order-7 +* buddy for an order-7 unmovable alloc once the THPs are migrated), OR +* - some tainted SPB has a free buddy on the requesting migratetype's +* own list at an order < @order (a smaller PASS_1 retry would +* succeed directly), OR +* - some tainted SPB has a free buddy on the opposite non-MOV list at +* an order < @order (PASS_2C borrow at the smaller order would +* succeed) -- only meaningful for UNMOV/RECL allocs. +* +* Used by the get_page_from_freelist relax sequence to discriminate +* "the caller has an order-decrement fallback that the tainted pool can +* eventually serve" from "the alloc must escalate to dropping +* ALLOC_NOFRAGMENT and tainting a clean SPB". +* +* Walks zone->spb_lists[SB_TAINTED][*] under zone->lock: spb_update_list() +* mutates these same lists under zone->lock, so a lockless walk would race +* with list-cursor reassignment (list_move from a concurrent allocator +* caller could splice the cursor onto a different list and turn the walk +* into an infinite loop or crash on a corrupted list_head). Sister function +* tainted_pool_has_free() takes zone->lock for the same reason; match its +* lock discipline. Bounded by the tainted SPB count plus a constant amount +* of work per SPB. +*/ +static bool spb_tainted_can_serve_smaller (struct zone *zone, +unsigned int order, +int migratetype) +{ +struct superpageblock *sb; +unsigned long flags; +bool found = false; +int full; +unsigned int o; +int opposite_mt =-1 ; + +if (order ==0 ) +return false; + +if (migratetype ==MIGRATE_UNMOVABLE ) + opposite_mt =MIGRATE_RECLAIMABLE ; +else if (migratetype ==MIGRATE_RECLAIMABLE ) + opposite_mt =MIGRATE_UNMOVABLE ; + +spin_lock_irqsave (&zone->lock, flags); +for (full =0 ; full < __NR_SB_FULLNESS && !found; full++) { +list_for_each_entry (sb, &zone->spb_lists[SB_TAINTED ][full], + list) { +/* +* MOV content can be reclaimed (LRU folios) or +* migrated (compaction / spb_evacuate_for_order), +* making the SPB able to host a smaller (or even +* same-order) non-MOV alloc on the retry. Cheap +* counter check, covers most real cases. +*/ +if (sb->nr_movable >0 ) { + found = true; +break ; + } + +if (!sb->nr_free_pages) +continue ; + +/* +* No MOV content but there might be a same-mt or +* opposite-non-MOV buddy at a smaller order that a +* PASS_1 retry / PASS_2C borrow could serve. +*/ +for (o =0 ; o < order; o++) { +struct free_area *area = &sb->free_area[o]; + +if (!list_empty (&area->free_list[migratetype])) { + found = true; +break ; + } +if (opposite_mt >=0 && + !list_empty (&area->free_list[opposite_mt])) { + found = true; +break ; + } + } +if (found) +break ; + } + } +spin_unlock_irqrestore (&zone->lock, flags); +return found; +} +/* * High-water threshold for proactively kicking the slab shrinker. When a * non-movable allocation consumes from a tainted SPB whose total free
@@ -6303,8 +6398,35 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,*/ if (no_fallback && !defrag_mode && !(gfp_mask & __GFP_DIRECT_RECLAIM)) { +struct zone *pref =zonelist_zone (ac->preferred_zoneref); +if (gfp_mask & __GFP_NORETRY)return NULL ; + +/* +* Best-effort high-order callers convention: stripping +* __GFP_DIRECT_RECLAIM, setting __GFP_NOWARN, omitting +* __GFP_NOFAIL, and asking for a high order indicates the +* caller has an order-decrement fallback (kvmalloc's +* vmalloc fallback, vmalloc's order-decrement loop, +* alloc_skb_with_frags's order-decrement loop, ...). +* +* If the tainted-SPB pool already has a free buddy at any +* lower order on a free list a smaller retry could use, +* refuse this attempt so the caller's order-decrement +* uses that sub-pageblock space instead of forcing us to +* drop ALLOC_NOFRAGMENT and taint a clean SPB. +* +* Same intent as adding __GFP_NORETRY at every such +* caller, but applied centrally so we cover both existing +* and future callers without per-call-site fixes. +*/ +if (order >0 && (gfp_mask & __GFP_NOWARN) && + !(gfp_mask & __GFP_NOFAIL) && +spb_tainted_can_serve_smaller (pref, order, + ac->migratetype)) +return NULL ; +if (!(alloc_flags &ALLOC_NOFRAG_TAINTED_OK )) { alloc_flags |=ALLOC_NOFRAG_TAINTED_OK ; goto retry;
Signature · 1 line
2.54.0
RFC PATCH 36/40 mm: page_alloc: set ALLOC_NOFRAGMENT on alloc_frozen_pages_nolock_noprof
In reply to Rik van RielThe no-lock atomic page allocator (alloc_frozen_pages_nolock) bypasses __alloc_pages_slowpath() entirely and calls get_page_from_freelist() directly. The slowpath is where ALLOC_NOFRAGMENT is normally set for non-movable allocations, so the nolock path runs without the "skip clean SPBs" guard.
Add ALLOC_NOFRAGMENT to the alloc_flags. The function is best-effort and callers already handle NULL. The flag steers the alloc toward tainted-SPB sub-pageblock space first; for order > 0 the existing auto-refuse in the get_page_from_freelist relax sequence returns NULL when the tainted pool can serve a smaller order, and for order = 0 the alloc falls back to claiming a clean SPB only if the tainted pool is exhausted of suitable fragments.
ALLOC_NOFRAGMENT is purely a pageblock-category steering hint; it does not depend on __GFP_DIRECT_RECLAIM and does not introduce any sleeping locks, so it composes cleanly with ALLOC_TRYLOCK in NMI, hardirq, and PREEMPT_RT contexts.
--- mm/page_alloc.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-)
mm/page_alloc.c +17 -1
@@ -11525,7 +11525,23 @@ struct page *alloc_frozen_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned*/ gfp_t alloc_gfp = __GFP_NOWARN | __GFP_ZERO | __GFP_NOMEMALLOC | __GFP_COMP | gfp_flags; -unsigned int alloc_flags =ALLOC_TRYLOCK ; +/* +* ALLOC_NOFRAGMENT steers this best-effort no-lock allocation +* toward tainted-SPB sub-pageblock space before fragmenting any +* clean superpageblock. Without it, atomic kmalloc_nolock callers +* (e.g. BPF storage from sched_process_exec tracepoints) hit the +* fallback path on every PCP miss and convert a movable pageblock +* in a clean SPB to UNMOVABLE -- tainting a 1 GiB hugepage +* candidate for an order-0 atomic alloc. With NOFRAGMENT set: +* - order > 0: the get_page_from_freelist relax sequence +* auto-refuses to drop NOFRAGMENT when the tainted pool can +* serve a smaller order, returning NULL to the caller. +* - order = 0: prefers tainted-SPB fragments first; only falls +* back to claiming a clean-SPB pageblock if the tainted pool +* is exhausted of suitable fragments. +* Callers of alloc_pages_nolock() already handle NULL. +*/ +unsigned int alloc_flags =ALLOC_TRYLOCK |ALLOC_NOFRAGMENT ;struct alloc_context ac = { };struct page *page;
Signature · 1 line
2.54.0
RFC PATCH 37/40 mm: page_alloc: move spb_get_category and spb_tainted_reserve to mmzone.h
In reply to Rik van RielPure move with no semantic change. Both helpers will be needed in mm/compaction.c by upcoming SPB-skip predicates; keep a single source of truth for them in <linux/mmzone.h> alongside pfn_to_superpageblock().
--- include/linux/mmzone.h | 30 ++++++++++++++++++++++++++++++ mm/page_alloc.c | 27 +++++---------------------- 2 files changed, 35 insertions(+), 22 deletions(-)
include/linux/mmzone.h +30 -0
@@ -1296,6 +1296,36 @@ static inline struct superpageblock *pfn_to_superpageblock(struct zone *zone,return &zone->superpageblocks[idx]; } +/** +* spb_get_category - Determine if a superpageblock is clean or tainted +* @sb: superpageblock to classify +* +* A superpageblock is clean if it contains only free and movable pageblocks. +* Any unmovable, reclaimable, or reserved pageblocks make it tainted. +*/ +static inline enum sb_category spb_get_category (struct superpageblock *sb) +{ +if (sb->nr_unmovable || sb->nr_reclaimable || sb->nr_reserved) +return SB_TAINTED ; +return SB_CLEAN ; +} + +/* +* Minimum free-pageblock reserve a tainted SPB tries to maintain so the +* allocator can satisfy non-movable allocations without tainting fresh +* clean SPBs. Used by spb_tainted_reserve() as a floor for the per-SPB +* reserve; the page allocator and compaction both consult +* spb_tainted_reserve() to decide when a tainted SPB has so few free +* pageblocks left that movable allocations should look elsewhere. +* Scale with SPB size: reserve ~3% of pageblocks (minimum 4). +*/ +#define SPB_TAINTED_RESERVE_MIN 4 + +static inline u16 spb_tainted_reserve (const struct superpageblock *sb) +{ +return max_t (u16,SPB_TAINTED_RESERVE_MIN , sb->total_pageblocks /32 ); +} +enum pgdat_flags {PGDAT_WRITEBACK ,/* reclaim scanning has recently found * many pages under writeback
mm/page_alloc.c +5 -22
@@ -673,22 +673,8 @@ void superpageblock_set_has_movable(struct zone *zone, struct page *page) }#endif /* CONFIG_COMPACTION */ -/** -* spb_get_category - Determine if a superpageblock is clean or tainted -* @sb: superpageblock to classify -* -* A superpageblock is clean if it contains only free and movable pageblocks. -* Any unmovable, reclaimable, or reserved pageblocks make it tainted. -* Reserved pageblocks (memory holes) taint the superpageblock because it -* can never be used for 1GB hugepages, making it a better home for -* unmovable/reclaimable allocations. -*/ -static inline enum sb_category spb_get_category (struct superpageblock *sb) -{ -if (sb->nr_unmovable || sb->nr_reclaimable || sb->nr_reserved) -return SB_TAINTED ; -return SB_CLEAN ; -} +/* spb_get_category() lives in <linux/mmzone.h> for shared use with +* mm/compaction.c. */ /** * sb_get_fullness - Determine the fullness bucket for a superpageblock
@@ -2700,13 +2686,10 @@ static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags* * Scale with SPB size: reserve ~3% of pageblocks (minimum 4). * For a 512-pageblock SPB this gives 16 reserved pageblocks. +* +* SPB_TAINTED_RESERVE_MIN and spb_tainted_reserve() live in +* <linux/mmzone.h> for shared use with mm/compaction.c. */ -#define SPB_TAINTED_RESERVE_MIN 4 - -static inline u16 spb_tainted_reserve (const struct superpageblock *sb) -{ -return max_t (u16,SPB_TAINTED_RESERVE_MIN , sb->total_pageblocks /32 ); -}/* * spb_tainted_can_serve_smaller - could a smaller-order @migratetype alloc
Signature · 1 line
2.54.0
RFC PATCH 38/40 mm: compaction: skip empty tainted superpageblocks as migration source
In reply to Rik van RielTainted superpageblocks with nr_movable == 0 hold only unmovable and/or reclaimable pages. None are migration candidates (compaction only moves migratable pages), so scanning them is pure overhead. Bail out at the top of isolate_migratepages_block() when the current pageblock falls inside such an SPB, returning 0 without performing any per-page scan.
The caller (isolate_migratepages) then advances to the next pageblock and re-enters; each pageblock in the empty tainted SPB takes the same fast bail, so the whole SPB is effectively skipped without per-page scan work. A tainted SPB with nr_movable > 0 still gets scanned normally, preserving correctness.
--- mm/compaction.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
mm/compaction.c +21 -0
@@ -873,6 +873,27 @@ isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn, cc->migrate_pfn = low_pfn; +/* +* Fast-path: a tainted SPB with no movable content has nothing to +* migrate from this pageblock. Bail out immediately and let the +* caller move on to the next pageblock; the caller will re-enter +* this function for each subsequent pageblock in the SPB and bail +* the same way, so the whole SPB is effectively skipped without +* any per-page scan work. +*/ +if (cc->zone->nr_superpageblocks) { +struct superpageblock *sb = +pfn_to_superpageblock (cc->zone, low_pfn); + +if (sb &&spb_get_category (sb) ==SB_TAINTED && + sb->nr_movable ==0 ) { +unsigned long sb_end = +ALIGN (low_pfn +1 ,SUPERPAGEBLOCK_NR_PAGES ); + cc->migrate_pfn =min (sb_end, end_pfn); +return 0 ; + } + } +/* * Ensure that there are not too many pages isolated from the LRU * list by either parallel reclaimers or compaction. If there are,
Signature · 1 line
2.54.0
RFC PATCH 39/40 mm: compaction: respect tainted SPB reserve in destination selection
In reply to Rik van RielTainted SPBs reserve headroom (perspb_tainted_reserve()) so the allocator can satisfy non-movable allocations without tainting fresh clean SPBs. Compaction's free-page scanner can erode that reserve by picking destination pages from tainted-SPB free lists -- exactly the headroom we need for unmovable demand.
Refuse tainted-SPB pageblocks as compaction destinations once nr_free is at or below spb_tainted_reserve(sb). Clean SPBs (no reserve) stay fully eligible. This naturally biases compaction toward producing free pageblocks inside clean SPBs, where they're useful for hugepage allocation.
Combined with the source-side skip and the kcompactd wake fix, this is sufficient for kcompactd to handle clean-SPB consolidation alone.
--- mm/compaction.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
mm/compaction.c +15 -0
@@ -1503,6 +1503,21 @@ static bool suitable_migration_target(struct compact_control *cc,if (cc->ignore_block_suitable)return true; +/* +* Tainted superpageblocks reserve some headroom for non-movable +* allocations. Don't spill compaction migration into that reserve -- +* doing so erodes the headroom the allocator was holding to avoid +* tainting fresh clean SPBs. Clean SPBs (no reserve) stay eligible. +*/ +if (cc->zone->nr_superpageblocks) { +struct superpageblock *sb = +pfn_to_superpageblock (cc->zone,page_to_pfn (page)); + +if (sb &&spb_get_category (sb) ==SB_TAINTED && + sb->nr_free <=spb_tainted_reserve (sb)) +return false; + } +/* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */ if (is_migrate_movable (get_pageblock_migratetype (page)))return true;
Signature · 1 line
2.54.0
RFC PATCH 40/40 mm: page_alloc: SPB tracepoint instrumentation [DO-NOT-MERGE]
In reply to Rik van RielBundle all SPB anti-fragmentation diagnostic tracepoints into a single commit so the entire instrumentation can be dropped before upstream submission.
Tracepoint definitions (include/trace/events/kmem.h):
- spb_alloc_walk -- exit point of every __rmqueue_smallest
call with outcome and SPB visit count
- spb_alloc_fall_through -- fires when PASS 1/2/2b/2c all failed
and the allocator is about to taint a fresh clean SPB (PASS 3 / steal)
- spb_pb_taint -- every PB_has_<mt> bit transition
- spb_claim_block_refused -- try_to_claim_block exits with reason
- spb_evacuate_for_order_done -- evac phase completion summary
- spb_alloc_atomic_relax -- atomic NORETRY relaxation events
Plus enum value extensions:
- SPB_ALLOC_OUTCOME_PASS_2D = 8 extends the spb_alloc_walk outcome set for the cross-MOV borrow path.
- SPB_ATOMIC_RELAX_NOWARN_LOWER_ORDER = 3 extends the spb_alloc_atomic_relax step set for the best-effort high-order refusal path.
Tracepoint emission scaffolding and call sites (mm/page_alloc.c):
- alloc_flags parameter on __rmqueue_smallest (plumbed through all callers; passed as 0 by callers without an alloc_flags context), consumed by the trace_spb_alloc_walk emit
- n_spbs_visited counter + SPB_WALK_DONE macro in __rmqueue_smallest
- bool first/last in __spb_set_has_type / __spb_clear_has_type
- if-stmt brace + trace_spb_claim_block_refused in try_to_claim_block early-return paths (isolate, CMA, zone-boundary, noncompat-cross)
- struct zone *pref + trace_spb_alloc_atomic_relax in slowpath NORETRY/NOFRAG-tainted relaxation
- phase1_attempts/phase2_attempts counters + trace_spb_evacuate_for_order_done
- trace_printk("SB first unmovable/reclaimable") on first-of-type transitions per SPB
Designed for diagnostics only; the behavioral commits in this series provide the SPB anti-fragmentation machinery, this commit is purely instrumentation.
--- include/trace/events/kmem.h | 373 ++++++++++++++++++++++++++++++++++++ mm/page_alloc.c | 154 +++++++++++++-- 2 files changed, 514 insertions(+), 13 deletions(-)
include/trace/events/kmem.h +373 -0
@@ -266,6 +266,379 @@ TRACE_EVENT(mm_page_pcpu_drain, __entry->order, __entry->migratetype) ); +/* +* spb_pb_taint action encoding. +*/ +#define SPB_PB_TAINT_ACTION_SET 0/* set PB_has_<mt> */ +#define SPB_PB_TAINT_ACTION_CLEAR 1/* clear PB_has_<mt> */ + +#define show_spb_pb_taint_action (a) \ + __print_symbolic(a, \ + { SPB_PB_TAINT_ACTION_SET, "SET" }, \ + { SPB_PB_TAINT_ACTION_CLEAR, "CLEAR" }) + +/* +* Per-call tracepoint at every PB_has_<migratetype> bit transition. +* Distinct from the existing trace_printk lines (which only fire on +* the FIRST 0->1 transition per (SPB, migratetype)) — this fires on +* EVERY successful set/clear, and includes a flag for whether this +* call also caused a 0<->1 transition at the SPB-level counter +* (i.e., is_first_or_last for this (SPB, mt) combination). +* +* Use to answer "who is painting/clearing PB_has bits and at what +* rate?" — most useful when investigating runaway tainting or when +* Stage 1 / sync evac should be clearing bits but isn't. +* +* High volume: bounded by the rate of PB_has_* bit changes, which +* is typically per-allocation. Static-key gated to zero overhead +* when detached. +*/ +TRACE_EVENT (spb_pb_taint, + + TP_PROTO(struct page *page, int migratetype, int action, + bool is_first_or_last), + +TP_ARGS (page, migratetype, action, is_first_or_last), + +TP_STRUCT__entry ( + __field( unsigned long, pfn ) + __field( int, migratetype ) + __field( int, action ) +__field ( bool, is_first_or_last ) + ), + +TP_fast_assign ( + __entry->pfn = page_to_pfn(page); + __entry->migratetype = migratetype; + __entry->action = action; + __entry->is_first_or_last = is_first_or_last; + ), + +TP_printk ("pfn=0x%lx mt=%d action=%s first_or_last=%d" , + __entry->pfn, + __entry->migratetype, +show_spb_pb_taint_action (__entry->action), + __entry->is_first_or_last) +); + +/* +* spb_claim_block_refused reason encoding. +*/ +#define SPB_CLAIM_REFUSED_ISOLATE 0 +#define SPB_CLAIM_REFUSED_CMA 1 +#define SPB_CLAIM_REFUSED_ZONE_BOUNDARY 2 +#define SPB_CLAIM_REFUSED_CROSS_TYPE_NOT_FREE 3 +#define SPB_CLAIM_REFUSED_INSUFFICIENT_COMPAT 4 + +#define show_spb_claim_refused_reason (r) \ + __print_symbolic(r, \ + { SPB_CLAIM_REFUSED_ISOLATE, "ISOLATE" }, \ + { SPB_CLAIM_REFUSED_CMA, "CMA" }, \ + { SPB_CLAIM_REFUSED_ZONE_BOUNDARY, "ZONE_BOUNDARY" }, \ + { SPB_CLAIM_REFUSED_CROSS_TYPE_NOT_FREE, "CROSS_TYPE_NOT_FREE" }, \ + { SPB_CLAIM_REFUSED_INSUFFICIENT_COMPAT, "INSUFFICIENT_COMPAT" }) + +/* +* Per-refusal tracepoint inside try_to_claim_block. The function can +* fail for several reasons: pageblock isolated for evacuation, CMA +* pageblock, zone boundary straddle, cross-type relabel that requires +* a fully-free PB, or the heuristic threshold that says too few pages +* in the block are compatible. Visibility into WHICH reason fires how +* often informs Stage 4 design (e.g., is the heuristic gate the +* dominant cause of allocations spilling to clean SPBs?). +* +* Volume: bounded by the rate of fallback attempts, which is rare +* compared to total allocations. +*/ +TRACE_EVENT (spb_claim_block_refused, + + TP_PROTO(struct page *page, int start_type, int block_type, + int reason), + +TP_ARGS (page, start_type, block_type, reason), + +TP_STRUCT__entry ( + __field( unsigned long, pfn ) + __field( int, start_type ) + __field( int, block_type ) +__field ( int, reason ) + ), + +TP_fast_assign ( + __entry->pfn = page_to_pfn(page); + __entry->start_type = start_type; + __entry->block_type = block_type; + __entry->reason = reason; + ), + +TP_printk ("pfn=0x%lx start_mt=%d block_mt=%d reason=%s" , + __entry->pfn, + __entry->start_type, + __entry->block_type, +show_spb_claim_refused_reason (__entry->reason)) +); + +/* +* Per-call tracepoint at the exit of spb_evacuate_for_order, the +* synchronous slowpath evacuator called from +* __alloc_pages_direct_compact. Captures how many evacuate_pageblock +* calls were attempted in each phase: +* - Phase 1: coalesce within existing same-mt pageblocks +* - Phase 2: evacuate whole movable pageblocks to create free PBs +* +* Together with pgmigrate_success/pgmigrate_fail counter deltas, this +* lets us answer "is slowpath sync evacuation actually creating +* useful free pageblocks, or are the migrations EAGAINing on busy +* ebs?" — directly informs whether the per-call budget caps need +* tuning. +* +* Low volume: ~one event per direct-compact slowpath visit. +*/ +TRACE_EVENT (spb_evacuate_for_order_done, + + TP_PROTO(struct zone *zone, unsigned int order, int migratetype, + unsigned int phase1_attempts, unsigned int phase2_attempts, + bool did_evacuate), + +TP_ARGS (zone, order, migratetype, phase1_attempts, + phase2_attempts, did_evacuate), + +TP_STRUCT__entry ( + __string( name, zone->name ) + __field( unsigned int, order ) + __field( int, migratetype ) + __field( unsigned int, phase1_attempts ) + __field( unsigned int, phase2_attempts ) +__field ( bool, did_evacuate ) + ), + +TP_fast_assign ( + __assign_str(name); + __entry->order = order; + __entry->migratetype = migratetype; + __entry->phase1_attempts = phase1_attempts; + __entry->phase2_attempts = phase2_attempts; + __entry->did_evacuate = did_evacuate; + ), + +TP_printk ("zone=%s order=%u mt=%d p1=%u p2=%u did_evac=%d" , +__get_str (name), + __entry->order, + __entry->migratetype, + __entry->phase1_attempts, + __entry->phase2_attempts, + __entry->did_evacuate) +); + +/* +* spb_alloc_atomic_relax step encoding. +*/ +#define SPB_ATOMIC_RELAX_NORETRY_SKIP 0/* NORETRY caller — return NULL */ +#define SPB_ATOMIC_RELAX_ADD_TAINTED_OK 1/* add ALLOC_NOFRAG_TAINTED_OK retry */ +#define SPB_ATOMIC_RELAX_DROP_NOFRAGMENT 2/* drop ALLOC_NOFRAGMENT retry */ +#define SPB_ATOMIC_RELAX_NOWARN_LOWER_ORDER 3/* NOWARN best-effort + tainted has lower order */ + +#define show_spb_atomic_relax_step (s) \ + __print_symbolic(s, \ + { SPB_ATOMIC_RELAX_NORETRY_SKIP, "NORETRY_SKIP" }, \ + { SPB_ATOMIC_RELAX_ADD_TAINTED_OK, "ADD_TAINTED_OK" }, \ + { SPB_ATOMIC_RELAX_DROP_NOFRAGMENT, "DROP_NOFRAGMENT" }, \ + { SPB_ATOMIC_RELAX_NOWARN_LOWER_ORDER, "NOWARN_LOWER_ORDER" }) + +/* +* Per-event tracepoint at each atomic-allocation NOFRAGMENT-relaxation +* step in get_page_from_freelist. Captures NORETRY-skip exits (caller +* had a fallback so we returned NULL), and the two relaxation retries +* (add NOFRAG_TAINTED_OK; drop NOFRAGMENT entirely). +* +* Use to quantify how often each step fires under the workload. +* Validates the NORETRY-skip change is paying off. +* +* Volume: only on atomic allocs that exhaust the tainted pool — +* typically rare on a healthy system. +*/ +TRACE_EVENT (spb_alloc_atomic_relax, + + TP_PROTO(struct zone *zone, unsigned int order, int migratetype, + gfp_t gfp_mask, int step), + +TP_ARGS (zone, order, migratetype, gfp_mask, step), + +TP_STRUCT__entry ( + __string( name, zone->name ) + __field( unsigned int, order ) + __field( int, migratetype ) + __field( unsigned long, gfp_mask ) +__field ( int, step ) + ), + +TP_fast_assign ( + __assign_str(name); + __entry->order = order; + __entry->migratetype = migratetype; + __entry->gfp_mask = (__force unsigned long)gfp_mask; + __entry->step = step; + ), + +TP_printk ("zone=%s order=%u mt=%d gfp=%s step=%s" , +__get_str (name), + __entry->order, + __entry->migratetype, +show_gfp_flags (__entry->gfp_mask), +show_spb_atomic_relax_step (__entry->step)) +); + +/* +* spb_alloc_walk outcome encoding. SUCCESS_* values name which Pass +* inside __rmqueue_smallest produced the page. NO_PAGE means the +* function returned NULL (all passes failed). +*/ +#define SPB_ALLOC_OUTCOME_NO_PAGE 0 +#define SPB_ALLOC_OUTCOME_PASS_1 1/* preferred SPBs */ +#define SPB_ALLOC_OUTCOME_PASS_2 2/* claim_whole_block from tainted */ +#define SPB_ALLOC_OUTCOME_PASS_2B 3/* sub-PB claim from tainted */ +#define SPB_ALLOC_OUTCOME_PASS_2C 4/* cross-non-movable borrow */ +#define SPB_ALLOC_OUTCOME_PASS_3 5/* empty SPB (taints fresh SPB) */ +#define SPB_ALLOC_OUTCOME_PASS_4 6/* movable falls back to tainted */ +#define SPB_ALLOC_OUTCOME_ZONE_FALLBACK 7/* zone-level free_area (hotplug edge) */ +#define SPB_ALLOC_OUTCOME_PASS_2D 8/* cross-MOV borrow within tainted */ + +#define show_spb_alloc_outcome (o) \ + __print_symbolic(o, \ + { SPB_ALLOC_OUTCOME_NO_PAGE, "NO_PAGE" }, \ + { SPB_ALLOC_OUTCOME_PASS_1, "PASS_1" }, \ + { SPB_ALLOC_OUTCOME_PASS_2, "PASS_2" }, \ + { SPB_ALLOC_OUTCOME_PASS_2B, "PASS_2B" }, \ + { SPB_ALLOC_OUTCOME_PASS_2C, "PASS_2C" }, \ + { SPB_ALLOC_OUTCOME_PASS_2D, "PASS_2D" }, \ + { SPB_ALLOC_OUTCOME_PASS_3, "PASS_3" }, \ + { SPB_ALLOC_OUTCOME_PASS_4, "PASS_4" }, \ + { SPB_ALLOC_OUTCOME_ZONE_FALLBACK, "ZONE_FB" }) + +/* +* Per-allocation tracepoint at every exit of __rmqueue_smallest. +* Captures how many SPBs were walked before the allocation was +* satisfied (or determined unsatisfiable). +* +* Use this to characterize the cost of the linear spb_lists walk: +* - typical walk depth per allocation +* - per-(order, migratetype) walk-depth distribution +* - whether some workloads see pathologically long walks +* +* High-volume tracepoint (~1 emission per allocation, ~hundreds of +* thousands per second on busy systems). The static-key gating in +* the caller keeps cost at ~1 ns when the tracepoint is detached. +* When attached, expect ~100 ns/event (~10% CPU on a saturated +* allocator). Filter by outcome to reduce volume: +* tracepoint:kmem:spb_alloc_walk /args->n_spbs_visited > 5/ { ... } +*/ +TRACE_EVENT (spb_alloc_walk, + + TP_PROTO(struct zone *zone, unsigned int order, int migratetype, + unsigned int alloc_flags, int outcome, + unsigned int n_spbs_visited), + +TP_ARGS (zone, order, migratetype, alloc_flags, outcome, + n_spbs_visited), + +TP_STRUCT__entry ( + __string( name, zone->name ) + __field( unsigned int, order ) + __field( int, migratetype ) + __field( unsigned int, alloc_flags ) + __field( int, outcome ) + __field( unsigned int, n_spbs_visited ) + ), + +TP_fast_assign ( + __assign_str(name); + __entry->order = order; + __entry->migratetype = migratetype; + __entry->alloc_flags = alloc_flags; + __entry->outcome = outcome; + __entry->n_spbs_visited = n_spbs_visited; + ), + +TP_printk ("zone=%s order=%u mt=%d alloc_flags=0x%x outcome=%s n_spbs_visited=%u" , +__get_str (name), + __entry->order, + __entry->migratetype, + __entry->alloc_flags, +show_spb_alloc_outcome (__entry->outcome), + __entry->n_spbs_visited) +); + +/* +* Diagnostic tracepoint fired when __rmqueue_smallest's tainted-SPB +* passes (Pass 1/2/2b/2c) all failed and the allocator is about to +* fall through to Pass 3 (which may taint a clean SPB) or to the +* fallback paths in __rmqueue_claim/__rmqueue_steal. +* +* Captures enough state to answer "why didn't an existing tainted SPB +* absorb this allocation?": +* - n_tainted_with_buddy: count of tainted SPBs whose free_area at +* the requested order has a non-empty free_list of the requested +* migratetype. >0 means buddies WERE available — Pass 1 missed +* them somehow. 0 means the tainted pool genuinely had nothing at +* the right (order, mt). +* - walk flags: snapshot of struct spb_tainted_walk gathered during +* Pass 1's walk. saw_free_pages = any tainted SPB had any free +* pages anywhere; saw_free_pb = any tainted SPB had a wholly-free +* pageblock; saw_below_reserve = any tainted SPB was at or below +* its reserve threshold. +* +* Fires once per fall-through event, so volume scales with the rate +* at which clean-SPB tainting becomes a possibility — typically rare +* once the workload reaches steady state. +*/ +TRACE_EVENT (spb_alloc_fall_through, + + TP_PROTO(struct zone *zone, unsigned int order, int migratetype, + unsigned int alloc_flags, + unsigned int n_tainted, unsigned int n_tainted_with_buddy, + bool saw_free_pages, bool saw_free_pb, + bool saw_below_reserve), + +TP_ARGS (zone, order, migratetype, alloc_flags, + n_tainted, n_tainted_with_buddy, + saw_free_pages, saw_free_pb, saw_below_reserve), + +TP_STRUCT__entry ( + __string( name, zone->name ) + __field( unsigned int, order ) + __field( int, migratetype ) + __field( unsigned int, alloc_flags ) + __field( unsigned int, n_tainted ) + __field( unsigned int, n_tainted_with_buddy ) + __field( bool, saw_free_pages ) + __field( bool, saw_free_pb ) +__field ( bool, saw_below_reserve ) + ), + +TP_fast_assign ( + __assign_str(name); + __entry->order = order; + __entry->migratetype = migratetype; + __entry->alloc_flags = alloc_flags; + __entry->n_tainted = n_tainted; + __entry->n_tainted_with_buddy = n_tainted_with_buddy; + __entry->saw_free_pages = saw_free_pages; + __entry->saw_free_pb = saw_free_pb; + __entry->saw_below_reserve = saw_below_reserve; + ), + +TP_printk ("zone=%s order=%u mt=%d alloc_flags=0x%x n_tainted=%u n_tainted_with_buddy=%u walk=[fp=%d fpb=%d below=%d]" , +__get_str (name), + __entry->order, + __entry->migratetype, + __entry->alloc_flags, + __entry->n_tainted, + __entry->n_tainted_with_buddy, + __entry->saw_free_pages, + __entry->saw_free_pb, + __entry->saw_below_reserve) +); + TRACE_EVENT(mm_page_alloc_extfrag, TP_PROTO(struct page *page,
mm/page_alloc.c +141 -13
404 lines not on this page · raw message
Signature · 1 line
2.54.0
kernel test robot
build botRe: [RFC PATCH 40/40] mm: page_alloc: SPB tracepoint instrumentation [DO-NOT-MERGE]
kernel test robot noticed the following build errors:
Hi Johannes,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on rppt-memblock/fixes]
[cannot apply to akpm-mm/mm-everything rppt-memblock/for-next linus/master v6.16-rc1 next-20260520] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Rik-van-Riel/mm-page_alloc-replace-pageblock_flags-bitmap-with-struct-pageblock_data/20260520-231340 base: https://git.kernel.org/pub/scm/linux/kernel/git/rppt/memblock.git fixes patch link: https://lore.kernel.org/r/20260520150018.2491267-41-riel%40surriel.com patch subject: [RFC PATCH 40/40] mm: page_alloc: SPB tracepoint instrumentation [DO-NOT-MERGE] config: i386-allnoconfig-bpf (https://download.01.org/0day-ci/archive/20260521/[email protected]/config) compiler: gcc-14 (Debian 14.2.0-19) 14.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260521/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All error/warnings (new ones prefixed by >>):
In file included from kernel/fork.c:120:
kernel/../mm/internal.h: In function 'pfn_to_pageblock':
>> kernel/../mm/internal.h:824:37: error: invalid use of undefined type 'struct pageblock_data'
824 | return &zone->pageblock_data[idx];
| ^
--
In file included from mm/filemap.c:54:
mm/internal.h: In function 'pfn_to_pageblock':
>> mm/internal.h:824:37: error: invalid use of undefined type 'struct pageblock_data'
824 | return &zone->pageblock_data[idx];
| ^
--
In file included from mm/mm_init.c:35:
mm/internal.h: In function 'pfn_to_pageblock':
>> mm/internal.h:824:37: error: invalid use of undefined type 'struct pageblock_data'
824 | return &zone->pageblock_data[idx];
| ^
mm/mm_init.c: In function 'usemap_size':
>> mm/mm_init.c:1467:39: error: invalid application of 'sizeof' to incomplete type 'struct pageblock_data'
1467 | return nr_pageblocks * sizeof(struct pageblock_data);
| ^~~~~~
>> mm/mm_init.c:1468:1: warning: control reaches end of non-void function [-Wreturn-type]
1468 | }
| ^
--
In file included from mm/page_alloc.c:58:
mm/internal.h: In function 'pfn_to_pageblock':
>> mm/internal.h:824:37: error: invalid use of undefined type 'struct pageblock_data'
824 | return &zone->pageblock_data[idx];
| ^
mm/page_alloc.c: In function 'get_pfnblock_flags_word':
>> mm/page_alloc.c:329:44: error: invalid use of undefined type 'struct pageblock_data'
329 | return &pfn_to_pageblock(page, pfn)->flags;
| ^~
>> mm/page_alloc.c:330:1: warning: control reaches end of non-void function [-Wreturn-type]
330 | }
| ^
--
In file included from fs/exec.c:82:
fs/../mm/internal.h: In function 'pfn_to_pageblock':
>> fs/../mm/internal.h:824:37: error: invalid use of undefined type 'struct pageblock_data'
824 | return &zone->pageblock_data[idx];
| ^
--
In file included from lib/vsprintf.c:51:
lib/../mm/internal.h: In function 'pfn_to_pageblock':
>> lib/../mm/internal.h:824:37: error: invalid use of undefined type 'struct pageblock_data'
824 | return &zone->pageblock_data[idx];
| ^vim +824 kernel/../mm/internal.h
810
811 static inline struct pageblock_data *pfn_to_pageblock(const struct page *page,
812 unsigned long pfn)
813 {
814 #ifdef CONFIG_SPARSEMEM
815 struct mem_section *ms = __pfn_to_section(pfn);
816 unsigned long idx = (pfn & (PAGES_PER_SECTION - 1)) >> pageblock_order;
817
818 return §ion_to_usemap(ms)[idx];
819 #else
820 struct zone *zone = page_zone(page);
821 unsigned long idx;
822
823 idx = (pfn - pageblock_start_pfn(zone->zone_start_pfn)) >> pageblock_order;
> 824 return &zone->pageblock_data[idx];
825 #endif
826 }
827
--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
syzbot ci has tested the following series
syzbot ci has tested the following series
[v1] mm: reliable 1GB page allocation
https://lore.kernel.org/all/[email protected]
* [RFC PATCH 01/40] mm: page_alloc: replace pageblock_flags bitmap with struct pageblock_data
* [RFC PATCH 02/40] mm: page_alloc: per-cpu pageblock buddy allocator
* [RFC PATCH 03/40] mm: page_alloc: split-path PCP free with local-trylock + remote-llist
* [RFC PATCH 04/40] mm: mm_init: fix zone assignment for pages in unavailable ranges
* [RFC PATCH 05/40] mm: page_alloc: remove watermark boost mechanism
* [RFC PATCH 06/40] mm: page_alloc: async evacuation of stolen movable pageblocks
* [RFC PATCH 07/40] mm: page_alloc: track actual page contents in pageblock flags
* [RFC PATCH 08/40] mm: page_alloc: superpageblock metadata for 1GB anti-fragmentation
* [RFC PATCH 09/40] mm: page_alloc: support superpageblock resize for memory hotplug
* [RFC PATCH 10/40] mm: page_alloc: add superpageblock fullness lists for allocation steering
* [RFC PATCH 11/40] mm: page_alloc: steer pageblock stealing to tainted superpageblocks
* [RFC PATCH 12/40] mm: page_alloc: steer movable allocations to fullest clean superpageblocks
* [RFC PATCH 13/40] mm: page_alloc: extract claim_whole_block from try_to_claim_block
* [RFC PATCH 14/40] mm: page_alloc: add per-superpageblock free lists
* [RFC PATCH 15/40] mm: page_alloc: add background superpageblock defragmentation worker
* [RFC PATCH 16/40] mm: compaction: walk per-superpageblock free lists for migration targets
* [RFC PATCH 17/40] mm: page_alloc: superpageblock-aware contiguous and higher order allocation
* [RFC PATCH 18/40] mm: page_alloc: prevent atomic allocations from tainting clean SPBs
* [RFC PATCH 19/40] mm: page_alloc: aggressively pack non-movable allocs in tainted SPBs on large systems
* [RFC PATCH 20/40] mm: page_alloc: prefer reclaim over tainting clean superpageblocks
* [RFC PATCH 21/40] mm: page_alloc: adopt partial pageblocks from tainted superpageblocks
* [RFC PATCH 22/40] mm: page_alloc: add CONFIG_DEBUG_VM sanity checks for SPB counters
* [RFC PATCH 23/40] mm: page_alloc: targeted evacuation and dynamic reserves for tainted SPBs
* [RFC PATCH 24/40] mm: page_alloc: prevent UNMOVABLE/RECLAIMABLE mixing in pageblocks
* [RFC PATCH 25/40] mm: trigger deferred SPB evac when atomic allocs would taint a clean SPB
* [RFC PATCH 26/40] mm: page_alloc: refuse fragmenting fallback for callers with cheap fallback
* [RFC PATCH 27/40] mm: page_alloc: cross-migratetype buddy borrow within tainted SPBs
* [RFC PATCH 28/40] mm: page_alloc: drive slab shrink from SPB anti-fragmentation pressure
* [RFC PATCH 29/40] mm: page_reporting: walk per-superpageblock free lists
* [RFC PATCH 30/40] mm: show_mem: collect migratetype letters from per-superpageblock lists
* [RFC PATCH 31/40] mm: page_alloc: per-(zone, order, mt) PASS_1 hint cache
* [RFC PATCH 32/40] mm: debug: prevent infinite recursion in dump_page() with CMA
* [RFC PATCH 33/40] PM: hibernate: walk per-superpageblock free lists in mark_free_pages
* [RFC PATCH 34/40] btrfs: allocate eb-attached btree pages as movable
* [RFC PATCH 35/40] mm: page_alloc: refuse best-effort high-order allocs servable at lower orders
* [RFC PATCH 36/40] mm: page_alloc: set ALLOC_NOFRAGMENT on alloc_frozen_pages_nolock_noprof
* [RFC PATCH 37/40] mm: page_alloc: move spb_get_category and spb_tainted_reserve to mmzone.h
* [RFC PATCH 38/40] mm: compaction: skip empty tainted superpageblocks as migration source
* [RFC PATCH 39/40] mm: compaction: respect tainted SPB reserve in destination selection
* [RFC PATCH 40/40] mm: page_alloc: SPB tracepoint instrumentation [DO-NOT-MERGE]
and found the following issue:
WARNING in preempt_count_sub
Full report is available here:
https://ci.syzbot.org/series/8eef71e1-708c-40d0-9f9d-3a1bd637fc80
***
WARNING in preempt_count_sub
tree: mm-new URL: https://kernel.googlesource.com/pub/scm/linux/kernel/git/akpm/mm.git base: 4b83cbc4c15f09b000cc06f033f64b0824b6dc87 arch: amd64 compiler: Debian clang version 21.1.8 (++20251221033036+2078da43e25a-1~exp1~20251221153213.50), Debian LLD 21.1.8 config: https://ci.syzbot.org/builds/de024c89-d472-4f06-b5be-4f75f2acd1d9/config
------------[ cut here ]------------ DEBUG_LOCKS_WARN_ON(val > preempt_count()) WARNING: kernel/sched/core.c:5883 at preempt_count_sub+0x9e/0x170, CPU#0: kworker/0:0/9 Modules linked in: CPU: 0 UID: 0 PID: 9 Comm: kworker/0:0 Not tainted syzkaller #0 PREEMPT(full) Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014 Workqueue: events drain_vmap_area_work RIP: 0010:preempt_count_sub+0xa5/0x170 Code: 29 31 90 48 c1 e8 03 0f b6 04 18 84 c0 0f 85 88 00 00 00 83 3d ff 50 9d 0e 00 75 13 48 8d 3d 32 37 a0 0e 48 c7 c6 c0 f8 cb 8b <67> 48 0f b9 3a 90 eb b8 90 e8 ed d6 1d 03 85 c0 74 2f 48 c7 c0 c4 RSP: 0000:ffffc900000e7590 EFLAGS: 00010246
RAX: 0000000000000000 RBX: dffffc0000000000 RCX: ffff8881007d5880 RDX: 0000000000000000 RSI: ffffffff8bcbf8c0 RDI: ffffffff90341000 RBP: ffff888121042dc0 R08: ffffffff903129c3 R09: 1ffffffff2062538 R10: dffffc0000000000 R11: fffffbfff2062539 R12: 0000000000000020 R13: dffffc0000000000 R14: ffff888121042d80 R15: ffff88815fffbae8 FS: 0000000000000000(0000) GS:ffff88818dc7e000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: ffff88823ffff000 CR3: 000000000e74a000 CR4: 00000000000006f0 Call Trace: <TASK> free_frozen_page_commit+0x737/0x1290 __free_frozen_pages+0x873/0x1070 kasan_depopulate_vmalloc_pte+0x6d/0x90 __apply_to_page_range+0xbdc/0x1420 __kasan_release_vmalloc+0xa2/0xd0 purge_vmap_node+0x220/0x960 __purge_vmap_area_lazy+0x779/0xb40 drain_vmap_area_work+0x27/0x40 process_scheduled_works+0xb5d/0x1860 worker_thread+0xa53/0xfc0 kthread+0x388/0x470 ret_from_fork+0x514/0xb70 ret_from_fork_asm+0x1a/0x30 </TASK>
***
If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:
---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].
To test a patch for this bug, please reply with #syz test (should be on a separate line).
The patch should be attached to the email.
Note: arguments like custom git repos and branches are not supported.
Quoted 21 lines · On Wed, 20 May 2026 10:59:06 -0400 Rik van Riel <[email protected]> wrote:
Some workloads see real performance benefits from using 1GB pages, but allocating 1GB pages has often been limited to hugetlb pages that were set aside at boot time, or using CMA to keep a fixed amount of system memory off limits to the kernel.
Neither of those are great solutions, given that modern servers tend to be large, often run multiple workloads simultaneously, and each workload wants something else.
To address that issue, this patch series divides memory not just into 2MB page blocks, but into PUD sized superpageblocks, and aggressively tries to steer unmovable, reclaimable, and highatomic allocations into those superpageblocks that have already been "tainted" by such allocations.
The goal is to leave as many 1GB superpageblocks as possible used by only movable allocations, so they can be easily defragmented for either regular PMD sized huge pages, or for PUD sized huge pages.
Quoted 8 lines
Various strategies are used to accomplish this goal:
- unmovable and reclaimable allocations are preferentially done from 1GB blocks that have already been "tainted" by these allocations
- kernel allocations that can be done as one higher order allocation, or a number of smaller allocations (eg. kvmalloc) will fall back to small pages, rather than taint a new 1GB block
Hi Rik!
The comments are just based on coverletter.
Hopefully will get to review all the patches. The above one of kernel allocations falling back to small pages is interesting.
- Will it result in a performance impact as kernel allocations wont benefit from higher order allocation?
- Will this impact 2M THP allocation efficiency due to more fragmentation of kernel memory?
Quoted 4 lines
- movable allocations are preferentially done from clean 1GB blocks, which have only free and movable memory inside, starting with the fullest of these 1GB blocks
- 2MB allocations follow the same strategy
Quoted 8 lines
- 1GB allocations start with the emptiest clean 1GB block
- if a 1GB block is mixed, with some movable pageblocks, some free pageblocks, and some unmovable/reclaimable pageblocks, the system has a free threshold below which only unmovable and reclaimable allocations can be done from that 1GB block
- below that threshold, no new movable allocations are allowed in that 1GB block, while new unmovable/reclaimable allocations are still allowed
by allowed, do you mean if movable allocations fail, it will result in OOM?
Quoted 32 lines
- when a 1GB block is below that threshold, use the migration code to evacuate enough movable memory from the 1GB block to bring free memory in that 1GB block back to the threshold
These strategies together serve to concentrate unmovable and reclaimable allocations in as few 1GB blocks as possible, leaving as many 1GB blocks as possible available for movable allocations.
That enables both more extensive use of 2MB THPs and mTHPs, as well as reliable allocation of 1GB pages.
The above strategies also make the core page allocator more complicated, and slower. In order to avoid that issue, the series is built on top of Johannes's PCPBuddy series, which has the goal of reducing how often CPUs need to get pages from the zone free lists, instead relying on CPUs giving back pages to each other, based on page block ownership.
TODO:
- compaction "always" succeeds, with a success rate of 99.96% seen in traces; this sounds great, but it also results in compaction never being throttled, and compaction blowing out everybody's PCP throughlru_add_drain()calls. This needs some sort of solution.
- replace the superpageblock name with something Matthew and David both like
- find more corner cases, and fix themBased on
e1914add2799
Quoted 7 lines · Usama Arif
On Wed, 20 May 2026 10:59:06 -0400 Rik van Riel <[email protected]>
Hopefully will get to review all the patches. The above one of kernel allocations falling back to small pages is interesting.
- Will it result in a performance impact as kernel allocations wont benefit from higher order allocation?
It might! We may well need a better solution here, like spilling over earlier, but limiting the number of 1GB blocks we can spill over into simultaneously (partially used for kernel memory).
Quoted 2 lines
- Will this impact 2M THP allocation efficiency due to more fragmentation of kernel memory?
THPs come from movable memory. With more 1GB page blocks not having kernel allocations in it, THP allocations should be easier.
Quoted 15 lines
Quoted 14 lines
- movable allocations are preferentially done from clean 1GB blocks, which have only free and movable memory inside, starting with the fullest of these 1GB blocks
- 2MB allocations follow the same strategy
- 1GB allocations start with the emptiest clean 1GB block
- if a 1GB block is mixed, with some movable pageblocks, some free pageblocks, and some unmovable/reclaimable pageblocks, the system has a free threshold below which only unmovable and reclaimable allocations can be done from that 1GB block
- below that threshold, no new movable allocations are allowed in that 1GB block, while new unmovable/reclaimable allocations are still allowed
Quoted 2 lines
by allowed, do you mean if movable allocations fail, it will result in OOM?
Yes, but by that time the zone free memory should also be below the low watermark, because there should only be a few partially occupied tainted 1GB page blocks.
If the zone has 300MB low watermark, and there are 50MB tied up in those reserved-for-unmovable memory areas, it should not cause early OOMs.
I don't know if we can end up in a situation where somehow the reserved-for-unmovable memory would add up to more than the zone low watermark.
That would be bad, and if it happened we would have to add some sort of protection against that.
Signature · 1 line
All Rights Reversed.
Lorenzo Stoakes
reviewer+cc missing maintainers.
+cc Linus for general issues raised.
(Apologies, this email is VERY long, even for me)
Hi Rik,
I appreciate this is an RFC, but obviously part of that is early feedback. So if this is meant to be an (EXTREMELY) rough pre-RFC proof-of-concept then fine (however your 'todo' suggests otherwise).
And of course, before I get critical :) thank you for looking into this, it's very interesting work. I want this feature to land. BUT :)
So if this in any way resembles what you plan to send upstream un-RFC'd I need to pour a fairly large bucket of very cold water over this.
TL;DR: The series is completely unmergeable as it stands. Not even close.
Before we get into the code, please please please make sure you cc- the right people. You're doing very invasive, very major work here.
You failed to even cc- the page allocator maintainer (Vlastimil) for a series that radically alters page allocation.
MAKE SURE you cc- Vlastimil and all other maintainers and reviewers + lists on future (RFC!!) revisions of this please.
If you want to do a quiet off-list pre-RFC that's fine, but it's unforgivable to leave Vlastimil out of this even for that.
It's 30 seconds running a script (filtering for maintainers alone to save on noise):
$ scripts/get_maintainer.pl --nogit --nogit-fallback --nor [email protected] Andrew Morton <[email protected]> (maintainer:MEMORY MANAGEMENT - CORE) David Hildenbrand <[email protected]> (maintainer:MEMORY MANAGEMENT - CORE) Jonathan Corbet <[email protected]> (maintainer:DOCUMENTATION) Chris Mason <[email protected]> (maintainer:BTRFS FILE SYSTEM) David Sterba <[email protected]> (maintainer:BTRFS FILE SYSTEM) Vlastimil Babka <[email protected]> (maintainer:MEMORY MANAGEMENT - PAGE ALLOCATOR) Steven Rostedt <[email protected]> (maintainer:TRACING) Masami Hiramatsu <[email protected]> (maintainer:TRACING) "Rafael J. Wysocki" <[email protected]> (maintainer:HIBERNATION (aka Software Suspend, aka swsusp)) Oscar Salvador <[email protected]> (maintainer:MEMORY HOT(UN)PLUG) Mike Rapoport <[email protected]> (maintainer:MEMBLOCK AND MEMORY MANAGEMENT INITIALIZATION) Johannes Weiner <[email protected]> (maintainer:MEMORY MANAGEMENT - RECLAIM) [email protected] (open list:MEMORY MANAGEMENT - CORE) [email protected] (open list:DOCUMENTATION) [email protected] (open list) [email protected] (open list:BTRFS FILE SYSTEM) [email protected] (open list:TRACING) [email protected] (open list:HIBERNATION (aka Software Suspend, aka swsusp)) [email protected] (open list:MEMORY HOT(UN)PLUG) HIBERNATION (aka Software Suspend, aka swsusp) status: Supported SUSPEND TO RAM status: Supported
OK, so getting into the code. You didn't include an overall diffstat. So let's see:
$ git checkout e1914add2799 ... $ b4 shazam [email protected] ... $ git format-patch --cover-letter HEAD~40 ... $ tail -31 0000-cover-letter.patch Documentation/admin-guide/sysctl/vm.rst | 21 - Documentation/mm/physical_memory.rst | 13 +- fs/btrfs/extent_io.c | 69 +- fs/btrfs/extent_io.h | 4 +- fs/btrfs/inode.c | 2 +- fs/btrfs/ioctl.c | 2 +- fs/btrfs/raid56.c | 6 +- fs/btrfs/relocation.c | 2 +- fs/btrfs/scrub.c | 3 +- include/linux/mmzone.h | 236 +- include/linux/page-flags.h | 9 + include/linux/pageblock-flags.h | 10 + include/linux/vm_event_item.h | 10 + include/trace/events/kmem.h | 373 ++ kernel/power/snapshot.c | 35 +- mm/compaction.c | 360 +- mm/debug.c | 19 +- mm/internal.h | 39 + mm/memory_hotplug.c | 4 + mm/mm_init.c | 400 +- mm/page_alloc.c | 5064 ++++++++++++++++++++--- mm/page_reporting.c | 149 +- mm/show_mem.c | 27 +- mm/sparse.c | 3 +- mm/vmscan.c | 115 +- mm/vmstat.c | 71 +- 26 files changed, 6131 insertions(+), 915 deletions(-)
This is completely insane :) I do hope the omission of the diffstat was not to hide this, but at any rate, adding ~5,000 lines of code to page_alloc.c is a complete non-starter.
In any case I think clearly more files are required, mm/super_pageblock.c or whatever it'll be, but at any rate this much code being added to me clearly indicates something is terribly wrong here anyway.
And you added no tests whatsoever. I get that some things are hard to test in the kernel and mm, but not even an attempt? Surely you have some localised stuff that you've been using to exercise this, couldn't some of that be made into selftests?
Certainly if tests are not present, this needs to be justified in the cover letter.
(Again I appreciate this is an RFC, so perhaps those are coming.)
Anyway let's look at some of this code. Johannes's patches all look reasonable, but as soon as we start seeing:
Things start to go awry.
The series is full of extremely dense comments that contain far too much specific information to be parseable. E.g.:
+ * - owner_cpu == this CPU (or no owner): take the local PCP
+ * lock with spin_trylock and enqueue normally. The trylock + * fails only on rare local self re-entry (IRQ/NMI fires + * while the interrupted task already holds the lock) or + * while a remote drain is active; either way, fall back to + * free_one_page (or the zone-llist for FPI_TRYLOCK). No + * irqsave: the trylock cannot block on self, and remote + * CPUs never take this pcp->lock (they go via free_llist), + * so an interruption cannot deadlock against another freer.
This isn't readable. This isn't acceptable. It matches exactly what I've found LLMs to do, adding far too much detail in way that isn't human-readable.
You must redo all of these.
The patches are all quite dense. 40 patches is already far too many IMO for a series this massive, but you're also piling in tonnes of complexity in every patch.
The series should really be broken out into separate series that each slowly build up the prerequisites, so they are reviewable, parseable, can be seen in action before we move to the superblock concept and each having tests or means of asserting that they in fact function.
It feels that there are patches that indeed can be broken out sensibly like this,
e.g. https://lore.kernel.org/all/[email protected]/
(which also seems to be a fix? So maybe should be sent as one with appropriate tags?), so I think that's really the only viable way to land something this huge.
I see Usama commented on you breaking userspace, and you said you are not going to do that after all (thanks)... but it worries me that you essentially render the watermark boost broken? I don't think that's OK?
The code in general dumps large blocks of code into already existing huge functions but, even more unforgivably, turns small, maintainable, easily understood functions into completely disgusting horror shows.
For instance, __rmqueue_smallest() goes from ~20 lines to 604 lines. This is completely insane and totally unacceptable.
The code is also full of software engineering 101 fails. For instance in __rmqueue_sb_find_fallback():
if (search_cats & SB_SEARCH_PREFERRED) {
...
for (full = SB_FULL; full < __NR_SB_FULLNESS; full++) {
list_for_each_entry(sb,
&zone->spb_lists[cat][full], list) {
...
if (movable && cat == SB_TAINTED &&
sb->nr_free <= spb_tainted_reserve(sb))
continue;
...
for (i = 0; i < MIGRATE_PCPTYPES - 1; i++) {
...
if (page) {
...
}
}
}
}
}Note the mix of insane nesting AND guard clauses to make it even more indecipherable.
There's no world in which I, or any other mm maintainer (I would venture to say) want to maintain stuff like this.
A particularly concerning patch is
https://lore.kernel.org/all/[email protected]/ -
The commit messages suffer from the same issue as the comments - incredibly dense material that is far too detailed to the point of absolutely clarifying nothing. E.g.:
"The SPB list heads (zone->spb_empty and the spb_lists[cat][full] matrix)
are initialized only by setup_superpageblocks(), which is __init and runs only at boot. Hot-add into a previously-empty zone invokes init_one_superpageblock() with zero-initialized list_heads, and the inlined list_add_tail() NULL-derefs walking ->next->prev."
Is just complete word salad. It may as well be written in Egyptian hieroglyphs.
You're explaining spaghetti code using English language which makes it even more indecipherable, and not getting to the root of what you are actually doing.
Again this feels very LLM-generated. I've noticed that they tend to do this 'write out the code again but in English' stuff (and is why I do not allow LLMs to generate code or comments for me!)
You need to make commit messages and comments as succinct as possible and as clear as possible for _human beings_ :)
I also notice you have this huge blocks of word salad comments all over the place but I haven't seen a single kdoc comment (EDIT: noticed at least 1 later!)
This is a far more helpful, structured, form of describing functions and for anything put in a header you really do need to provide them.
Back to the patch. The diffstat is:
include/linux/mmzone.h | 10 + mm/compaction.c | 36 +- mm/internal.h | 10 + mm/mm_init.c | 146 +++++-- mm/page_alloc.c | 853 ++++++++++++++++++++++++++++++++--------- mm/vmstat.c | 66 ++-- 6 files changed, 883 insertions(+), 238 deletions(-)
This is (generally speaking, and certainly in this case) far, far too much for a single patch.
But as per above this is the patch where you commit what are essentially code war crimes against __rmqueue_smallest(), adding code so densely nested that you have to lop off the end of code to fit:
+ if (!movable && !is_migrate_cma(migratetype)) {
+ for (full = SB_FULL; full < __NR_SB_FULLNESS; full++) {
+ list_for_each_entry(sb,
+ &zone->spb_lists[SB_TAINTED][full], list) {
+ if (!sb->nr_free)
+ continue;
+ for (current_order = max_t(unsigned int,
+ order, pageblock_order);
+ current_order < NR_PAGE_ORDERS;
+ ++current_order) {
+ area = &sb->free_area[current_order];
+ page = get_page_from_free_area(
+ area, MIGRATE_MOVABLE);
+ if (!page)
+ continue;
+ if (get_pageblock_isolate(page))
+ continue;
+ if (is_migrate_cma(
+ get_pageblock_migratetype(page)))
+ continue;
+ page = claim_whole_block(zone, page,
+ current_order, order,
+ migratetype, MIGRATE_MOVABLE);
+ trace_mm_page_alloc_zone_locked(
+ page, order, migratetype,
+ pcp_allowed_order(order) &&
+ migratetype < MIGRATE_PCPTYPES);
+ return page;
+ }
+ }
+ }
+ }
I mean in what world are we taking code like this?
https://lore.kernel.org/all/[email protected]/ has what seem to be more human comments (good!) but then so densely nested that they have to be cropped (bad).
using smaller, separate, functions and a structured programming approach here is the way to go.
There's random smaller issues too like
https://lore.kernel.org/all/[email protected]/
seems to assume the compiler can't figure out to remove dead code (note the wild inconsistency too in comments)
You seem in some commits to undo or correct stuff you did in previous ones like
https://lore.kernel.org/all/[email protected]/
I mean perhaps I'm mistaken, but otherwise, can you instead rebase your series please?
And again we see the world salad:
+ * Maximum tainted superpageblock candidates per spb_evacuate_for_order call.
+ * Collected under zone->lock, then evacuated without it. Larger than the
+ * contig-allocation candidate cap because evacuation runs from the slowpath
+ * after reclaim/compaction failed: we need a meaningful chance of freeing a
+ * non-MOV-claimable pageblock before the slowpath escalates to dropping
+ * ALLOC_NOFRAGMENT (which lets __rmqueue_claim taint clean SPBs). Sized to
+ * scan a meaningful fraction of a typical tainted-pool population.
No kdocs, some functions/complicated logic missing any comments at all, then piles of words thrown at you like a rock.
This isn't pleasant to read, it adds no clarity, it just makes the whole thing a mess.
The code in that one is at least vaguely ok (though still too nested).
I feel like where you've manually written code the quality substantially improves, where the LLM has, the quality nosedives into oblivion.
For instance
https://lore.kernel.org/all/[email protected]/
seems to be radically better, albeit adding far too much code. So I assume that was more manual.
Stuff like
https://lore.kernel.org/all/[email protected]/
shows more of a structural issue.
In:
+ * Mark callers that have a cheap fallback if the page allocator returns
+ * NULL, so __rmqueue can refuse to taint a clean SPB when an existing
+ * tainted SPB still has free pageblocks waiting to be evacuated.
+ *
+ * Two shapes qualify:
+ *
+ * 1. Explicit fallback declaration: __GFP_NORETRY without
+ * __GFP_RETRY_MAYFAIL. Used by THP, slab high-order refill,
+ * skb_page_frag_refill on full sockets, etc.
+ *
+ * 2. Atomic-context shape: no __GFP_DIRECT_RECLAIM, no __GFP_NOMEMALLOC,
+ * no __GFP_NOFAIL. These callers (GFP_ATOMIC, GFP_NOWAIT, including + * ALLOC_HIGHATOMIC consumers) have implicit fallbacks: drop the + * packet, demote the slab order, return ENOMEM up the slowpath, + * retry from process context with GFP_KERNEL, etc. ALLOC_HIGHATOMIC + * callers also get a second crack at the dedicated MIGRATE_HIGHATOMIC + * reserve in rmqueue_buddy after __rmqueue returns NULL. + * Tainting a 1 GiB SPB to satisfy any of them is a long-lived + * fragmentation event for short-lived data.
+ *
The comment is vastly better than most, but you seem to be tying far too much up in assumptions about what particular workloads do.
This is indicative perhaps of a need to refactor to more reasonably determine these.
Adding a function and state, say, that expresses these properties would allow you to break out these concepts and have the code be self-documenting (as well as adding suitable actual documentation in comments that would be more succinct).
https://lore.kernel.org/all/[email protected]/
also shows some real issues with how you've implemented this, e.g.:
+ * Called from each PASS_1/2/2B/2C/2D success path after a successful
+ * allocation against a tainted SPB. If the SPB is below its shrink
+ * high-water mark, queue the SPB-driven slab shrink and try to start
+ * the per-SPB defrag worker. Both have their own cooldown gates inside,
+ * so this is cheap to call on every such allocation.
Now you're putting information from one gargantuan function with labels about 'passes' (rather reminiscent of VMA merge 'cases') into another.
This is a clear sign of a broken abstraction and the code not being structured correctly.
You should _express_ state encoded in these 'passes' in the _actual code_, break that code up sensibly and in a way that can be assessed for correctness, not put a bit-rotting comment on top of a function whose correctness is much harder to confirm.
Again this patch has similar issues with ridiculously dense indecipherable comments, e.g.:
+ * Last-chance defrag trigger before tainting a fresh clean SPB.
+ * Walk the tainted-SPB list and try to wake the per-SPB defrag
+ * worker on each. Catches SPBs that are stuck in expired-cooldown
+ * state because no allocator activity has touched them recently
+ * (the routine event-driven trigger from spb_update_list only
+ * fires on bucket transitions, not on every alloc). Once the
+ * cooldown has expired, spb_maybe_start_defrag() will requeue
+ * work; otherwise the gate inside spb_needs_defrag() no-ops
+ * cheaply. Bounded by nr_tainted_spbs and only runs when we are
+ * already on the slow path of fragmenting the clean pool.
The spoondecker is montiplexed in the fradupple complex dedadderated in the splunkyfied concratanator underfined by the transpontaculatoration matrixifier... :)
I think this is symptomatic of the abstraction being fundamentally broken.
If you have to establish vast swathes of cognitive context like this mid way through a huge function (again poor __rmqueue_smallest() who will never forgive you), then you've basically failed to abstract it.
Please I beg you ADD FUNCTIONS :) structured programming is a thing, struct's are a thing, abstraction is a thing :)
Pouring spaghetti into a single function is something you expect to see on a 1990's PHP website, not in core mm code ;)
https://lore.kernel.org/all/[email protected]/
seems to be another example of you just rethinking parts of what you already submitted midway through the series.
Again I might be missing something here, but if you are doing this, please just rebase your series to use $NEWIDEA from the start.
https://lore.kernel.org/all/[email protected]/ is another wall of text (newlines! Please :) but it seems like something you can break out separately no?
It seems at least reviewable :)
https://lore.kernel.org/all/[email protected]/
contains more of the same broken abstraction stuff, terrible nesting stuff, word salad stuff but is at least mercifully smaller.
https://lore.kernel.org/all/[email protected]/ is almost emblematic of the terrible (LLM I hope?) comment issue in the series. Overly dense hieroglyphs.
https://lore.kernel.org/all/[email protected]/ is another 'why didn't you rebase?' patch (again maybe I'm missing something here!)
https://lore.kernel.org/all/[email protected]/
seems more reasonable although newlines please :)
And finally
https://lore.kernel.org/all/[email protected]/ - while it's a do-not-merge patch in an RFC that changes tracing so maybe unfair, but the comments are suffering the same symptoms as the rest of the series.
~
So really, you need to start again, from scratch, and without the use of an LLM for generating code, or at least with it kept on a (very very short) leash.
And to be clear, I _want_ this concept of GB superpageblocks to land. It's a really exciting concept.
Pulling compaction kicking and screaming into 2026 stands to significantly benefit linux users and developers.
But the execution has to be _completely_ rethought.
I also worry about correctness - I simply cannot see how you can have sense of it, given the state of the code. For something so invasive and so critical to kernel functionality, code quality is simply not optional here.
Practical thoughts on how to rework the series:
- Properly abstract the concepts
- Properly separate out functions and data structures
- Add _human-readable_ comments that are succinct + clear as possible
- If a function becomes too nested, separate into smaller functions
- Add tests, if at all or in any way possible (and justify if you can't)
- Clarify commit messages, don't just rewrite code in English
- Use newlines for new paragraphs everywhere :)
- Refactor existing code in preparation for your changes
- Add a new file to contain your changes (+ add to page alloc MAINTAINERS section)
- Add kdocs for anything not static, and clearly describe static functions
- Split into separate series as much as possible, gradually building foundations for your changes
- Make everything less dense and more abstracted
In general, write the series with reviewers and other kernel developers in mind - write clear explanations in comments and commit messages, have the series slowly build to what you're implementing.
That way, we can see that correctness is maintained throughout, can review what's there sensibly, and the series becomes upstreamable.
IOW I say we take off and nuke the entire site from orbit. It's the only way to be sure :)
~
Another issue here is maintainer time - even this _extremely_ light-touch review has taken me a few hours (of my weekend :). To review it in detail would take probably DAYS of dedicated work.
In general, I'm concerned that we're going to get caught in a cycle of LLM code sent - reviewers spending hours reviewing - LLM generates new revision
- etc.
This simply isn't scalable, maintainers cannot do this in the face of the sheer quantity and complexity of code that LLMs can generate.
We are simply going to have to NAK. And that helps nobody.
Luckily for me, this isn't in a sub-(sub-)system I maintain, so I am not obliged, but I do have empathy for my fellow maintainers, and am VERY concerned about this trend.
There has recently been an absolute wave of LLM code, some acked as such (and I think you for doing so here!) but others unacknowledged entirely, and the workload, which was already too much, has risen significantly (Jon has noted the rise in commit count for instance in LWN).
Treating maintainer time as without value was already an issue, but I fear that we'll see a significant increase in maintainer stress and sadly, burnout.
As such, I feel that we will have to implement measures at some point to deprioritise/quickly dismiss such series, unfortunately.
But series from smart and capable engineers such as yourselfk who are well respected in the communityk will likely not bek and thus will suffer from this issue indefinitely.
So on that basis, I ask respectfully that you account for this when using this tooling.
(Also, I appreciate that this is an RFC, but your recent non-RFC GUP series
https://lore.kernel.org/all/[email protected]/
(revision v2 at
https://lore.kernel.org/all/[email protected]/) has all the same hallmarks as this one, so I feel this point needs to be underlined).
~
Speaking more generally across the industry, I've been reading about companies generating code blindly and running into terrible problems with software that ends up becoming totally unmanageable.
I won't tolerate this happening happening in mm, and strongly object to the concept (held by some AI proponents) that code is simply an unimportant byproduct of AI.
The kernel's code (and especially mm's) is _critically_ important, quite literally, as it forms the basis of the world's critical technical infrastructure.
I am not opposed to the use of LLMs, but they _must_ serve as tools to _assist_ experts at their job, not a means by which code bases are degraded.
~
OK with all that said - to be absolutely clear - I respect you a great deal, and I KNOW you're (much, much) better than this.
And, to repeat, this idea is very exciting and I _want_ to see this land.
But I feel you've rather let the LLM run amok and it's selling you (very, very) short, given just how smart and capable you are.
Let's try again :)
Thanks, Lorenzo
Quoted 10 lines · Lorenzo Stoakes
So really, you need to start again, from scratch, and without the use of an
LLM for generating code, or at least with it kept on a (very very short)
leash.And to be clear, I _want_ this concept of GB superpageblocks to land. It's
a really exciting concept.
That is the one reason I sent out RFC code before it is ready. I am looking for feedback on the concepts in this series.
How do people feel about splitting up the free lists, so each gigabyte (well, PUD sized) chunk of memory has its own free lists?
How can we balance the desire for higher-order kernel allocations, against the desire to preserve gigabyte sized chunks of memory that can be used for user space?
Quoted 4 lines
Pulling compaction kicking and screaming into 2026 stands to significantly
benefit linux users and developers.
That's another big question. How do we balance the desire to keep compaction overhead low with the desire to do higher order allocations almost everywhere?
Quoted 2 lines
But the execution has to be _completely_ rethought.
There's no argument there.
I am just hoping to figure out what I should be doing on a conceptual level, before figuring out how to do it cleanly.
The mess in the RFC is the result of trying something that seemed right, watching it fail in some subtle way, and trying to fix it up.
Once I know what I need to do, coming up with a cleaner implementation is very doable.
Quoted 5 lines
IOW I say we take off and nuke the entire site from orbit. It's the only
way to be sure :)
BOOM?
Quoted 5 lines
Another issue here is maintainer time - even this _extremely_ light- touch
review has taken me a few hours (of my weekend :). To review it in detail
would take probably DAYS of dedicated work.
I suspect there is a mismatch in expectations here.
I already knew this code has to be totally redone.
I was looking for feedback on the basic concepts and design in the patch series, but failed to clearly communicate that.
You provided some detailed feedback on the code, but as of yet nobody has really provided any opinions on things like whether it is desirable at all to have the free lists per gigablock, or whether we need to come up with some totally different approach.
How do we better communicate that kind of thing in the future?
Is that something to spell out more clearly in the cover letter?
Is that kind of feedback something developers could even reasonably ask for? (if not, how do we figure out what maintainers want?)
Signature · 1 line
All Rights Reversed.
Lorenzo Stoakes
reviewerTL;DR - please don't send unfiltered LLM code to list _at all_. If you want to share it, link to a repo.
Quoted 3 lines · Rik van Riel
That is the one reason I sent out RFC code before it is ready. I am looking for feedback on the concepts in this series.
...
Quoted 2 lines
Once I know what I need to do, coming up with a cleaner implementation is very doable.
...
Quoted 3 lines
The mess in the RFC is the result of trying something that seemed right, watching it fail in some subtle way, and trying to fix it up.
...
Quoted 3 lines
Quoted 1 line
But the execution has to be _completely_ rethought.
There's no argument there.
...
Quoted 9 lines
Quoted 5 lines
Another issue here is maintainer time - even this _extremely_ light- touch
review has taken me a few hours (of my weekend :). To review it in detail
would take probably DAYS of dedicated work.I suspect there is a mismatch in expectations here.
I already knew this code has to be totally redone.
I'm glad we are in agreement on this :)
But in general I feel you have sent this and at least one other series like this without being as clear as you should have been.
I hate to belabour the point but just to be clear:
* You label one patch [DO-NOT-MERGE], but none of the others (implying they are candidates for being merged) [0] and the cover letter has TODOs, including trivia like naming, but nothing about the code.
* You sent a non-RFC series with identical code quality issues [1] recently.
* Until I pointed it out, you were responding to other review here as if the series was genuinely was intended for (eventual) merge:
- "This is a userspace-visible removal. Writes to /proc/sys/vm/watermark_boost_factor will now return -ENOENT instead of being accepted, breaking userspace." [2]
<-: "I'll just drop this patch for now." [3]
- "I left a small code nit inline, but whether you take that suggestion or leave it, you can add Reviewed-by: ..." [4]
<-: "I sent it with this series mostly because it's needed to make the series work, and to provide context on why it's needed. I'm happy to resend it with a GFP mask passed in by each caller. That would look better, indeed!" [5]
So to be concrete, if you send really rough code, Use [pre-RFC] or [DO NOT MERGE] (on the series as a whole) to make that clear and say so in the cover letter VERY VERY clearly.
Or, you can put it in a repo somewhere and link it in an email discussing the concepts (like I did with scalable CoW for instance).
Also if people respond to the series as if it isn't pre-RFC, I'd suggest in your replies saying something like 'I intend to completely rework all this anyway' or something like that! :)
Quoted 7 lines
How do people feel about splitting up the free lists, so each gigabyte (well, PUD sized) chunk of memory has its own free lists?
How can we balance the desire for higher-order kernel allocations, against the desire to preserve gigabyte sized chunks of memory that can be used for user space?
...
Quoted 5 lines
That's another big question. How do we balance the desire to keep compaction overhead low with the desire to do higher order allocations almost everywhere?
Quoted 1 line
...
Quoted 5 lines
I am just hoping to figure out what I should be doing on a conceptual level, before figuring out how to do it cleanly.
...
Quoted 15 lines
I was looking for feedback on the basic concepts and design in the patch series, but failed to clearly communicate that.
You provided some detailed feedback on the code, but as of yet nobody has really provided any opinions on things like whether it is desirable at all to have the free lists per gigablock, or whether we need to come up with some totally different approach.
How do we better communicate that kind of thing in the future?
Quoted 6 lines
Is that something to spell out more clearly in the cover letter?
Is that kind of feedback something developers could even reasonably ask for? (if not, how do we figure out what maintainers want?)
As above, firstly make it clear that the code you are sending for review is not to be reviewed so people don't waste highly contended maintainer time on that! :)
Also, you didn't respond to my point regarding cc'ing the right people - but that's clearly something you need to get right if you want this kind of feedback to start with.
For instance, you didn't cc- the page allocator maintainer (Vlastimil) on a series that is fundamentally changing the page allocator. That's not going to help with feedback.
In general, this area of the page allocator and compaction isn't my specialism in the kernel so I can't give you the in-depth feedback you need on that.
But I do have thoughts in general as to how to achieve what you want here:
Firstly - you should try to summarise what you're doing here and what you're changing alongside the trade-offs as clearly as you can in the cover letter.
Then highlight what it is you need feedback on, broken out into clear questions or points that make it easy for people to respond to.
And _you have already done this_ in your reply here:
* "How do people feel about splitting up the free lists, so each gigabyte (well, PUD sized) chunk of memory has its own free lists?"
* "How can we balance the desire for higher-order kernel allocations, against the desire to preserve gigabyte sized chunks of memory that can be used for user space?"
* "How do we balance the desire to keep compaction overhead low with the desire to do higher order allocations almost everywhere?"
I think a really good way of doing this would be to start out with something like:
Right now compaction often fails to achieve what we need, with fragmentation occurring anyway and (for instance) THP stalling on the availability of higher order folios.
etc. etc.
Summarising _the problem_.
Then a section about your proposed solution, e.g.:
I propose a means by which we proactively achieve gigabyte-sized pageblocks with logic which maintains these as physically contiguous under both ordinary and contended workloads
Then list out the "secret sauce" of your approach, e.g.:
This works by arranging memory such that unmovable allocations are grouped at <blah blah blah> etc.
Then raise your questions e.g.:
I'd like to ask the community - how do people feel about splitting up the free lists, so each gigabyte (well, PUD sized) chunk of memory has its own free lists? <etc. etc.>
Then make it clear whether this is an RFC that is ready for primetime or not:
This series is simply intended as a proof-of-concept - PLEASE DO NOT REVIEW THE CODE per-se, but rather comment on the concepts!
(And obviously as above, if that _is_ what you intend, underline it with [DO NOT MERGE] or [pre-RFC] or something like that).
I'd also very strongly suggest (as I did in my original reply) breaking out parts that can be broken out as prerequisite series.
If you're doing something good or useful _anyway_ then just send that separately first, and have later work rely on the earlier work.
There's no rush, this is huge and will take time.
A final KEY point:
NEVER submit unfiltered code generated by an LLMs to the list in _any_ form. If you want people to access code like that to test or something, then put it in a remote repo and link to it.
The code is SO overly complicated and SO messy that it's really difficult for people to understand what's actually going on.
At the heart of what you need here is CLARITY.
You need to CLEARLY communicate what it is you're doing so busy maintainers can examine it. That's the _only_ way you're going to get something like this merged.
The LLM-generated code is so awful that ain't nobody got the time to try to understand what it's doing.
The workload for this really has to be on submitters, not maintainers.
And what you've done, even if not intended, is workslopping, and that's really not acceptable. Quoting the kernel process on tool-generated content [6]:
"If tools permit you to generate a contribution automatically, expect additional scrutiny in proportion to how much of it was generated.
As with the output of any tooling, the result may be incorrect or inappropriate. You are expected to understand and to be able to defend everything you submit. If you are unable to do so, then do not submit the resulting changes.
If you do so anyway, maintainers are entitled to reject your series without detailed review."
As per this and my previous reply, AI slop doesn't scale, even as an RFC - I won't have time to reply like this in future, and we will just have to reject your series out of hand, which helps nobody.
Quoted 4 lines
--
All Rights Reversed.
Thanks, Lorenzo
[0]:https://lore.kernel.org/all/[email protected]/ [1]:https://lore.kernel.org/linux-mm/[email protected]/ [2]:https://lore.kernel.org/all/[email protected]/ [3]:https://lore.kernel.org/all/[email protected]/ [4]:https://lore.kernel.org/all/[email protected]/ [5]:https://lore.kernel.org/all/[email protected]/ [6]:https://docs.kernel.org/process/generated-content.html
Vlastimil Babka (SUSE)
maintainerQuoted 55 lines · Lorenzo Stoakes
TL;DR - please don't send unfiltered LLM code to list
_atall_. If you want to share it, link to a repo.Quoted 3 lines · Rik van Riel
That is the one reason I sent out RFC code before it is ready. I am looking for feedback on the concepts in this series.
...
Quoted 2 lines
Once I know what I need to do, coming up with a cleaner implementation is very doable.
...
Quoted 3 lines
The mess in the RFC is the result of trying something that seemed right, watching it fail in some subtle way, and trying to fix it up.
...
Quoted 3 lines
Quoted 1 line
But the execution has to be _completely_ rethought.
There's no argument there.
...
Quoted 9 lines
Quoted 5 lines
Another issue here is maintainer time - even this _extremely_ light- touch
review has taken me a few hours (of my weekend :). To review it in detail
would take probably DAYS of dedicated work.I suspect there is a mismatch in expectations here.
I already knew this code has to be totally redone.
I'm glad we are in agreement on this :)
But in general I feel you have sent this and at least one other series like this without being as clear as you should have been.
I hate to belabour the point but just to be clear:
* You label one patch [DO-NOT-MERGE], but none of the others (implying they are candidates for being merged) [0] and the cover letter has TODOs, including trivia like naming, but nothing about the code.
* You sent a non-RFC series with identical code quality issues [1] recently.
* Until I pointed it out, you were responding to other review here as if the series was genuinely was intended for (eventual) merge:
- "This is a userspace-visible removal. Writes to
/proc/sys/vm/watermark_boost_factorwill now return-ENOENTinstead of being accepted, breaking userspace." [2]<-: "I'll just drop this patch for now." [3]
- "I left a small code nit inline, but whether you take that suggestion or leave it, you can add Reviewed-by: ..." [4]
Quoted 8 lines
<-: "I sent it with this series mostly because it's needed to make the series work, and to provide context on why it's needed. I'm happy to resend it with a GFP mask passed in by each caller. That would look better, indeed!" [5]
So to be concrete, if you send really rough code, Use [pre-RFC] or [DO NOT MERGE] (on the series as a whole) to make that clear and say so in the cover letter VERY VERY clearly.
Yes please. [POC NOT-FOR-MERGE] perhaps?
Quoted 2 lines
Or, you can put it in a repo somewhere and link it in an email discussing the concepts (like I did with scalable CoW for instance).
Indeed.
Quoted 11 lines
As above, firstly make it clear that the code you are sending for review is not to be reviewed so people don't waste highly contended maintainer time on that! :)
Also, you didn't respond to my point regarding cc'ing the right people - but that's clearly something you need to get right if you want this kind of feedback to start with.
For instance, you didn't cc- the page allocator maintainer (Vlastimil) on a series that is fundamentally changing the page allocator. That's not going to help with feedback.
Right! Thanks a lot for adding me, Lorenzo.
Quoted 4 lines
In general, this area of the page allocator and compaction isn't my specialism in the kernel so I can't give you the in-depth feedback you need on that.
Quoted 8 lines
But I do have thoughts in general as to how to achieve what you want here:
Firstly - you should try to summarise what you're doing here and what you're changing alongside the trade-offs as clearly as you can in the cover letter.
Then highlight what it is you need feedback on, broken out into clear questions or points that make it easy for people to respond to.
Yep.
Quoted 4 lines
And
_youhave already donethis_in your reply here:* "How do people feel about splitting up the free lists, so each gigabyte (well, PUD sized) chunk of memory has its own free lists?"
My immediate response is that now we'd need to search multiple sets of lists instead of a single one? What about the overhead?
Having a POC (even vibe-coded) for measuring that overhead might be actually useful to quickly figure out whether the idea is viable or not.
But then the code doesn't need to be sent as a huge series if it's not for review. As Lorenzo said, git repo link is enough.
Quoted 6 lines
* "How can we balance the desire for higher-order kernel allocations, against the desire to preserve gigabyte sized chunks of memory that can be used for user space?"
* "How do we balance the desire to keep compaction overhead low with the desire to do higher order allocations almost everywhere?"
How can we have a cake and eat it too? :)
Quoted 28 lines
I think a really good way of doing this would be to start out with something like:
Right now compaction often fails to achieve what we need, with fragmentation occurring anyway and (for instance) THP stalling on the availability of higher order folios.
etc. etc.
Summarising
_theproblem_.Then a section about your proposed solution, e.g.:
I propose a means by which we proactively achieve gigabyte-sized pageblocks with logic which maintains these as physically contiguous under both ordinary and contended workloads
Then list out the "secret sauce" of your approach, e.g.:
This works by arranging memory such that unmovable allocations are grouped at <blah blah blah> etc.
Then raise your questions e.g.:
I'd like to ask the community - how do people feel about splitting up the free lists, so each gigabyte (well, PUD sized) chunk of memory has its own free lists? <etc. etc.>
Quoted 8 lines
Then make it clear whether this is an RFC that is ready for primetime or not:
This series is simply intended as a proof-of-concept - PLEASE DO NOT REVIEW THE CODE per-se, but rather comment on the concepts!
(And obviously as above, if that _is_ what you intend, underline it with [DO NOT MERGE] or [pre-RFC] or something like that).
Ack.
Quoted 5 lines
I'd also very strongly suggest (as I did in my original reply) breaking out parts that can be broken out as prerequisite series.
If you're doing something good or useful _anyway_ then just send that separately first, and have later work rely on the earlier work.
Ack.
Quoted 11 lines
There's no rush, this is huge and will take time.
A final KEY point:
NEVER submit unfiltered code generated by an LLMs to the list in _any_ form. If you want people to access code like that to test or something, then put it in a remote repo and link to it.
The code is SO overly complicated and SO messy that it's really difficult for people to understand what's actually going on.
Quoted 8 lines
At the heart of what you need here is CLARITY.
You need to CLEARLY communicate what it is you're doing so busy maintainers can examine it. That's the _only_ way you're going to get something like this merged.
The LLM-generated code is so awful that ain't nobody got the time to try to understand what it's doing.
Indeed.
Quoted 14 lines
The workload for this really has to be on submitters, not maintainers.
And what you've done, even if not intended, is workslopping, and that's really not acceptable. Quoting the kernel process on tool-generated content [6]:
"If tools permit you to generate a contribution automatically, expect additional scrutiny in proportion to how much of it was generated.
As with the output of any tooling, the result may be incorrect or inappropriate. You are expected to understand and to be able to defend everything you submit. If you are unable to do so, then do not submit the resulting changes.
Quoted 6 lines
If you do so anyway, maintainers are entitled to reject your series without detailed review."
As per this and my previous reply, AI slop doesn't scale, even as an RFC - I won't have time to reply like this in future, and we will just have to reject your series out of hand, which helps nobody.
True. Thanks a lot for going out of your way on this!
Quoted 14 lines
Quoted 4 lines
--
All Rights Reversed.Thanks, Lorenzo
[0]:https://lore.kernel.org/all/[email protected]/ [1]:https://lore.kernel.org/linux-mm/[email protected]/ [2]:https://lore.kernel.org/all/[email protected]/ [3]:https://lore.kernel.org/all/[email protected]/ [4]:https://lore.kernel.org/all/[email protected]/ [5]:https://lore.kernel.org/all/[email protected]/ [6]:https://docs.kernel.org/process/generated-content.html
Quoted 8 lines · Vlastimil Babka (SUSE)
Quoted 6 lines · Lorenzo Stoakes
So to be concrete, if you send really rough code, Use [pre-RFC] or [DO NOT
MERGE] (on the series as a whole) to make that clear and say so in the
cover letter VERY VERY clearly.
Quoted 7 lines
Yes please. [POC NOT-FOR-MERGE] perhaps?
Quoted 3 lines
Or, you can put it in a repo somewhere and link it in an email discussing
the concepts (like I did with scalable CoW for instance).Indeed.
I'll do that for the next version.
I suspect it will take a while to beat this thing into shape.
Quoted 10 lines
Quoted 6 lines
And
_youhave already donethis_in your reply here:* "How do people feel about splitting up the free lists, so each gigabyte
(well, PUD sized) chunk of memory has its own free lists?"My immediate response is that now we'd need to search multiple sets of lists
instead of a single one? What about the overhead?
The current code is clearly not good enough. It has to try several gigablocks almost blindly, because there is no efficient way to find the right gigablock.
I have an idea on how to fix that with bitmaps.
We could have one bitmap per order, indicating which gigablocks have order 0 pages, order 1 pages, etc
Then a second set of bitmaps indicating which gigablocks have unmovable / reclaimable pages.
At that point, finding a good gigablock to allocate from can be done with a bitmap_and and a search.
These bitmaps would only need to be changed when the status of a gigablock changes, eg. going from having order 0 pages free, to not having any order 0 pages free.
Does that seem like a workable approach?
Once we can quickly pinpoint a gigablock for the page allocator to grab pages from, we can also split out the "pick a gigablock" code from the "allocate a page" code.
Quoted 7 lines
Quoted 7 lines
* "How can we balance the desire for higher-order kernel allocations,
against the desire to preserve gigabyte sized chunks of memory that can
be used for user space?"
Quoted 5 lines
Quoted 3 lines
* "How do we balance the desire to keep compaction overhead low with the
desire to do higher order allocations almost everywhere?"How can we have a cake and eat it too? :)
Pretty much :/
I suspect it's going to require some fun interactions between allocation, reclaim, and compaction.
However, with everybody from networking, to filesystems, to anonymous memory wanting to use higher order allocations of differing sizes, it seems like we're going to have to tackle this somehow.
Quoted 9 lines
Quoted 8 lines
I'd also very strongly suggest (as I did in my original reply) breaking out
parts that can be broken out as prerequisite series.If you're doing something good or useful _anyway_ then just send that
separately first, and have later work rely on the earlier work.
That becomes cleaner with the "post a link to
a tree" thing, as well.
The pcpbuddy stuff is likely to go in separately. Johannes is still working on that code.
The "make btrfs inode cache pages movable" thing already went in.
I think I have a few more things in the tree that can go in separately, but hopefully that will grow as this code solidifies.
On the flip side, things like "making compaction scale" may well end up depending on the gigablock stuff, because lack of targeting data seems like a likely cause for why compaction has to try so hard.
I'll make sure to go over every point raised by you guys before writing the next version of the code, and again before posting a link to the tree.
Signature · 1 line
All Rights Reversed.