Cache aware scheduling
Subsystems (5)
v4 cover Cache aware scheduling
This patch series introduces infrastructure for cache-aware load balancing, with the goal of co-locating tasks that share data within the same Last Level Cache (LLC) domain. By improving cache locality, the scheduler can reduce cache bouncing and cache misses, ultimately improving data access efficiency. The design builds on the initial prototype from Peter [1].
This initial implementation treats threads within the same process as entities that are likely to share data. During load balancing, the scheduler attempts to aggregate such threads onto the same LLC domain whenever possible.
Most of the feedback received on v3 has been addressed. Some aspects could be enhanced later after the basic cache-aware portion has landed:
There were discussions around grouping tasks using mechanisms other than process membership. While we agree that more flexible grouping is desirable, this series intentionally focuses on establishing basic process-based grouping first, with alternative grouping mechanisms to be explored in a follow-on series.
There was also discussion in v3 that the task wakeup path should be used to perform cache-aware scheduling. According to previous test results, performing task aggregation in the wakeup path introduced task migration bouncing. Primarily that was due to the wake up path not having the up to date LLC load information. That led to over-aggregation that needed to be corrected later in load balancing. Load balancing path was chosen as the conservative path to perform task aggregation. The task wakeup path will be investigated as a future enhancement.
Furthermore, there was also requests to make cache-aware scheduling benefit small LLC systems. Peter suggested using an llc-mask instead of a single llc value for preferences[2]. This could also be implemented as a future enhancement.
The cache aware load balancing logic remains largely unchanged. The significant changes in v4 are:
1. LLC ID management: the calculation of the LLC ID switches to using bitmap allocation rather than maintaining a static value.
2. Introduce a new patch [2/22] to limit the CPU scan span with preferred NUMA node when NUMA balancing is enabled.
3. Tweaks in load balance failure considerations where keeping load imbalance at low load and not pulling task from preferred LLC is not considered as a balance failure.
Other changes are described in each patch.
Test results:
The patch series was applied and tested on v7.0-rc3. Git tree can be found here:
https://github.com/timcchen1298/linux/tree/cache_aware_v4
The first test platform is a 2 socket Intel Sapphire Rapids with 30 cores per socket. The DRAM interleaving is enabled in the BIOS so it essential has one NUMA node with two last level caches. There are 60 CPUs associated with each last level cache.
The second test platform is a AMD Genoa. There are 4 Nodes and 32 CPUs per node. Each node has 2 CCXs and each CCX has 16 CPUs.
hackbench/schbench/netperf/stream/stress-ng/chacha20 were launched on these two platforms.
[TL;DR]
Sappire Rapids:
hackbench shows significant improvement when the number of different active threads is below the capacity of a LLC. schbench shows limitted wakeup latency improvement. ChaCha20-xiangshan(risc-v simulator) shows good throughput improvement. No obvious difference was observed in netperf/stream/stress-ng in Hmean.
Genoa:
Significant improvement is observed in hackbench when the active number of threads is lower than the number of CPUs within 1 LLC. On v2, Aaron reported improvement of hackbench/redis when system is underloaded. ChaCha20-xiangshan shows huge throughput improvement. Phoronix has tested v1 and shows good improvements in 30+ cases[3]. No obvious difference was observed in netperf/stream/stress-ng in Hmean.
Detail:
To conserve space, data without much difference with baseline is not presented.
Sapphire Rapids:
[hackbench pipe]
================
case load baseline(std%) compare%( std%) threads-pipe-10 1-groups 1.00 ( 1.22) +26.09 ( 1.10) threads-pipe-10 2-groups 1.00 ( 4.90) +22.88 ( 0.18) threads-pipe-10 4-groups 1.00 ( 2.07) +9.00 ( 3.49) threads-pipe-10 8-groups 1.00 ( 8.13) +3.45 ( 3.62) threads-pipe-16 1-groups 1.00 ( 2.11) +26.30 ( 0.08) threads-pipe-16 2-groups 1.00 ( 15.13) -1.77 ( 11.89) threads-pipe-16 4-groups 1.00 ( 4.37) +0.58 ( 7.99) threads-pipe-16 8-groups 1.00 ( 2.88) +2.71 ( 3.50) threads-pipe-2 1-groups 1.00 ( 9.40) +22.07 ( 0.71) threads-pipe-2 2-groups 1.00 ( 9.99) +18.01 ( 0.95) threads-pipe-2 4-groups 1.00 ( 3.98) +24.66 ( 0.96) threads-pipe-2 8-groups 1.00 ( 7.00) +21.83 ( 0.23) threads-pipe-20 1-groups 1.00 ( 1.03) +28.84 ( 0.21) threads-pipe-20 2-groups 1.00 ( 4.42) +31.90 ( 3.15) threads-pipe-20 4-groups 1.00 ( 9.97) +4.56 ( 1.69) threads-pipe-20 8-groups 1.00 ( 1.87) +1.25 ( 0.74) threads-pipe-4 1-groups 1.00 ( 4.48) +25.67 ( 0.78) threads-pipe-4 2-groups 1.00 ( 9.14) +4.91 ( 2.08) threads-pipe-4 4-groups 1.00 ( 7.68) +19.36 ( 1.53) threads-pipe-4 8-groups 1.00 ( 10.79) +7.20 ( 12.20) threads-pipe-8 1-groups 1.00 ( 4.69) +21.93 ( 0.03) threads-pipe-8 2-groups 1.00 ( 1.16) +25.29 ( 0.65) threads-pipe-8 4-groups 1.00 ( 2.23) -1.27 ( 3.62) threads-pipe-8 8-groups 1.00 ( 4.65) -3.08 ( 2.75)
Note: The default number of fd in hackbench is changed from 20 to various values to ensure that threads fit within a single LLC, especially on AMD systems. Take "threads-pipe-8, 2-groups" for example, the number of fd is 8, and 2 groups are created.
[schbench]
The 99th percentile wakeup latency shows some improvements when the system is underload, while it does not bring much difference with the increasing of system utilization.
99th Wakeup Latencies Base (mean std) Compare (mean std) Change
--------------------------------------------------------------------------------
thread=2 9.00(0.00) 9.00(1.73) 0.00% thread=4 7.33(0.58) 6.33(0.58) +13.64% thread=8 9.00(0.00) 7.67(1.15) +14.78% thread=16 8.67(0.58) 8.67(1.53) 0.00% thread=32 9.00(0.00) 7.00(0.00) +22.22% thread=64 9.33(0.58) 9.67(0.58) -3.64% thread=128 12.00(0.00) 12.00(0.00) 0.00%
[chacha200]
baseline:
Host time spent: 67861ms
cache aware scheduling enabled:
Host time spent: 54441ms
Time reduced by 24%
Genoa:
[hackbench pipe]
The default number of fd is 20, which exceed the number of CPUs in a LLC. So the fd is adjusted to 2, 4, 6, 8, 20 respectively. Exclude the result with large run-to-run variance, 10% ~ 50% improvement is observed when the system is underloaded:
[hackbench pipe]
================
case load baseline(std%) compare%( std%) threads-pipe-2 1-groups 1.00 ( 2.89) +47.33 ( 1.20) threads-pipe-2 2-groups 1.00 ( 3.88) +39.82 ( 0.61) threads-pipe-2 4-groups 1.00 ( 8.76) +5.57 ( 13.10) threads-pipe-20 1-groups 1.00 ( 4.61) +11.72 ( 1.06) threads-pipe-20 2-groups 1.00 ( 6.18) +14.55 ( 1.47) threads-pipe-20 4-groups 1.00 ( 2.99) +10.16 ( 4.49) threads-pipe-4 1-groups 1.00 ( 4.23) +43.70 ( 2.14) threads-pipe-4 2-groups 1.00 ( 3.68) +8.45 ( 4.04) threads-pipe-4 4-groups 1.00 ( 17.72) +2.42 ( 1.14) threads-pipe-6 1-groups 1.00 ( 3.10) +7.74 ( 3.83) threads-pipe-6 2-groups 1.00 ( 3.42) +14.26 ( 4.53) threads-pipe-6 4-groups 1.00 ( 10.34) +10.94 ( 7.12) threads-pipe-8 1-groups 1.00 ( 4.21) +9.06 ( 4.43) threads-pipe-8 2-groups 1.00 ( 1.88) +3.74 ( 0.58) threads-pipe-8 4-groups 1.00 ( 2.78) +23.96 ( 1.18)
[chacha200]
Host time spent: 54762ms
Host time spent: 28295ms
Time reduced by 48%
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://www.phoronix.com/review/cache-aware-scheduling-amd-turin
Change history:
**v4 Changes:**
1. Using bitmap based LLC id dynamic allocation mechanism.
2. Introduce a new patch [2/22] to limit the CPU scan depth with preferred NUMA node.
3. Keeping load imbalance at low load and not pulling task from preferred LLC is not considered as a balance failure.
4. Other changes from v3 are detailed in each patch's change log.
**v3 Changes:**
v3 link: https://lore.kernel.org/all/[email protected]/
1. Cache-aware scheduling is skipped after repeated load balance failures (up to cache_nice_tries). This avoids repeatedly attempting cache-aware migrations when no movable tasks prefer the destination LLC.
2. The busiest runqueue is no longer sorted to select tasks that prefer the destination LLC. This sorting was costly, and equivalent behavior can be achieved by skipping tasks that do not prefer the destination LLC during cache-aware migrations.
3. Accounting of the number of tasks preferring each LLC is now kept in the lowest-level sched domain per CPU. This simplifies handling of LLC resizing and changes in the number of LLC domains.
4. Other changes from v2 are detailed in each patch's change log.
**v2 Changes:**
v2 link: https://lore.kernel.org/all/[email protected]/
1. Align NUMA balancing and cache affinity by
prioritizing NUMA balancing when their decisions differ.
2. Dynamically resize per-LLC statistics structures based on the LLC size.
3. Switch to a contiguous LLC-ID space so these IDs can be used directly as array indices for LLC statistics.
4. Add clarification comments.
5. Add 3 debug patches (not meant for merging).
6. Other changes to address feedbacks from review of v1 patch set
(see individual patch change log).
**v1**
v1 link: https://lore.kernel.org/all/[email protected]/
Chen Yu (10):
sched/cache: Limit the scan number of CPUs when calculating task
occupancy
sched/cache: Record per LLC utilization to guide cache aware
scheduling decisions
sched/cache: Introduce helper functions to enforce LLC migration
policy
sched/cache: Disable cache aware scheduling for processes with high
thread counts
sched/cache: Avoid cache-aware scheduling for memory-heavy processes sched/cache: Enable cache aware scheduling for multi LLCs NUMA node sched/cache: Allow the user space to turn on and off cache aware
scheduling
sched/cache: Add user control to adjust the aggressiveness of
cache-aware scheduling
-- DO NOT APPLY!!! -- sched/cache/debug: Display the per LLC occupancy
for each process via proc fs
-- DO NOT APPLY!!! -- sched/cache/debug: Add ftrace to track the load
balance statistics
Peter Zijlstra (Intel) (1):
sched/cache: Introduce infrastructure for cache-aware load balancing
Tim Chen (11):
sched/cache: Make LLC id continuous
sched/cache: Assign preferred LLC ID to processes sched/cache: Track LLC-preferred tasks per runqueue sched/cache: Introduce per CPU's tasks LLC preference counter sched/cache: Calculate the percpu sd task LLC preference sched/cache: Count tasks prefering destination LLC in a sched group sched/cache: Check local_group only once in update_sg_lb_stats() sched/cache: Prioritize tasks preferring destination LLC during
balancing
sched/cache: Add migrate_llc_task migration type for cache-aware
balancing
sched/cache: Handle moving single tasks to/from their preferred LLC sched/cache: Respect LLC preference in task migration and detach
fs/proc/base.c | 31 + include/linux/cacheinfo.h | 21 +- include/linux/mm_types.h | 43 ++ include/linux/sched.h | 32 + include/linux/sched/topology.h | 17 + include/trace/events/sched.h | 140 ++++ init/Kconfig | 11 + init/init_task.c | 3 + kernel/fork.c | 6 + kernel/sched/core.c | 13 + kernel/sched/debug.c | 58 +- kernel/sched/fair.c | 1180 +++++++++++++++++++++++++++++++- kernel/sched/sched.h | 50 ++ kernel/sched/topology.c | 234 ++++++- 14 files changed, 1810 insertions(+), 29 deletions(-)
Signature · 1 line
2.32.0
PATCH v4 1/22 sched/cache: Introduce infrastructure for cache-aware load balancing
From: "Peter Zijlstra (Intel)" <[email protected]>
Adds infrastructure to enable cache-aware load balancing, which improves cache locality by grouping tasks that share resources within the same cache domain. This reduces cache misses and improves overall data access efficiency.
In this initial implementation, threads belonging to the same process are treated as entities that likely share working sets. The mechanism tracks per-process CPU occupancy across cache domains and attempts to migrate threads toward cache-hot domains where their process already has active threads, thereby enhancing locality.
This provides a basic model for cache affinity. While the current code targets the last-level cache (LLC), the approach could be extended to other domain types such as clusters (L2) or node-internal groupings.
At present, the mechanism selects the CPU within an LLC that has the highest recent runtime. Subsequent patches in this series will use this information in the load-balancing path to guide task placement toward preferred LLCs.
In the future, more advanced policies could be integrated through NUMA balancing-for example, migrating a task to its preferred LLC when spare capacity exists, or swapping tasks across LLCs to improve cache affinity. Grouping of tasks could also be generalized from that of a process to be that of a NUMA group, or be user configurable.
---
Notes:
v3->v4:
No change.include/linux/mm_types.h | 32 +++++ include/linux/sched.h | 24 ++++ init/Kconfig | 11 ++ kernel/fork.c | 6 + kernel/sched/core.c | 6 + kernel/sched/fair.c | 266 +++++++++++++++++++++++++++++++++++++++ kernel/sched/sched.h | 14 +++ 7 files changed, 359 insertions(+)
include/linux/mm_types.h +32 -0
@@ -1173,6 +1173,8 @@ struct mm_struct {/* MM CID related storage */ struct mm_mm_cid mm_cid; +/* sched_cache related statistics */ +struct sched_cache_stat sc_stat;#ifdef CONFIG_MMU atomic_long_t pgtables_bytes;/* size of all page tables */ #endif
@@ -1575,6 +1577,36 @@ static inline unsigned int mm_cid_size(void)# define MM_CID_STATIC_SIZE 0#endif /* CONFIG_SCHED_MM_CID */ +#ifdef CONFIG_SCHED_CACHE +void mm_init_sched (struct mm_struct *mm, +struct sched_cache_time __percpu *pcpu_sched); + +static inline int mm_alloc_sched_noprof (struct mm_struct *mm) +{ +struct sched_cache_time __percpu *pcpu_sched = + alloc_percpu_noprof(struct sched_cache_time); + +if (!pcpu_sched) +return -ENOMEM ; + +mm_init_sched (mm, pcpu_sched); +return 0 ; +} + +#define mm_alloc_sched (...) alloc_hooks(mm_alloc_sched_noprof(__VA_ARGS__)) + +static inline void mm_destroy_sched (struct mm_struct *mm) +{ +free_percpu (mm->sc_stat.pcpu_sched); + mm->sc_stat.pcpu_sched =NULL ; +} +#else /* !CONFIG_SCHED_CACHE */ + +static inline int mm_alloc_sched (struct mm_struct *mm) {return 0 ; } +static inline void mm_destroy_sched (struct mm_struct *mm) { } + +#endif /* CONFIG_SCHED_CACHE */ +struct mmu_gather ;extern void tlb_gather_mmu (struct mmu_gather *tlb,struct mm_struct *mm);extern void tlb_gather_mmu_fullmm (struct mmu_gather *tlb,struct mm_struct *mm);
include/linux/sched.h +24 -0
@@ -1406,6 +1406,10 @@ struct task_struct {unsigned long numa_pages_migrated;#endif /* CONFIG_NUMA_BALANCING */ +#ifdef CONFIG_SCHED_CACHE +struct callback_head cache_work; +#endif +struct rseq_data rseq;struct sched_mm_cid mm_cid;
@@ -2376,6 +2380,26 @@ static __always_inline int task_mm_cid(struct task_struct *t) }#endif +#ifdef CONFIG_SCHED_CACHE + +struct sched_cache_time { +u64 runtime; +unsigned long epoch; +}; + +struct sched_cache_stat { +struct sched_cache_time __percpu *pcpu_sched; +raw_spinlock_t lock; +unsigned long epoch; +int cpu; +}____cacheline_aligned_in_smp ; + +#else + +struct sched_cache_stat { }; + +#endif +#ifndef MODULE #ifndef COMPILE_OFFSETS
init/Kconfig +11 -0
@@ -1005,6 +1005,17 @@ config NUMA_BALANCING This system will be inactive on UMA systems. +config SCHED_CACHE + bool "Cache aware load balance" + default y + depends on SMP + help + When enabled, the scheduler will attempt to aggregate tasks from + the same process onto a single Last Level Cache (LLC) domain when + possible. This improves cache locality by keeping tasks that share + resources within the same cache domain, reducing cache misses and + lowering data access latency. + config NUMA_BALANCING_DEFAULT_ENABLED bool "Automatically enable NUMA aware memory/task placement" default y
kernel/fork.c +6 -0
@@ -724,6 +724,7 @@ void __mmdrop(struct mm_struct *mm)cleanup_lazy_tlbs (mm);WARN_ON_ONCE (mm == current->active_mm); +mm_destroy_sched (mm);mm_free_pgd (mm);mm_free_id (mm);destroy_context (mm);
@@ -1124,6 +1125,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,if (mm_alloc_cid (mm, p)) goto fail_cid; +if (mm_alloc_sched (mm)) + goto fail_sched; +if (percpu_counter_init_many (mm->rss_stat,0 ,GFP_KERNEL_ACCOUNT ,NR_MM_COUNTERS )) goto fail_pcpu;
@@ -1133,6 +1137,8 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,return mm; fail_pcpu: +mm_destroy_sched (mm); +fail_sched:mm_destroy_cid (mm); fail_cid:destroy_context (mm);
kernel/sched/core.c +6 -0
@@ -4437,6 +4437,7 @@ static void __sched_fork(u64 clone_flags, struct task_struct *p)init_numa_balancing (clone_flags, p); p->wake_entry.u_flags =CSD_TYPE_TTWU ; p->migration_pending =NULL ; +init_sched_mm (p); }DEFINE_STATIC_KEY_FALSE (sched_numa_balancing);
@@ -8749,6 +8750,11 @@ void __init sched_init(void) rq->core_cookie =0UL ;#endif +#ifdef CONFIG_SCHED_CACHE +raw_spin_lock_init (&rq->cpu_epoch_lock); + rq->cpu_epoch_next = jiffies; +#endif +zalloc_cpumask_var_node (&rq->scratch_mask,GFP_KERNEL ,cpu_to_node (i)); }
kernel/sched/fair.c +266 -0
290 lines not on this page · raw message
kernel/sched/sched.h +14 -0
@@ -1177,6 +1177,12 @@ struct rq {struct scx_rq scx;struct sched_dl_entity ext_server;#endif +#ifdef CONFIG_SCHED_CACHE +raw_spinlock_t cpu_epoch_lock____cacheline_aligned ; +u64 cpu_runtime; +unsigned long cpu_epoch; +unsigned long cpu_epoch_next; +#endif struct sched_dl_entity fair_server;
@@ -4007,6 +4013,14 @@ static inline void mm_cid_switch_to(struct task_struct *prev, struct task_structstatic inline void mm_cid_switch_to (struct task_struct *prev,struct task_struct *next) { }#endif /* !CONFIG_SCHED_MM_CID */ +#ifdef CONFIG_SCHED_CACHE +static inline bool sched_cache_enabled (void ) +{ +return false; +} +#endif +extern void init_sched_mm (struct task_struct *p); +extern u64 avg_vruntime (struct cfs_rq *cfs_rq);extern int entity_eligible (struct cfs_rq *cfs_rq,struct sched_entity *se); static inline
Signature · 1 line
2.32.0
PATCH v4 2/22 sched/cache: Limit the scan number of CPUs when calculating task occupancy
In reply to Tim ChenFrom: Chen Yu <[email protected]>
When NUMA balancing is enabled, the kernel currently iterates over all online CPUs to aggregate process-wide occupancy data. On large systems, this global scan introduces significant overhead.
To reduce scan latency, limit the search to a subset of relevant CPUs:
1. The task's preferred NUMA node.
2. The node where the task is currently running.
3. The node that contains the task's current preferred LLC..
While focusing solely on the preferred NUMA node is ideal, a process-wide scan must remain flexible because the "preferred node" is a per-task attribute. Different threads within the same process may have different preferred nodes, causing the process-wide preference to migrate. Maintaining a mask that covers both the preferred and active running nodes ensures accuracy while significantly reducing the number of CPUs inspected.
Future work may integrate numa_group to further refine task aggregation.
---
Notes:
v3->v4:
New patch.kernel/sched/fair.c | 46 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-)
kernel/sched/fair.c +45 -1
@@ -1431,6 +1431,50 @@ static void task_tick_cache(struct rq *rq, struct task_struct *p) } } +static void get_scan_cpumasks (cpumask_var_t cpus,struct task_struct *p) +{ +#ifdef CONFIG_NUMA_BALANCING +int cpu, curr_cpu, pref_nid; + +if (!static_branch_likely (&sched_numa_balancing)) + goto out; + + cpu = p->mm->sc_stat.cpu; + curr_cpu =task_cpu (p); + +/* +* Scanning in the preferred NUMA node is ideal. However, the NUMA +* preferred node is per-task rather than per-process. It is possible +* for different threads of the process to have distinct preferred +* nodes; consequently, the process-wide preferred LLC may bounce +* between different nodes. As a workaround, maintain the scan +* CPU mask to also cover the process's current preferred LLC and the +* current running node to mitigate the bouncing risk. +* TBD: numa_group should be considered during task aggregation. +*/ + pref_nid = p->numa_preferred_nid; +/* honor the task's preferred node */ +if (pref_nid ==NUMA_NO_NODE ) + goto out; + +cpumask_or (cpus, cpus,cpumask_of_node (pref_nid)); + +/* honor the task's preferred LLC CPU */ +if (cpu !=-1 && !cpumask_test_cpu (cpu, cpus)) +cpumask_or (cpus, cpus, +cpumask_of_node (cpu_to_node (cpu))); + +/* make sure the task's current running node is included */ +if (!cpumask_test_cpu (curr_cpu, cpus)) +cpumask_or (cpus, cpus,cpumask_of_node (cpu_to_node (curr_cpu))); + +return ; + +out: +#endif +cpumask_copy (cpus, cpu_online_mask); +} +static void task_cache_work (struct callback_head *work) {struct task_struct *p = current;
@@ -1451,7 +1495,7 @@ static void task_cache_work(struct callback_head *work)return ;scoped_guard (cpus_read_lock) { -cpumask_copy (cpus, cpu_online_mask); +get_scan_cpumasks (cpus, p);for_each_cpu (cpu, cpus) {/* XXX sched_cluster_active */
Signature · 1 line
2.32.0
PATCH v4 3/22 sched/cache: Record per LLC utilization to guide cache aware scheduling decisions
In reply to Tim ChenFrom: Chen Yu <[email protected]>
When a system becomes busy and a process's preferred LLC is saturated with too many threads, tasks within that LLC migrate frequently. These in LLC migrations introduce latency and degrade performance. To avoid this, task aggregation should be suppressed when the preferred LLC is overloaded, which requires a metric to indicate LLC utilization.
Record per LLC utilization/cpu capacity during periodic load balancing. These statistics will be used in later patches to decide whether tasks should be aggregated into their preferred LLC.
---
Notes:
v3->v4:
No change.include/linux/sched/topology.h | 4 ++ kernel/sched/fair.c | 70 ++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+)
include/linux/sched/topology.h +4 -0
@@ -68,6 +68,10 @@ struct sched_domain_shared {atomic_t nr_busy_cpus;int has_idle_cores;int nr_idle_scan; +#ifdef CONFIG_SCHED_CACHE +unsigned long util_avg; +unsigned long capacity; +#endif };struct sched_domain {
kernel/sched/fair.c +70 -0
88 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 4/22 sched/cache: Introduce helper functions to enforce LLC migration policy
In reply to Tim ChenFrom: Chen Yu <[email protected]>
Cache-aware scheduling aggregates threads onto their preferred LLC, mainly through load balancing. When the preferred LLC becomes saturated, more threads are still placed there, increasing latency. A mechanism is needed to limit aggregation so that the preferred LLC does not become overloaded.
Introduce helper functions can_migrate_llc() and can_migrate_llc_task() to enforce the LLC migration policy:
1. Aggregate a task to its preferred LLC if both source and destination LLCs are not too busy, or if doing so will not leave the preferred LLC much more imbalanced than the non-preferred one (>20% utilization difference, a little higher than the default imbalance_pct(17%) of the LLC domain as hysteresis). Later this threshold will be turned into tunable debugfs.
2. Allow moving a task from overloaded preferred LLC to a non preferred LLC if this will not cause the non preferred LLC to become too imbalanced to cause a later migration back.
3. If both LLCs are too busy, let the generic load balance to spread the tasks.
Further (hysteresis)action could be taken in the future to prevent tasks from being migrated into and out of the preferred LLC frequently (back and forth): the threshold for migrating a task out of its preferred LLC should be higher than that for migrating it into the LLC.
---
Notes:
v3->v4:
Moving the capacity check after the utilization adjustment to make it consistent with the decision matrix(Madadi Vineeth Reddy).
Raise the default threshold in fits_llc_capacity() from 50% to 75% for single-core system. Because single-core system does not need to consider the capacity of SMT. This helps further improve the performance base on the test conducted on single-core system.
kernel/sched/fair.c | 167 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+)
kernel/sched/fair.c +167 -0
@@ -9790,6 +9790,38 @@ static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_ }#ifdef CONFIG_SCHED_CACHE +/* +* The margin used when comparing LLC utilization with CPU capacity. +* It determines the LLC load level where active LLC aggregation is +* done. +* Derived from fits_capacity(). +* +* (default: ~50%, tunable via debugfs) +*/ +static bool fits_llc_capacity (unsigned long util,unsigned long max) +{ +u32 aggr_pct =50 ; + +/* +* For single core systems, raise the aggregation +* threshold to accommodate more tasks. +*/ +if (cpu_smt_num_threads ==1 ) + aggr_pct = (aggr_pct *3 /2 ); + +return util *100 < max * aggr_pct; +} + +/* +* The margin used when comparing utilization. +* is 'util1' noticeably greater than 'util2' +* Derived from capacity_greater(). +* Bias is in perentage. +*/ +/* Allows dst util to be bigger than src util by up to bias percent */ +#define util_greater (util1, util2) \ + ((util1) * 100 > (util2) * 120) +static __maybe_unused bool get_llc_stats (int cpu,unsigned long *util,unsigned long *cap) {
@@ -9804,6 +9836,141 @@ static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util, return true; } + +/* +* Decision matrix according to the LLC utilization. To +* decide whether we can do task aggregation across LLC. +* +* By default, 50% is the threshold for treating the LLC +* as busy. The reason for choosing 50% is to avoid saturation +* of SMT-2, and it is also a safe cutoff for other SMT-n +* platforms. SMT-1 has higher threshold because it is +* supposed to accommodate more tasks, see fits_llc_capacity(). +* +* 20% is the utilization imbalance percentage to decide +* if the preferred LLC is busier than the non-preferred LLC. +* 20 is a little higher than the LLC domain's imbalance_pct +* 17. The hysteresis is used to avoid task bouncing between the +* preferred LLC and the non-preferred LLC, and it will +* be turned into tunable debugfs. +* +* 1. moving towards the preferred LLC, dst is the preferred +* LLC, src is not. +* +* src \ dst 30% 40% 50% 60% +* 30% Y Y Y N +* 40% Y Y Y Y +* 50% Y Y G G +* 60% Y Y G G +* +* 2. moving out of the preferred LLC, src is the preferred +* LLC, dst is not: +* +* src \ dst 30% 40% 50% 60% +* 30% N N N N +* 40% N N N N +* 50% N N G G +* 60% Y N G G +* +* src : src_util +* dst : dst_util +* Y : Yes, migrate +* N : No, do not migrate +* G : let the Generic load balance to even the load. +* +* The intention is that if both LLCs are quite busy, cache aware +* load balance should not be performed, and generic load balance +* should take effect. However, if one is busy and the other is not, +* the preferred LLC capacity(50%) and imbalance criteria(20%) should +* be considered to determine whether LLC aggregation should be +* performed to bias the load towards the preferred LLC. +*/ + +/* migration decision, 3 states are orthogonal. */ +enum llc_mig { + mig_forbid =0 ,/* N: Don't migrate task, respect LLC preference */ + mig_llc,/* Y: Do LLC preference based migration */ + mig_unrestricted/* G: Don't restrict generic load balance migration */ +}; + +/* +* Check if task can be moved from the source LLC to the +* destination LLC without breaking cache aware preferrence. +* src_cpu and dst_cpu are arbitrary CPUs within the source +* and destination LLCs, respectively. +*/ +static enum llc_mig can_migrate_llc (int src_cpu,int dst_cpu, +unsigned long tsk_util, +bool to_pref) +{ +unsigned long src_util, dst_util, src_cap, dst_cap; + +if (!get_llc_stats (src_cpu, &src_util, &src_cap) || + !get_llc_stats (dst_cpu, &dst_util, &dst_cap)) +return mig_unrestricted; + + src_util = src_util < tsk_util ?0 : src_util - tsk_util; + dst_util = dst_util + tsk_util; + +if (!fits_llc_capacity (dst_util, dst_cap) && + !fits_llc_capacity (src_util, src_cap)) +return mig_unrestricted; + +if (to_pref) { +/* +* Don't migrate if we will get preferred LLC too +* heavily loaded and if the dest is much busier +* than the src, in which case migration will +* increase the imbalance too much. +*/ +if (!fits_llc_capacity (dst_util, dst_cap) && +util_greater (dst_util, src_util)) +return mig_forbid; + }else { +/* +* Don't migrate if we will leave preferred LLC +* too idle, or if this migration leads to the +* non-preferred LLC falls within sysctl_aggr_imb percent +* of preferred LLC, leading to migration again +* back to preferred LLC. +*/ +if (fits_llc_capacity (src_util, src_cap) || + !util_greater (src_util, dst_util)) +return mig_forbid; + } +return mig_llc; +} + +/* +* Check if task p can migrate from source LLC to +* destination LLC in terms of cache aware load balance. +*/ +static __maybe_unused enum llc_mig can_migrate_llc_task (int src_cpu,int dst_cpu, +struct task_struct *p) +{ +struct mm_struct *mm; +bool to_pref; +int cpu; + + mm = p->mm; +if (!mm) +return mig_unrestricted; + + cpu = mm->sc_stat.cpu; +if (cpu <0 ||cpus_share_cache (src_cpu, dst_cpu)) +return mig_unrestricted; + +if (cpus_share_cache (dst_cpu, cpu)) + to_pref = true; +else if (cpus_share_cache (src_cpu, cpu)) + to_pref = false; +else +return mig_unrestricted; + +return can_migrate_llc (src_cpu, dst_cpu, +task_util (p), to_pref); +} +#else static inline bool get_llc_stats (int cpu,unsigned long *util,unsigned long *cap)
Signature · 1 line
2.32.0
PATCH v4 5/22 sched/cache: Make LLC id continuous
In reply to Tim ChenIntroduce an index mapping between CPUs and their LLCs. This provides a roughly continuous per LLC index needed for cache-aware load balancing in later patches.
The existing per_cpu llc_id usually points to the first CPU of the LLC domain, which is sparse and unsuitable as an array index. Using llc_id directly would waste memory.
With the new mapping, CPUs in the same LLC share an approximate continuous id:
per_cpu(llc_id, CPU=0...15) = 0
per_cpu(llc_id, CPU=16...31) = 1
per_cpu(llc_id, CPU=32...47) = 2
...
Note that the LLC IDs are allocated via bitmask, so the IDs may be reused during CPU offline->online transitions.
---
Notes:
v3->v4:
Leverage dynamic cpumask management infrastructure for LLC id allocation.
(K Prateek Nayak, Peter Zijlstra)
kernel/sched/core.c | 2 + kernel/sched/sched.h | 3 ++ kernel/sched/topology.c | 90 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 93 insertions(+), 2 deletions(-)
kernel/sched/core.c +2 -0
@@ -8417,6 +8417,8 @@ int sched_cpu_deactivate(unsigned int cpu)*/ synchronize_rcu (); +sched_domains_free_llc_id (cpu); +sched_set_rq_offline (rq, cpu);scx_rq_deactivate (rq);
kernel/sched/sched.h +3 -0
@@ -4019,6 +4019,9 @@ static inline bool sched_cache_enabled(void) return false; }#endif + +void sched_domains_free_llc_id (int cpu); +extern void init_sched_mm (struct task_struct *p);extern u64 avg_vruntime (struct cfs_rq *cfs_rq);
kernel/sched/topology.c +88 -2
140 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 6/22 sched/cache: Assign preferred LLC ID to processes
In reply to Tim ChenWith cache-aware scheduling enabled, each task is assigned a preferred LLC ID. This allows quick identification of the LLC domain where the task prefers to run, similar to numa_preferred_nid in NUMA balancing.
---
Notes:
v3->v4:
Use WRITE_ONCE()/READ_ONCE() on p->preferred_llc
(Madadi Vineeth Reddy)include/linux/sched.h | 1 + init/init_task.c | 3 +++ kernel/sched/fair.c | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+)
include/linux/sched.h +1 -0
@@ -1408,6 +1408,7 @@ struct task_struct {#ifdef CONFIG_SCHED_CACHE struct callback_head cache_work; +int preferred_llc;#endif struct rseq_data rseq;
init/init_task.c +3 -0
@@ -214,6 +214,9 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { .numa_group = NULL, .numa_faults = NULL,#endif +#ifdef CONFIG_SCHED_CACHE + .preferred_llc = -1, +#endif #if defined(CONFIG_KASAN_GENERIC ) || defined(CONFIG_KASAN_SW_TAGS ) .kasan_depth = 1,#endif
kernel/sched/fair.c +43 -0
66 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 7/22 sched/cache: Track LLC-preferred tasks per runqueue
In reply to Tim ChenFor each runqueue, track the number of tasks with an LLC preference and how many of them are running on their preferred LLC. This mirrors nr_numa_running and nr_preferred_running for NUMA balancing, and will be used by cache-aware load balancing in later patches.
---
Notes:
v3->v4:
Use READ_ONCE() to access p->preferred_llc
(Madadi Vineeth Reddy).kernel/sched/core.c | 5 +++++ kernel/sched/fair.c | 47 +++++++++++++++++++++++++++++++++++++++++--- kernel/sched/sched.h | 8 ++++++++ 3 files changed, 57 insertions(+), 3 deletions(-)
kernel/sched/core.c +5 -0
@@ -539,6 +539,11 @@ void __trace_set_current_state(int state_value) }EXPORT_SYMBOL (__trace_set_current_state); +int task_llc (const struct task_struct *p) +{ +return per_cpu (sd_llc_id,task_cpu (p)); +} +/* * Serialization rules: *
kernel/sched/fair.c +44 -3
86 lines not on this page · raw message
kernel/sched/sched.h +8 -0
@@ -1195,6 +1195,12 @@ struct rq {#ifdef CONFIG_NUMA_BALANCING unsigned int numa_migrate_on;#endif + +#ifdef CONFIG_SCHED_CACHE +unsigned int nr_pref_llc_running; +unsigned int nr_llc_running; +#endif +/* * This is part of a global counter where only the total sum * over all CPUs matters. A task can increase this counter on
@@ -2066,6 +2072,8 @@ init_numa_balancing(u64 clone_flags, struct task_struct *p)#endif /* !CONFIG_NUMA_BALANCING */ +int task_llc (const struct task_struct *p); + static inline void queue_balance_callback(struct rq *rq, struct balance_callback *head,
Signature · 1 line
2.32.0
PATCH v4 8/22 sched/cache: Introduce per CPU's tasks LLC preference counter
In reply to Tim ChenThe lowest level of sched domain for each CPU is assigned an array where each element tracks the number of tasks preferring a given LLC, indexed from 0 to max_lid. Since each CPU has its dedicated sd, this implies that each CPU will have a dedicated task LLC preference counter.
For example, sd->llc_counts[3] = 2 signifies that there are 2 tasks on this runqueue which prefer to run within LLC3.
The load balancer can use this information to identify busy runqueues and migrate tasks to their preferred LLC domains. This array will be reallocated at runtime during sched domain rebuild.
Introduce the buffer allocation mechanism, and the statistics will be calculated in the subsequent patch.
Note: the LLC preference statistics of each CPU are reset on sched domain rebuild and may under count temporarily, until the CPU becomes idle and the count is cleared. This is a trade off to avoid complex data synchronization across sched domain builds.
---
Notes:
v3->v4:
Rename pf to llc_counter to better reflect its usage;
Record its size (max_llcs) per sched domain;
Publish the llc_counter and its size together in
cpu_attach_domain().
(Peter Zijlstra)include/linux/sched/topology.h | 13 ++++++++ kernel/sched/topology.c | 61 +++++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 1 deletion(-)
include/linux/sched/topology.h +13 -0
@@ -102,6 +102,19 @@ struct sched_domain {u64 max_newidle_lb_cost;unsigned long last_decay_max_lb_cost; +#ifdef CONFIG_SCHED_CACHE +unsigned int llc_max; +/* +* per LLC preference counter +* __counted_by cannot be used here because +* when the percpu sched_domain is being allocated, +* llc_max is unknown, and thus the actual size +* of the sched_domain(including the llc_counts elements) +* is undetermined. +*/ +unsigned int *llc_counts; +#endif +#ifdef CONFIG_SCHEDSTATS /* sched_balance_rq() stats */ unsigned int lb_count[CPU_MAX_IDLE_TYPES ];
kernel/sched/topology.c +60 -1
94 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 9/22 sched/cache: Calculate the percpu sd task LLC preference
In reply to Tim ChenCalculate the number of tasks' LLC preferences for each runqueue. This statistic is computed during task enqueue and dequeue operations, and is used by the cache-aware load balancing.
---
Notes:
v3->v4:
Remove unnecessary rcu_read_lock() in eq/dq as rq lock is held. Use rcu_dereference_all() directly. (Peter Zijlstra)
kernel/sched/fair.c | 49 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+)
kernel/sched/fair.c +49 -0
@@ -1291,8 +1291,34 @@ static int llc_id(int cpu)return per_cpu (sd_llc_id, cpu); } +static inline bool valid_llc_buf (struct sched_domain *sd, +int id) +{ +/* +* These checks are used to avoid the following +* race causing out-of-range access to llc_counts: +* +* CPU0 CPU1 +* : +* ... +* build_sched_domains update_sg_lb_stats +* for_each_cpu_and(i, sg) +* sd=rq[i]->sd +* per_cpu(sd_llc_id,i)=new_llc +* llc=llc_id(i) +* !!!sd->llc_counts[llc]!!! +* sd->llc_counts=kzalloc() +* sd->llc_max=max_llc +*/ +if (unlikely (id <0 || !sd || !sd->llc_counts || id > sd->llc_max)) +return false; + +return true; +} +static void account_llc_enqueue (struct rq *rq,struct task_struct *p) { +struct sched_domain *sd;int pref_llc; pref_llc = p->preferred_llc;
@@ -1301,10 +1327,15 @@ static void account_llc_enqueue(struct rq *rq, struct task_struct *p) rq->nr_llc_running++; rq->nr_pref_llc_running += (pref_llc ==task_llc (p)); + + sd =rcu_dereference_all (rq->sd); +if (valid_llc_buf (sd, pref_llc)) + sd->llc_counts[pref_llc]++; }static void account_llc_dequeue (struct rq *rq,struct task_struct *p) { +struct sched_domain *sd;int pref_llc; pref_llc = p->preferred_llc;
@@ -1313,6 +1344,24 @@ static void account_llc_dequeue(struct rq *rq, struct task_struct *p) rq->nr_llc_running--; rq->nr_pref_llc_running -= (pref_llc ==task_llc (p)); + + sd =rcu_dereference_all (rq->sd); +if (valid_llc_buf (sd, pref_llc)) { +/* +* There is a race condition between dequeue +* and CPU hotplug. After a task has been enqueued +* on CPUx, a CPU hotplug event occurs, and all online +* CPUs (including CPUx) rebuild their sched_domains +* and reset statistics to zero(including sd->llc_counts). +* This can cause temporary undercount and we have to +* check for such underflow in sd->llc_counts. +* +* This undercount is temporary and accurate accounting +* will resume once the rq has a chance to be idle. +*/ +if (sd->llc_counts[pref_llc]) + sd->llc_counts[pref_llc]--; + } } void mm_init_sched(struct mm_struct *mm,
Signature · 1 line
2.32.0
PATCH v4 10/22 sched/cache: Count tasks prefering destination LLC in a sched group
In reply to Tim ChenDuring LLC load balancing, tabulate the number of tasks on each runqueue that prefer the LLC contains the env->dst_cpu in a sched group.
For example, consider a system with 4 LLC sched groups (LLC0 to LLC3) balancing towards LLC3. LLC0 has 3 tasks preferring LLC3, LLC1 has 2, and LLC2 has 1. LLC0, having the most tasks preferring LLC3, is selected as the busiest source to pick tasks from.
Within a source LLC, the total number of tasks preferring a destination LLC is computed by summing counts across all CPUs in that LLC. For instance, if LLC0 has CPU0 with 2 tasks and CPU1 with 1 task preferring LLC3, the total for LLC0 is 3.
These statistics allow the load balancer to choose tasks from source sched groups that best match their preferred LLCs.
---
Notes:
v3->v4:
Use rcu_dereference_all() for protection(Peter Zijlstra) Move the declaration of dst_llc variable under sched_cache_enabled(), and remove the corresponding ifdeffery(Peter Zijlstra)
kernel/sched/fair.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)
kernel/sched/fair.c +18 -0
@@ -10681,6 +10681,9 @@ struct sg_lb_stats {unsigned int nr_numa_running;unsigned int nr_preferred_running;#endif +#ifdef CONFIG_SCHED_CACHE +unsigned int nr_pref_dst_llc; +#endif };/*
@@ -11170,6 +11173,21 @@ static inline void update_sg_lb_stats(struct lb_env *env,if (cpu_overutilized (i)) *sg_overutilized =1 ; +#ifdef CONFIG_SCHED_CACHE +if (sched_cache_enabled ()) { +struct sched_domain *sd_tmp; +int dst_llc; + + dst_llc =llc_id (env->dst_cpu); +if (llc_id (i) != dst_llc) { + sd_tmp =rcu_dereference_all (rq->sd); +if (valid_llc_buf (sd_tmp, dst_llc)) + sgs->nr_pref_dst_llc += + sd_tmp->llc_counts[dst_llc]; + } + } +#endif +/* * No need to call idle_cpu() if nr_running is not 0 */
Signature · 1 line
2.32.0
PATCH v4 11/22 sched/cache: Check local_group only once in update_sg_lb_stats()
In reply to Tim ChenThere is no need to check the local group twice for both group_asym_packing and group_smt_balance. Adjust the code to facilitate future checks for group types (cache-aware load balancing) as well.
No functional changes are expected.
---
Notes:
v3->v4:
No change.kernel/sched/fair.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-)
kernel/sched/fair.c +10 -8
@@ -11228,14 +11228,16 @@ static inline void update_sg_lb_stats(struct lb_env *env, sgs->group_weight = group->group_weight; -/* Check if dst CPU is idle and preferred to this group */ -if (!local_group && env->idle && sgs->sum_h_nr_running && -sched_group_asym (env, sgs, group)) - sgs->group_asym_packing =1 ; - -/* Check for loaded SMT group to be balanced to dst CPU */ -if (!local_group &&smt_balance (env, sgs, group)) - sgs->group_smt_balance =1 ; +if (!local_group) { +/* Check if dst CPU is idle and preferred to this group */ +if (env->idle && sgs->sum_h_nr_running && +sched_group_asym (env, sgs, group)) + sgs->group_asym_packing =1 ; + +/* Check for loaded SMT group to be balanced to dst CPU */ +if (smt_balance (env, sgs, group)) + sgs->group_smt_balance =1 ; + } sgs->group_type =group_classify (env->sd->imbalance_pct, group, sgs);
Signature · 1 line
2.32.0
PATCH v4 12/22 sched/cache: Prioritize tasks preferring destination LLC during balancing
In reply to Tim ChenDuring LLC load balancing, first check for tasks that prefer the destination LLC and balance them to it before others.
Mark source sched groups containing tasks preferring non local LLCs with the group_llc_balance flag. This ensures the load balancer later pulls or pushes these tasks toward their preferred LLCs.
The priority of group_llc_balance is lower than that of group_overloaded and higher than that of all other group types. This is because group_llc_balance may exacerbate load imbalance, and if the LLC balancing attempt fails, the nr_balance_failed mechanism will trigger other group types to rebalance the load.
The load balancer selects the busiest sched_group and migrates tasks to less busy groups to distribute load across CPUs.
With cache-aware scheduling enabled, the busiest sched_group is the one with most tasks preferring the destination LLC. If the group has the llc_balance flag set, cache aware load balancing is triggered.
Introduce the helper function update_llc_busiest() to identify the sched_group with the most tasks preferring the destination LLC.
---
Notes:
v3->v4:
Add comments to explain LLC load balance priority. (Madadi Vineeth Reddy)
kernel/sched/fair.c | 79 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-)
kernel/sched/fair.c +78 -1
@@ -9747,6 +9747,16 @@ enum group_type {* from balancing the load across the system. */ group_imbalanced, +/* +* There are tasks running on non-preferred LLC, possible to move +* them to their preferred LLC without creating too much imbalance. +* The priority of group_llc_balance is lower than that of +* group_overloaded and higher than that of all other group types. +* This is because group_llc_balance may exacerbate load imbalance. +* If the LLC balancing attempt fails, the nr_balance_failed +* mechanism will trigger other group types to rebalance the load. +*/ + group_llc_balance,/* * The CPU is overloaded and can't provide expected CPU cycles to all * tasks.
@@ -10676,6 +10686,7 @@ struct sg_lb_stats {enum group_type group_type;unsigned int group_asym_packing;/* Tasks should be moved to preferred CPU */ unsigned int group_smt_balance;/* Task on busy SMT be moved */ +unsigned int group_llc_balance;/* Tasks should be moved to preferred LLC */ unsigned long group_misfit_task_load;/* A CPU has a task too big for its capacity */ #ifdef CONFIG_NUMA_BALANCING unsigned int nr_numa_running;
@@ -10934,6 +10945,9 @@ group_type group_classify(unsigned int imbalance_pct,if (group_is_overloaded (imbalance_pct, sgs))return group_overloaded; +if (sgs->group_llc_balance) +return group_llc_balance; +if (sg_imbalanced (group))return group_imbalanced;
@@ -11128,11 +11142,63 @@ static void record_sg_llc_stats(struct lb_env *env,if (unlikely (READ_ONCE (sd_share->capacity) != sgs->group_capacity)) WRITE_ONCE(sd_share->capacity, sgs->group_capacity); } + +/* +* Do LLC balance on sched group that contains LLC, and have tasks preferring +* to run on LLC in idle dst_cpu. +*/ +static inline bool llc_balance (struct lb_env *env,struct sg_lb_stats *sgs, +struct sched_group *group) +{ +if (!sched_cache_enabled ()) +return false; + +if (env->sd->flags &SD_SHARE_LLC ) +return false; + +/* +* Skip cache aware tagging if nr_balanced_failed is sufficiently high. +* Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed +* to avoid excessive task migration at the same time. +*/ +if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries +1 ) +return false; + +if (sgs->nr_pref_dst_llc && +can_migrate_llc (cpumask_first (sched_group_span (group)), + env->dst_cpu,0 , true) == mig_llc) +return true; + +return false; +} + +static bool update_llc_busiest (struct lb_env *env, +struct sg_lb_stats *busiest, +struct sg_lb_stats *sgs) +{ +/* +* There are more tasks that want to run on dst_cpu's LLC. +*/ +return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc; +}#else static inline void record_sg_llc_stats (struct lb_env *env,struct sg_lb_stats *sgs,struct sched_group *group) { } + +static inline bool llc_balance (struct lb_env *env,struct sg_lb_stats *sgs, +struct sched_group *group) +{ +return false; +} + +static bool update_llc_busiest (struct lb_env *env, +struct sg_lb_stats *busiest, +struct sg_lb_stats *sgs) +{ +return false; +}#endif /**
@@ -11237,6 +11303,10 @@ static inline void update_sg_lb_stats(struct lb_env *env,/* Check for loaded SMT group to be balanced to dst CPU */ if (smt_balance (env, sgs, group)) sgs->group_smt_balance =1 ; + +/* Check for tasks in this group can be moved to their preferred LLC */ +if (llc_balance (env, sgs, group)) + sgs->group_llc_balance =1 ; } sgs->group_type =group_classify (env->sd->imbalance_pct, group, sgs);
@@ -11300,6 +11370,10 @@ static bool update_sd_pick_busiest(struct lb_env *env,/* Select the overloaded group with highest avg_load. */ return sgs->avg_load > busiest->avg_load; +case group_llc_balance: +/* Select the group with most tasks preferring dst LLC */ +return update_llc_busiest (env, busiest, sgs); +case group_imbalanced:/* * Select the 1st imbalanced group as we don't have any way to
@@ -11562,6 +11636,7 @@ static bool update_pick_idlest(struct sched_group *idlest,return false;break ; +case group_llc_balance:case group_imbalanced:case group_asym_packing:case group_smt_balance:
@@ -11694,6 +11769,7 @@ sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, intreturn NULL ;break ; +case group_llc_balance:case group_imbalanced:case group_asym_packing:case group_smt_balance:
@@ -12192,7 +12268,8 @@ static struct sched_group *sched_balance_find_src_group(struct lb_env *env)* group's child domain. */ if (sds.prefer_sibling && local->group_type == group_has_spare && -sibling_imbalance (env, &sds, busiest, local) >1 ) + (busiest->group_type == group_llc_balance || +sibling_imbalance (env, &sds, busiest, local) >1 )) goto force_balance;if (busiest->group_type != group_overloaded) {
Signature · 1 line
2.32.0
PATCH v4 13/22 sched/cache: Add migrate_llc_task migration type for cache-aware balancing
In reply to Tim ChenIntroduce a new migration type, migrate_llc_task, to support cache-aware load balancing.
After identifying the busiest sched_group (having the most tasks preferring the destination LLC), mark migrations with this type. During load balancing, each runqueue in the busiest sched_group is examined, and the runqueue with the highest number of tasks preferring the destination CPU is selected as the busiest runqueue.
---
Notes:
v3->v4:
No change.kernel/sched/fair.c | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-)
kernel/sched/fair.c +37 -1
@@ -9768,7 +9768,8 @@ enum migration_type { migrate_load =0 , migrate_util, migrate_task, - migrate_misfit + migrate_misfit, + migrate_llc_task };#define LBF_ALL_PINNED 0x01
@@ -10382,6 +10383,10 @@ static int detach_tasks(struct lb_env *env) env->imbalance =0 ;break ; + +case migrate_llc_task: + env->imbalance--; +break ; }detach_task (p, env);
@@ -12022,6 +12027,15 @@ static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sreturn ; } +#ifdef CONFIG_SCHED_CACHE +if (busiest->group_type == group_llc_balance) { +/* Move a task that prefer local LLC */ + env->migration_type = migrate_llc_task; + env->imbalance =1 ; +return ; + } +#endif +if (busiest->group_type == group_imbalanced) {/* * In the group_imb case we cannot rely on group-wide averages
@@ -12328,7 +12342,10 @@ static struct rq *sched_balance_find_src_rq(struct lb_env *env, {struct rq *busiest =NULL , *rq;unsigned long busiest_util =0 , busiest_load =0 , busiest_capacity =1 ; +unsigned int __maybe_unused busiest_pref_llc =0 ; +struct sched_domain __maybe_unused *sd_tmp;unsigned int busiest_nr =0 ; +int __maybe_unused dst_llc;int i;for_each_cpu_and (i,sched_group_span (group), env->cpus) {
@@ -12456,6 +12473,23 @@ static struct rq *sched_balance_find_src_rq(struct lb_env *env,break ; +case migrate_llc_task: +#ifdef CONFIG_SCHED_CACHE + sd_tmp =rcu_dereference_all (rq->sd); + dst_llc =llc_id (env->dst_cpu); + +if (valid_llc_buf (sd_tmp, dst_llc)) { +unsigned int this_pref_llc = + sd_tmp->llc_counts[dst_llc]; + +if (busiest_pref_llc < this_pref_llc) { + busiest_pref_llc = this_pref_llc; + busiest = rq; + } + } +#endif +break ; + } }
@@ -12619,6 +12653,8 @@ static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sdcase migrate_misfit:__schedstat_add (sd->lb_imbalance_misfit[idle], env->imbalance);break ; +case migrate_llc_task: +break ; } }
Signature · 1 line
2.32.0
PATCH v4 14/22 sched/cache: Handle moving single tasks to/from their preferred LLC
In reply to Tim ChenCache aware scheduling mainly does two things:
1. Prevent task from migrating out of its preferred LLC if not nessasary.
2. Migrating task to their preferred LLC if nessasary.
For 1:
In the generic load balance, if the busiest runqueue has only one task, active balancing may be invoked to move it away. However, this migration might break LLC locality.
Prevent regular load balance from migrating a task that prefers the current LLC. The load level and imbalance do not warrant breaking LLC preference per the can_migrate_llc() policy. Here, the benefit of LLC locality outweighs the power efficiency gained from migrating the only runnable task away.
Before migration, check whether the task is running on its preferred
LLC: Do not move a lone task to another LLC if it would move the task away from its preferred LLC or cause excessive imbalance between LLCs.
For 2:
On the other hand, if the migration type is migrate_llc_task, it means that there are tasks on the env->src_cpu that want to be migrated to their preferred LLC, launch the active load balance anyway.
---
Notes:
v3->v4:
Use rcu_dereference_all() in alb_break_llc().
Add comments to explain the scenario to inhibit active balancing for cache aware aggregation.
kernel/sched/fair.c | 54 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-)
kernel/sched/fair.c +53 -1
@@ -10115,12 +10115,60 @@ static __maybe_unused enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu task_util(p), to_pref); } +/* +* Check if active load balance breaks LLC locality in +* terms of cache aware load balance. The load level and +* imbalance do not warrant breaking LLC preference per +* the can_migrate_llc() policy. Here, the benefit of +* LLC locality outweighs the power efficiency gained from +* migrating the only runnable task away. +*/ +static inline bool +alb_break_llc (struct lb_env *env) +{ +if (!sched_cache_enabled ()) +return false; + +if (cpus_share_cache (env->src_cpu, env->dst_cpu)) +return false; +/* +* All tasks prefer to stay on their current CPU. +* Do not pull a task from its preferred CPU if: +* 1. It is the only task running there(not too imbalance); OR +* 2. Migrating it away from its preferred LLC would violate +* the cache-aware scheduling policy. +*/ +if (env->src_rq->nr_pref_llc_running && + env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) { +unsigned long util =0 ; +struct task_struct *cur; + +if (env->src_rq->nr_running <=1 ) +return true; + + cur =rcu_dereference_all (env->src_rq->curr); +if (cur) + util =task_util (cur); + +if (can_migrate_llc (env->src_cpu, env->dst_cpu, + util, false) == mig_forbid) +return true; + } + +return false; +}#else static inline bool get_llc_stats (int cpu,unsigned long *util,unsigned long *cap) {return false; } + +static inline bool +alb_break_llc (struct lb_env *env) +{ +return false; +}#endif /* * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
@@ -12541,6 +12589,9 @@ static int need_active_balance(struct lb_env *env) {struct sched_domain *sd = env->sd; +if (alb_break_llc (env)) +return 0 ; +if (asym_active_balance (env))return 1 ;
@@ -12560,7 +12611,8 @@ static int need_active_balance(struct lb_env *env)return 1 ; } -if (env->migration_type == migrate_misfit) +if (env->migration_type == migrate_misfit || + env->migration_type == migrate_llc_task)return 1 ;return 0 ;
Signature · 1 line
2.32.0
PATCH v4 15/22 sched/cache: Respect LLC preference in task migration and detach
In reply to Tim ChenDuring load balancing, make can_migrate_task() consider a task's LLC preference.
Prevent a task from being moved out of its preferred LLC.
During the regular load balancing, if
the task cannot be migrated due to LLC locality, the nr_balance_failed also should not be increased.
---
Notes:
v3->v4:
Fix the bug in migrate_degrades_llc() that p->preferred_llc should be used for comparison rather than task_llc(p). (Madadi Vineeth Reddy)
Let nr_balance_failed overwrite cache-aware migration if the former is too high. (Peter Zijlstra, K Prateek Nayak)
kernel/sched/fair.c | 83 +++++++++++++++++++++++++++++++++++++++++--- kernel/sched/sched.h | 13 +++++++ 2 files changed, 91 insertions(+), 5 deletions(-)
kernel/sched/fair.c +78 -5
@@ -9777,6 +9777,7 @@ enum migration_type {#define LBF_DST_PINNED 0x04#define LBF_SOME_PINNED 0x08#define LBF_ACTIVE_LB 0x10 +#define LBF_LLC_PINNED 0x20struct lb_env {struct sched_domain *sd;
@@ -10089,8 +10090,8 @@ static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu,* Check if task p can migrate from source LLC to * destination LLC in terms of cache aware load balance. */ -static __maybe_unused enum llc_mig can_migrate_llc_task (int src_cpu,int dst_cpu, -struct task_struct *p) +static enum llc_mig can_migrate_llc_task (int src_cpu,int dst_cpu, +struct task_struct *p) {struct mm_struct *mm;bool to_pref;
@@ -10157,6 +10158,46 @@ alb_break_llc(struct lb_env *env) return false; } + +/* +* Check if migrating task p from env->src_cpu to +* env->dst_cpu breaks LLC localiy. +*/ +static bool migrate_degrades_llc (struct task_struct *p,struct lb_env *env) +{ +if (!sched_cache_enabled ()) +return false; + +if (task_has_sched_core (p)) +return false; +/* +* Skip over tasks that would degrade LLC locality; +* only when nr_balanced_failed is sufficiently high do we +* ignore this constraint. +* +* Threshold of cache_nice_tries is set to 1 higher +* than nr_balance_failed to avoid excessive task +* migration at the same time. +*/ +if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries +1 ) +return false; + +/* +* We know the env->src_cpu has some tasks prefer to +* run on env->dst_cpu, skip the tasks do not prefer +* env->dst_cpu, and find the one that prefers. +*/ +if (env->migration_type == migrate_llc_task && +READ_ONCE (p->preferred_llc) !=llc_id (env->dst_cpu)) +return true; + +if (can_migrate_llc_task (env->src_cpu, + env->dst_cpu, p) != mig_forbid) +return false; + +return true; +} +#else static inline bool get_llc_stats (int cpu,unsigned long *util,unsigned long *cap)
@@ -10169,6 +10210,12 @@ alb_break_llc(struct lb_env *env) {return false; } + +static inline bool +migrate_degrades_llc (struct task_struct *p,struct lb_env *env) +{ +return false; +}#endif /* * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
@@ -10266,10 +10313,29 @@ int can_migrate_task(struct task_struct *p, struct lb_env *env)return 1 ; degrades =migrate_degrades_locality (p, env); -if (!degrades) +if (!degrades) { +/* +* If the NUMA locality is not broken, +* further check if migration would hurt +* LLC locality. +*/ +if (migrate_degrades_llc (p, env)) { +/* +* If regular load balancing fails to pull a task +* due to LLC locality, this is expected behavior +* and we set LBF_LLC_PINNED so we don't increase +* nr_balance_failed unecessarily. +*/ +if (env->migration_type != migrate_llc_task) + env->flags |=LBF_LLC_PINNED ; + +return 0 ; + } + hot =task_hot (p, env); -else + }else { hot = degrades >0 ; + }if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {if (hot)
@@ -12910,9 +12976,16 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,* * Similarly for migration_misfit which is not related to * load/util migration, don't pollute nr_balance_failed. +* +* The same for cache aware scheduling's allowance for +* load imbalance. If regular load balance does not +* migrate task due to LLC locality, it is a expected +* behavior and don't pollute nr_balance_failed. +* See can_migrate_task(). */ if (idle !=CPU_NEWLY_IDLE && - env.migration_type != migrate_misfit) + env.migration_type != migrate_misfit && + !(env.flags &LBF_LLC_PINNED )) sd->nr_balance_failed++;if (need_active_balance (&env)) {
kernel/sched/sched.h +13 -0
@@ -1546,6 +1546,14 @@ extern void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags);extern void sched_core_get (void );extern void sched_core_put (void ); +static inline bool task_has_sched_core (struct task_struct *p) +{ +if (sched_core_disabled ()) +return false; + +return !!p->core_cookie; +} +#else /* !CONFIG_SCHED_CORE: */ static inline bool sched_core_enabled (struct rq *rq)
@@ -1586,6 +1594,11 @@ static inline bool sched_group_cookie_match(struct rq *rq, return true; } +static inline bool task_has_sched_core (struct task_struct *p) +{ +return false; +} +#endif /* !CONFIG_SCHED_CORE */ #ifdef CONFIG_RT_GROUP_SCHED
Signature · 1 line
2.32.0
PATCH v4 16/22 sched/cache: Disable cache aware scheduling for processes with high thread counts
In reply to Tim ChenFrom: Chen Yu <[email protected]>
A performance regression was observed by Prateek when running hackbench with many threads per process (high fd count). To avoid this, processes with a large number of active threads are excluded from cache-aware scheduling.
With sched_cache enabled, record the number of active threads in each process during the periodic task_cache_work(). While iterating over CPUs, if the currently running task belongs to the same process as the task that launched task_cache_work(), increment the active thread count.
If the number of active threads within the process exceeds the number of Cores(divided by SMTs number) in the LLC, do not enable cache-aware scheduling. However, on system with smaller number of CPUs within 1 LLC, like Power10/Power11 with SMT4 and LLC size of 4, this check effectively disables cache-aware scheduling for any process. One possible solution suggested by Peter is to use a LLC-mask instead of a single LLC value for preference. Once there are a 'few' LLCs as preference, this constraint becomes a little easier. It could be an enhancement in the future.
For users who wish to perform task aggregation regardless, a debugfs knob is provided for tuning in a subsequent patch.
---
Notes:
v3->v4:
Use cpu_smt_num_threads instead of cpumask_weight(cpu_smt_mask(cpu)) (Peter Zijlstra)
include/linux/sched.h | 1 + kernel/sched/fair.c | 54 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 51 insertions(+), 4 deletions(-)
include/linux/sched.h +1 -0
@@ -2392,6 +2392,7 @@ struct sched_cache_stat {struct sched_cache_time __percpu *pcpu_sched;raw_spinlock_t lock;unsigned long epoch; +u64 nr_running_avg;int cpu; }____cacheline_aligned_in_smp ;
kernel/sched/fair.c +50 -4
100 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 17/22 sched/cache: Avoid cache-aware scheduling for memory-heavy processes
In reply to Tim ChenFrom: Chen Yu <[email protected]>
Prateek and Tingyin reported that memory-intensive workloads (such as stream) can saturate memory bandwidth and caches on the preferred LLC when sched_cache aggregates too many threads.
To mitigate this, estimate a process's memory footprint by comparing its RSS (anonymous and shared pages) to the size of the LLC. If RSS exceeds the LLC size, skip cache-aware scheduling.
Note that RSS is only an approximation of the memory footprint. By default, the comparison is strict, but a later patch will allow users to provide a hint to adjust this threshold.
According to the test from Adam, some systems do not have shared L3 but with shared L2 as clusters. In this case, the L2 becomes the LLC[1].
Link[1]: https://lore.kernel.org/all/[email protected]/
---
Notes:
v3->v4:
No change.include/linux/cacheinfo.h | 21 ++++++++++------- kernel/sched/fair.c | 48 +++++++++++++++++++++++++++++++++++---- 2 files changed, 56 insertions(+), 13 deletions(-)
include/linux/cacheinfo.h +13 -8
@@ -113,18 +113,11 @@ int acpi_get_cache_info(unsigned int cpu,const struct attribute_group *cache_get_priv_group (struct cacheinfo *this_leaf); -/* -* Get the cacheinfo structure for the cache associated with @cpu at -* level @level. -* cpuhp lock must be held. -*/ -static inline struct cacheinfo *get_cpu_cacheinfo_level (int cpu,int level) +static inline struct cacheinfo *_get_cpu_cacheinfo_level (int cpu,int level) {struct cpu_cacheinfo *ci =get_cpu_cacheinfo (cpu);int i; -lockdep_assert_cpus_held (); -for (i =0 ; i < ci->num_leaves; i++) {if (ci->info_list[i].level == level) {if (ci->info_list[i].attributes &CACHE_ID )
@@ -136,6 +129,18 @@ static inline struct cacheinfo *get_cpu_cacheinfo_level(int cpu, int level)return NULL ; } +/* +* Get the cacheinfo structure for the cache associated with @cpu at +* level @level. +* cpuhp lock must be held. +*/ +static inline struct cacheinfo *get_cpu_cacheinfo_level (int cpu,int level) +{ +lockdep_assert_cpus_held (); + +return _get_cpu_cacheinfo_level (cpu, level); +} +/* * Get the id of the cache associated with @cpu at level @level. * cpuhp lock must be held.
kernel/sched/fair.c +43 -5
79 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 18/22 sched/cache: Enable cache aware scheduling for multi LLCs NUMA node
In reply to Tim ChenFrom: Chen Yu <[email protected]>
Introduce sched_cache_present to enable cache aware scheduling for multi LLCs NUMA node Cache-aware load balancing should only be enabled if there are more than 1 LLCs within 1 NUMA node. sched_cache_present is introduced to indicate whether this platform supports this topology.
Test results:
The first test platform is a 2 socket Intel Sapphire Rapids with 30 cores per socket. The DRAM interleaving is enabled in the BIOS so it essential has one NUMA node with two last level caches. There are 60 CPUs associated with each last level cache.
The second test platform is a AMD Genoa. There are 4 Nodes and 32 CPUs per node. Each node has 2 CCXs and each CCX has 16 CPUs.
hackbench/schbench/netperf/stream/stress-ng/chacha20 were launched on these two platforms.
[TL;DR]
Sappire Rapids:
hackbench shows significant improvement when the number of different active threads is below the capacity of a LLC. schbench shows limitted wakeup latency improvement. ChaCha20-xiangshan(risc-v simulator) shows good throughput improvement. No obvious difference was observed in netperf/stream/stress-ng in Hmean.
Genoa:
Significant improvement is observed in hackbench when the active number of threads is lower than the number of CPUs within 1 LLC. On v2, Aaron reported improvement of hackbench/redis when system is underloaded. ChaCha20-xiangshan shows huge throughput improvement. Phoronix has tested v1 and shows good improvements in 30+ cases[3]. No obvious difference was observed in netperf/stream/stress-ng in Hmean.
Detail:
Due to length constraints, data without much difference with baseline is not presented.
Sapphire Rapids:
[hackbench pipe]
================
case load baseline(std%) compare%( std%) threads-pipe-10 1-groups 1.00 ( 1.22) +26.09 ( 1.10) threads-pipe-10 2-groups 1.00 ( 4.90) +22.88 ( 0.18) threads-pipe-10 4-groups 1.00 ( 2.07) +9.00 ( 3.49) threads-pipe-10 8-groups 1.00 ( 8.13) +3.45 ( 3.62) threads-pipe-16 1-groups 1.00 ( 2.11) +26.30 ( 0.08) threads-pipe-16 2-groups 1.00 ( 15.13) -1.77 ( 11.89) threads-pipe-16 4-groups 1.00 ( 4.37) +0.58 ( 7.99) threads-pipe-16 8-groups 1.00 ( 2.88) +2.71 ( 3.50) threads-pipe-2 1-groups 1.00 ( 9.40) +22.07 ( 0.71) threads-pipe-2 2-groups 1.00 ( 9.99) +18.01 ( 0.95) threads-pipe-2 4-groups 1.00 ( 3.98) +24.66 ( 0.96) threads-pipe-2 8-groups 1.00 ( 7.00) +21.83 ( 0.23) threads-pipe-20 1-groups 1.00 ( 1.03) +28.84 ( 0.21) threads-pipe-20 2-groups 1.00 ( 4.42) +31.90 ( 3.15) threads-pipe-20 4-groups 1.00 ( 9.97) +4.56 ( 1.69) threads-pipe-20 8-groups 1.00 ( 1.87) +1.25 ( 0.74) threads-pipe-4 1-groups 1.00 ( 4.48) +25.67 ( 0.78) threads-pipe-4 2-groups 1.00 ( 9.14) +4.91 ( 2.08) threads-pipe-4 4-groups 1.00 ( 7.68) +19.36 ( 1.53) threads-pipe-4 8-groups 1.00 ( 10.79) +7.20 ( 12.20) threads-pipe-8 1-groups 1.00 ( 4.69) +21.93 ( 0.03) threads-pipe-8 2-groups 1.00 ( 1.16) +25.29 ( 0.65) threads-pipe-8 4-groups 1.00 ( 2.23) -1.27 ( 3.62) threads-pipe-8 8-groups 1.00 ( 4.65) -3.08 ( 2.75)
Note: The default number of fd in hackbench is changed from 20 to various values to ensure that threads fit within a single LLC, especially on AMD systems. Take "threads-pipe-8, 2-groups" for example, the number of fd is 8, and 2 groups are created.
[schbench]
The 99th percentile wakeup latency shows some improvements when the system is underload, while it does not bring much difference with the increasing of system utilization.
99th Wakeup Latencies Base (mean std) Compare (mean std) Change
=========================================================================
thread=2 9.00(0.00) 9.00(1.73) 0.00% thread=4 7.33(0.58) 6.33(0.58) +13.64% thread=8 9.00(0.00) 7.67(1.15) +14.78% thread=16 8.67(0.58) 8.67(1.53) 0.00% thread=32 9.00(0.00) 7.00(0.00) +22.22% thread=64 9.33(0.58) 9.67(0.58) -3.64% thread=128 12.00(0.00) 12.00(0.00) 0.00%
[chacha20 on simulated risc-v]
baseline:
Host time spent: 67861ms
cache aware scheduling enabled:
Host time spent: 54441ms
Time reduced by 24%
Genoa:
[hackbench pipe]
The default number of fd is 20, which exceed the number of CPUs in a LLC. So the fd is adjusted to 2, 4, 6, 8, 20 respectively. Exclude the result with large run-to-run variance, 10% ~ 50% improvement is observed when the system is underloaded:
[hackbench pipe]
================
case load baseline(std%) compare%( std%) threads-pipe-2 1-groups 1.00 ( 2.89) +47.33 ( 1.20) threads-pipe-2 2-groups 1.00 ( 3.88) +39.82 ( 0.61) threads-pipe-2 4-groups 1.00 ( 8.76) +5.57 ( 13.10) threads-pipe-20 1-groups 1.00 ( 4.61) +11.72 ( 1.06) threads-pipe-20 2-groups 1.00 ( 6.18) +14.55 ( 1.47) threads-pipe-20 4-groups 1.00 ( 2.99) +10.16 ( 4.49) threads-pipe-4 1-groups 1.00 ( 4.23) +43.70 ( 2.14) threads-pipe-4 2-groups 1.00 ( 3.68) +8.45 ( 4.04) threads-pipe-4 4-groups 1.00 ( 17.72) +2.42 ( 1.14) threads-pipe-6 1-groups 1.00 ( 3.10) +7.74 ( 3.83) threads-pipe-6 2-groups 1.00 ( 3.42) +14.26 ( 4.53) threads-pipe-6 4-groups 1.00 ( 10.34) +10.94 ( 7.12) threads-pipe-8 1-groups 1.00 ( 4.21) +9.06 ( 4.43) threads-pipe-8 2-groups 1.00 ( 1.88) +3.74 ( 0.58) threads-pipe-8 4-groups 1.00 ( 2.78) +23.96 ( 1.18)
[chacha20 on simulated risc-v]
Host time spent: 54762ms
Host time spent: 28295ms
Time reduced by 48%
---
Notes:
v3->v4:
Add test results into commit log.
kernel/sched/sched.h | 4 +++- kernel/sched/topology.c | 18 ++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-)
kernel/sched/sched.h +3 -1
@@ -4035,9 +4035,11 @@ static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct#endif /* !CONFIG_SCHED_MM_CID */ #ifdef CONFIG_SCHED_CACHE +DECLARE_STATIC_KEY_FALSE (sched_cache_present); +static inline bool sched_cache_enabled (void ) { -return false; +return static_branch_unlikely (&sched_cache_present); }#endif
kernel/sched/topology.c +16 -2
@@ -809,6 +809,7 @@ enum s_alloc { };#ifdef CONFIG_SCHED_CACHE +DEFINE_STATIC_KEY_FALSE (sched_cache_present);static bool alloc_sd_llc (const struct cpumask *cpu_map,struct s_data *d) {
@@ -2674,6 +2675,7 @@ static int build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr) { enum s_alloc alloc_state = sa_none; +bool has_multi_llcs = false;struct sched_domain *sd;struct s_data d;struct rq *rq =NULL ;
@@ -2784,10 +2786,12 @@ build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att* between LLCs and memory channels. */ nr_llcs = sd->span_weight / child->span_weight; -if (nr_llcs ==1 ) +if (nr_llcs ==1 ) { imb = sd->span_weight >>3 ; -else + }else { imb = nr_llcs; + has_multi_llcs = true; + } imb =max (1U , imb); sd->imb_numa_nr = imb;
@@ -2842,6 +2846,16 @@ build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att ret =0 ; error: +#ifdef CONFIG_SCHED_CACHE +/* +* TBD: check before writing to it. sched domain rebuild +* is not in the critical path, leave as-is for now. +*/ +if (!ret && has_multi_llcs) +static_branch_enable_cpuslocked (&sched_cache_present); +else +static_branch_disable_cpuslocked (&sched_cache_present); +#endif __free_domain_allocs (&d, alloc_state, cpu_map);return ret;
Signature · 1 line
2.32.0
PATCH v4 19/22 sched/cache: Allow the user space to turn on and off cache aware scheduling
In reply to Tim ChenFrom: Chen Yu <[email protected]>
Provide a debugfs directory llc_balancing, and a knob named "enabled" under it to allow the user to turn off and on the cache aware scheduling at runtime.
---
Notes:
v3->v4:
Create the debugfs knobs under debug/sched/llc_balancing directory. (Peter Zijlstra)
kernel/sched/debug.c | 48 +++++++++++++++++++++++++++++- kernel/sched/sched.h | 7 ++++- kernel/sched/topology.c | 65 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 2 deletions(-)
kernel/sched/debug.c +47 -1
@@ -209,6 +209,46 @@ static const struct file_operations sched_scaling_fops = { .release = single_release, }; +#ifdef CONFIG_SCHED_CACHE +static ssize_t +sched_cache_enable_write (struct file *filp,const char __user *ubuf, +size_t cnt,loff_t *ppos) +{ +bool val; +int ret; + + ret =kstrtobool_from_user (ubuf, cnt, &val); +if (ret) +return ret; + + sysctl_sched_cache_user = val; + +sched_cache_active_set_unlocked (); + +return cnt; +} + +static int sched_cache_enable_show (struct seq_file *m,void *v) +{ +seq_printf (m,"%d\n" , sysctl_sched_cache_user); +return 0 ; +} + +static int sched_cache_enable_open (struct inode *inode, +struct file *filp) +{ +return single_open (filp, sched_cache_enable_show,NULL ); +} + +static const struct file_operations sched_cache_enable_fops = { + .open = sched_cache_enable_open, + .write = sched_cache_enable_write, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; +#endif +#ifdef CONFIG_PREEMPT_DYNAMIC static ssize_t sched_dynamic_write(struct file *filp, const char __user *ubuf,
@@ -592,7 +632,7 @@ static void debugfs_ext_server_init(void)static __init int sched_init_debug (void ) { -struct dentry __maybe_unused *numa; +struct dentry __maybe_unused *numa, *llc; debugfs_sched =debugfs_create_dir ("sched" ,NULL );
@@ -625,6 +665,12 @@ static __init int sched_init_debug(void)debugfs_create_u32 ("hot_threshold_ms" ,0644 , numa, &sysctl_numa_balancing_hot_threshold);#endif /* CONFIG_NUMA_BALANCING */ +#ifdef CONFIG_SCHED_CACHE + llc =debugfs_create_dir ("llc_balancing" , debugfs_sched); +debugfs_create_file ("enabled" ,0644 , llc,NULL , + &sched_cache_enable_fops); +#endif +debugfs_create_file ("debug" ,0444 , debugfs_sched,NULL , &sched_debug_fops);debugfs_fair_server_init ();
kernel/sched/sched.h +6 -1
@@ -4036,11 +4036,16 @@ static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct#ifdef CONFIG_SCHED_CACHE DECLARE_STATIC_KEY_FALSE (sched_cache_present); +DECLARE_STATIC_KEY_FALSE (sched_cache_active); +extern int sysctl_sched_cache_user;static inline bool sched_cache_enabled (void ) { -return static_branch_unlikely (&sched_cache_present); +return static_branch_unlikely (&sched_cache_active); } + +extern void sched_cache_active_set_unlocked (void ); +#endif void sched_domains_free_llc_id (int cpu);
kernel/sched/topology.c +65 -0
84 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 20/22 sched/cache: Add user control to adjust the aggressiveness of cache-aware scheduling
In reply to Tim ChenFrom: Chen Yu <[email protected]>
Introduce a set of debugfs knobs to control how aggressive the cache aware scheduling do the task aggregation.
(1) aggr_tolerance
With sched_cache enabled, the scheduler uses a process's RSS as a proxy for its LLC footprint to determine if aggregating tasks on the preferred LLC could cause cache contention. If RSS exceeds the LLC size, aggregation is skipped. Some workloads with large RSS but small actual memory footprints may still benefit from aggregation. Since the kernel cannot efficiently track per-task cache usage (resctrl is user-space only), userspace can provide a more accurate hint.
Introduce /sys/kernel/debug/sched/llc_balancing/aggr_tolerance to let users control how strictly RSS limits aggregation. Values range from 0 to 100:
- 0: Cache-aware scheduling is disabled.
- 1: Strict; tasks with RSS larger than LLC size are skipped.
- >=100: Aggressive; tasks are aggregated regardless of RSS.
For example, with a 32MB L3 cache:
- aggr_tolerance=1 -> tasks with RSS > 32MB are skipped.
- aggr_tolerance=99 -> tasks with RSS > 784GB are skipped
(784GB = (1 + (99 - 1) * 256) * 32MB).
Similarly, /sys/kernel/debug/sched/llc_balancing/aggr_tolerance also controls how strictly the number of active threads is considered when doing cache aware load balance. The number of SMTs is also considered. High SMT counts reduce the aggregation capacity, preventing excessive task aggregation on SMT-heavy systems like Power10/Power11.
Yangyu suggested introducing separate aggregation controls for the number of active threads and memory RSS checks. Since there are plans to add per-process/task group controls, fine-grained tunables are deferred to that implementation.
(2) epoch_period, epoch_affinity_timeout, imb_pct, overaggr_pct are also turned into tunable.
---
Notes:
v3->v4:
Create the debugfs knobs under debug/sched/llc_balancing directory. (Peter Zijlstra)
kernel/sched/debug.c | 10 ++++++++ kernel/sched/fair.c | 60 ++++++++++++++++++++++++++++++++++++++------ kernel/sched/sched.h | 5 ++++ 3 files changed, 68 insertions(+), 7 deletions(-)
kernel/sched/debug.c +10 -0
@@ -669,6 +669,16 @@ static __init int sched_init_debug(void) llc =debugfs_create_dir ("llc_balancing" , debugfs_sched);debugfs_create_file ("enabled" ,0644 , llc,NULL , &sched_cache_enable_fops); +debugfs_create_u32 ("aggr_tolerance" ,0644 , llc, + &llc_aggr_tolerance); +debugfs_create_u32 ("epoch_period" ,0644 , llc, + &llc_epoch_period); +debugfs_create_u32 ("epoch_affinity_timeout" ,0644 , llc, + &llc_epoch_affinity_timeout); +debugfs_create_u32 ("overaggr_pct" ,0644 , llc, + &llc_overaggr_pct); +debugfs_create_u32 ("imb_pct" ,0644 , llc, + &llc_imb_pct);#endif debugfs_create_file ("debug" ,0444 , debugfs_sched,NULL , &sched_debug_fops);
kernel/sched/fair.c +53 -7
112 lines not on this page · raw message
kernel/sched/sched.h +5 -0
@@ -4038,6 +4038,11 @@ static inline void mm_cid_switch_to(struct task_struct *prev, struct task_structDECLARE_STATIC_KEY_FALSE (sched_cache_present);DECLARE_STATIC_KEY_FALSE (sched_cache_active);extern int sysctl_sched_cache_user; +extern unsigned int llc_aggr_tolerance; +extern unsigned int llc_epoch_period; +extern unsigned int llc_epoch_affinity_timeout; +extern unsigned int llc_imb_pct; +extern unsigned int llc_overaggr_pct;static inline bool sched_cache_enabled (void ) {
Signature · 1 line
2.32.0
PATCH v4 21/22 -- DO NOT APPLY!!! -- sched/cache/debug: Display the per LLC occupancy for each process via proc fs
In reply to Tim ChenFrom: Chen Yu <[email protected]>
Debug patch only.
Show the per-LLC occupancy in /proc/{PID}/schedstat, with each column corresponding to one LLC. This can be used to verify if the cache-aware load balancer works as expected by aggregating threads onto dedicated LLCs.
Suppose there are 2 LLCs and the sampling duration is 10 seconds:
Enable the cache aware load balance, LLC0 residency delta is 0, LLC1 is 12 seconds:
0 12281
disable the cache aware load balance, tasks are spread to 2 LLCs:
9299 5435
Note: The race condition is not properly dealt with in this patch; out-of-bounds access may be triggered during CPU hotplug due to max_llcs changes. Do not query per-LLC occupancy during CPU hotplug.
---
Notes:
v3->v4:
Minor fix.fs/proc/base.c | 31 +++++++++++++++++++++++++ include/linux/mm_types.h | 17 +++++++++++--- include/linux/sched.h | 6 +++++ kernel/sched/fair.c | 50 ++++++++++++++++++++++++++++++++++++---- 4 files changed, 97 insertions(+), 7 deletions(-)
fs/proc/base.c +31 -0
@@ -518,6 +518,37 @@ static int proc_pid_schedstat(struct seq_file *m, struct pid_namespace *ns, (unsigned long long )task->se.sum_exec_runtime, (unsigned long long )task->sched_info.run_delay, task->sched_info.pcount); +#ifdef CONFIG_SCHED_CACHE +if (sched_cache_inuse ()) { +struct mm_struct *mm = task->mm; +u64 *llc_runtime; +int mm_sched_llc; + +if (!mm) +return 0 ; + + llc_runtime =kcalloc (max_lid +1 ,sizeof (u64),GFP_KERNEL ); +if (!llc_runtime) +return 0 ; + +if (get_mm_per_llc_runtime (task, llc_runtime)) + goto out; + +if (mm->sc_stat.cpu ==-1 ) + mm_sched_llc =-1 ; +else + mm_sched_llc =llc_id (mm->sc_stat.cpu); + +for (int i =0 ; i <= max_lid; i++) +seq_printf (m,"%s%s%llu " , + i == task->preferred_llc ?"*" :"" , + i == mm_sched_llc ?"?" :"" , + llc_runtime[i]); +seq_puts (m,"\n" ); +out: +kfree (llc_runtime); + } +#endif return 0 ; }
include/linux/mm_types.h +14 -3
@@ -1579,17 +1579,26 @@ static inline unsigned int mm_cid_size(void)#ifdef CONFIG_SCHED_CACHE void mm_init_sched (struct mm_struct *mm, -struct sched_cache_time __percpu *pcpu_sched); +struct sched_cache_time __percpu *pcpu_sched, +struct sched_cache_time __percpu *pcpu_time);static inline int mm_alloc_sched_noprof (struct mm_struct *mm) {struct sched_cache_time __percpu *pcpu_sched = - alloc_percpu_noprof(struct sched_cache_time); + alloc_percpu_noprof(struct sched_cache_time), + *pcpu_time;if (!pcpu_sched)return -ENOMEM ; -mm_init_sched (mm, pcpu_sched); + pcpu_time = alloc_percpu_noprof(struct sched_cache_time); +if (!pcpu_time) { +free_percpu (pcpu_sched); +return -ENOMEM ; + } + +mm_init_sched (mm, pcpu_sched, pcpu_time); +return 0 ; }
@@ -1598,7 +1607,9 @@ static inline int mm_alloc_sched_noprof(struct mm_struct *mm)static inline void mm_destroy_sched (struct mm_struct *mm) {free_percpu (mm->sc_stat.pcpu_sched); +free_percpu (mm->sc_stat.pcpu_time); mm->sc_stat.pcpu_sched =NULL ; + mm->sc_stat.pcpu_time =NULL ; }#else /* !CONFIG_SCHED_CACHE */
include/linux/sched.h +6 -0
@@ -2390,12 +2390,18 @@ struct sched_cache_time {struct sched_cache_stat {struct sched_cache_time __percpu *pcpu_sched; +struct sched_cache_time __percpu *pcpu_time;raw_spinlock_t lock;unsigned long epoch;u64 nr_running_avg;int cpu; }____cacheline_aligned_in_smp ; +int get_mm_per_llc_runtime (struct task_struct *p,u64 *buf); +bool sched_cache_inuse (void ); +extern int max_lid; +int llc_id (int cpu); +#else struct sched_cache_stat { };
kernel/sched/fair.c +46 -4
104 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v4 22/22 -- DO NOT APPLY!!! -- sched/cache/debug: Add ftrace to track the load balance statistics
In reply to Tim ChenFrom: Chen Yu <[email protected]>
Debug patch only.
To help investigate any potential performance regressions caused by cache-aware scheduling in the future, introduce these ftrace events.
The user leverages these trace events (via bpftrace, etc.) to monitor the cache-aware load balancing activity - specifically, whether tasks are moved to their preferred LLC, moved out of their preferred LLC, whether cache-aware load balancing is skipped due to exceeding the memory footprint limit or too many active tasks, and the reason why LLC preferred migration is allowed or not.
Together with existing scheduler events, the newly introduced events above can be used to narrow down the performance regression. For example, the regression could be caused by excessive task migrations among CPUs, which can be tracked either by trace_sched_attach_task() or by checking the return value of select_task_rq_fair(). Alternatively, it could be caused by over-aggregation within a single LLC, which can be identified via context switch events.
The scanning time to find the hottest LLC is simply recorded, which can be used to evaluate whether the statistics calculation for cache-aware scheduling is costly.
---
Notes:
v3->v4:
Add more trace events.
include/trace/events/sched.h | 140 +++++++++++++++++++++++++++++++++++ kernel/sched/fair.c | 64 +++++++++++++--- 2 files changed, 192 insertions(+), 12 deletions(-)
include/trace/events/sched.h +140 -0
@@ -10,6 +10,146 @@#include <linux/tracepoint.h> #include <linux/binfmts.h> +#ifdef CONFIG_SCHED_CACHE +TRACE_EVENT (sched_llc_mig, + TP_PROTO(unsigned long dst_util, unsigned long dst_cap, + unsigned long src_util, unsigned long src_cap, + int to_pref, int mig_hint), + +TP_ARGS (dst_util, dst_cap, src_util, src_cap, to_pref, mig_hint), + +TP_STRUCT__entry ( + __field(unsigned long, dst_util) + __field(unsigned long, dst_cap) + __field(unsigned long, src_util) + __field(unsigned long, src_cap) + __field(int, to_pref) +__field (int, mig_hint) + ), + +TP_fast_assign ( + __entry->dst_util = dst_util; + __entry->dst_cap = dst_cap; + __entry->src_util = src_util; + __entry->src_cap = src_cap; + __entry->to_pref = to_pref; + __entry->mig_hint = mig_hint; + ), + +TP_printk ("dst_util=%lu dst_cap=%lu src_util=%lu src_cap=%lu to_pref=%d mig_hint=%d" , + __entry->dst_util, __entry->dst_cap, __entry->src_util, + __entry->src_cap, __entry->to_pref, __entry->mig_hint) +); + +TRACE_EVENT (sched_llc_scan, + + TP_PROTO(struct task_struct *t, unsigned long cost), + +TP_ARGS (t, cost), + +TP_STRUCT__entry ( + __array(char, comm, TASK_COMM_LEN) + __field(pid_t, pid) + __field(unsigned long, cost) + ), + +TP_fast_assign ( + memcpy(__entry->comm, t->comm, TASK_COMM_LEN); + __entry->pid = t->pid; + __entry->cost = cost; + ), + +TP_printk ("comm=%s pid=%d scan_cost=%lu" , + __entry->comm, __entry->pid, + __entry->cost) +); + +TRACE_EVENT (sched_exceed_llc_cap, + + TP_PROTO(struct task_struct *t, int exceeded, int scale, + unsigned long llc, unsigned long rss), + +TP_ARGS (t, exceeded, scale, llc, rss), + +TP_STRUCT__entry ( + __array(char, comm, TASK_COMM_LEN) + __field(pid_t, pid) + __field(int, exceeded) + __field(int, scale) + __field(unsigned long, llc) + __field(unsigned long, rss) + ), + +TP_fast_assign ( + memcpy(__entry->comm, t->comm, TASK_COMM_LEN); + __entry->pid = t->pid; + __entry->exceeded = exceeded; + __entry->scale = scale; + __entry->llc = llc; + __entry->rss = rss; + ), + +TP_printk ("comm=%s pid=%d exceed_cap=%d scale=%d llc=%lu rss=%lu" , + __entry->comm, __entry->pid, + __entry->exceeded, __entry->scale, + __entry->llc, __entry->rss) +); + +TRACE_EVENT (sched_exceed_llc_nr, + + TP_PROTO(struct task_struct *t, int exceeded), + +TP_ARGS (t, exceeded), + +TP_STRUCT__entry ( + __array(char, comm, TASK_COMM_LEN) + __field(pid_t, pid) +__field (int, exceeded) + ), + +TP_fast_assign ( + memcpy(__entry->comm, t->comm, TASK_COMM_LEN); + __entry->pid = t->pid; + __entry->exceeded = exceeded; + ), + +TP_printk ("comm=%s pid=%d exceed_nr=%d" , + __entry->comm, __entry->pid, + __entry->exceeded) +); + +TRACE_EVENT (sched_attach_task, + + TP_PROTO(struct task_struct *t, int pref_cpu, int pref_llc, + int attach_cpu, int attach_llc), + +TP_ARGS (t, pref_cpu, pref_llc, attach_cpu, attach_llc), + +TP_STRUCT__entry ( + __array(char, comm, TASK_COMM_LEN) + __field(pid_t, pid) + __field(int, pref_cpu) + __field(int, pref_llc) + __field(int, attach_cpu) +__field (int, attach_llc) + ), + +TP_fast_assign ( + memcpy(__entry->comm, t->comm, TASK_COMM_LEN); + __entry->pid = t->pid; + __entry->pref_cpu = pref_cpu; + __entry->pref_llc = pref_llc; + __entry->attach_cpu = attach_cpu; + __entry->attach_llc = attach_llc; + ), + +TP_printk ("comm=%s pid=%d pref_cpu=%d pref_llc=%d attach_cpu=%d attach_llc=%d" , + __entry->comm, __entry->pid, + __entry->pref_cpu, __entry->pref_llc, + __entry->attach_cpu, __entry->attach_llc) +); +#endif +/* * Tracepoint for calling kthread_stop, performed to end a kthread: */
kernel/sched/fair.c +52 -12
152 lines not on this page · raw message
Signature · 1 line
2.32.0
Peter Zijlstra
maintainerRe: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
In reply to Tim ChenQuoted 24 lines · Tim Chen
kernel/sched/fair.c +24
-0+static inline +void account_mm_sched (struct rq *rq,struct task_struct *p,s64 delta_exec) +{ +struct sched_cache_time *pcpu_sched; +struct mm_struct *mm = p->mm; +unsigned long epoch; + +if (!sched_cache_enabled ()) +return ; + +if (p->sched_class != &fair_sched_class) +return ; +/* +* init_task, kthreads and user thread created +* by user_mode_thread() don't have mm. +*/ +if (!mm || !mm->sc_stat.pcpu_sched) +return ; + + pcpu_sched =per_cpu_ptr (p->mm->sc_stat.pcpu_sched,cpu_of (rq)); + + scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) { +__update_mm_sched (rq, pcpu_sched); + pcpu_sched->runtime += delta_exec;
kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1402
Quoted 10 lines
kernel/sched/fair.c +10
-0+ rq->cpu_runtime += delta_exec; + epoch = rq->cpu_epoch; + } + +/* +* If this process hasn't hit task_cache_work() for a while, or it +* has only 1 thread, invalidate its preferred state. +*/ + if (time_after(epoch, + READ_ONCE(mm->sc_stat.epoch) + EPOCH_LLC_AFFINITY_TIMEOUT) ||
I really think that:
if (epoch - READ_ONCE(mm->sc_stat.epoch) > EPOCH_LLC_AFFINITY_TIMEOUT)
is simpler to read.
kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1403
Quoted 1 line
kernel/sched/fair.c +1
-0+ get_nr_threads(p) <= 1) {
And this, I just noticed this, why are we excluding tasks with one thread? The comment just states we are (doh), but utterly fails to explain why.
Quoted 4 lines
kernel/sched/fair.c +4
-0+if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; + } +}
Peter Zijlstra
maintainerRe: [Patch v4 16/22] sched/cache: Disable cache aware scheduling for processes with high thread counts
In reply to Tim ChenQuoted 30 lines · Tim Chen
kernel/sched/fair.c +9
-1@@ -1507,7 +1513,8 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)*/ if (time_after (epoch,READ_ONCE (mm->sc_stat.epoch) +EPOCH_LLC_AFFINITY_TIMEOUT ) || -get_nr_threads (p) <=1 ) { +get_nr_threads (p) <=1 || +exceed_llc_nr (mm,cpu_of (rq))) {if (mm->sc_stat.cpu !=-1 ) mm->sc_stat.cpu =-1 ; }@@ -1608,6 +1633,13 @@ static void task_cache_work(struct callback_head *work)if (p->flags &PF_EXITING )return ; +if (get_nr_threads (p) <=1 ) { +if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; + +return ; + } +if (!zalloc_cpumask_var (&cpus,GFP_KERNEL ))return ;@@ -10105,6 +10144,13 @@ static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu,if (cpu <0 ||cpus_share_cache (src_cpu, dst_cpu))return mig_unrestricted;
kernel/sched/fair.c static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu, · line 10156
Quoted 10 lines
kernel/sched/fair.c +7
-0+/* skip cache aware load balance for single/too many threads */ +if (get_nr_threads (p) <=1 ||exceed_llc_nr (mm, dst_cpu)) { +if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; +return mig_unrestricted; + } +if (cpus_share_cache (dst_cpu, cpu)) to_pref = true;else if (cpus_share_cache (src_cpu, cpu))
This is what that made me notice that weird get_nr_threads() <= 1 thing.
Peter Zijlstra
maintainerRe: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
In reply to Tim ChenQuoted 10 lines · Tim Chen
From: Chen Yu <[email protected]>
Prateek and Tingyin reported that memory-intensive workloads (such as stream) can saturate memory bandwidth and caches on the preferred LLC when
sched_cacheaggregates too many threads.To mitigate this, estimate a process's memory footprint by comparing its RSS (anonymous and shared pages) to the size of the LLC. If RSS exceeds the LLC size, skip cache-aware scheduling.
Quoted 6 lines
Note that RSS is only an approximation of the memory footprint. By default, the comparison is strict, but a later patch will allow users to provide a hint to adjust this threshold.
According to the test from Adam, some systems do not have shared L3 but with shared L2 as clusters. In this case, the L2 becomes the LLC[1].
This is pretty terrible. If you want LLC size, add it to the topology information (and ideally integrate with RDT) and make proportional to cpumask size, such that if someone cuts the domain in pieces, they get proportional size etc.
Also, if we have NUMA_BALANCING on, that can provide a much better estimate for the actual size.
Just using RSS seems like a very bad metric here.
Peter Zijlstra
maintainerRe: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
FWIW, I'm going to start auto-stripping *@gmail addresses soon. I'm getting sick and tired of those bounces. If Google doesn't care, I can't be arsed either.
Quoted 28 lines · Peter Zijlstra
Quoted 10 lines · Tim Chen
From: Chen Yu <[email protected]>
Prateek and Tingyin reported that memory-intensive workloads (such as stream) can saturate memory bandwidth and caches on the preferred LLC when
sched_cacheaggregates too many threads.To mitigate this, estimate a process's memory footprint by comparing its RSS (anonymous and shared pages) to the size of the LLC. If RSS exceeds the LLC size, skip cache-aware scheduling.
Quoted 6 lines
Note that RSS is only an approximation of the memory footprint. By default, the comparison is strict, but a later patch will allow users to provide a hint to adjust this threshold.
According to the test from Adam, some systems do not have shared L3 but with shared L2 as clusters. In this case, the L2 becomes the LLC[1].
This is pretty terrible. If you want LLC size, add it to the topology information (and ideally integrate with RDT) and make proportional to cpumask size, such that if someone cuts the domain in pieces, they get proportional size etc.
Also, if we have
NUMA_BALANCINGon, that can provide a much better estimate for the actual size.Just using RSS seems like a very bad metric here.
Re: [Patch v4 02/22] sched/cache: Limit the scan number of CPUs when calculating task occupancy
In reply to Tim ChenQuoted 11 lines · Tim Chen
From: Chen Yu <[email protected]>
When NUMA balancing is enabled, the kernel currently iterates over all online CPUs to aggregate process-wide occupancy data. On large systems, this global scan introduces significant overhead.
To reduce scan latency, limit the search to a subset of relevant CPUs:
1. The task's preferred NUMA node.
2. The node where the task is currently running.
3. The node that contains the task's current preferred LLC..
Quoted 7 lines
While focusing solely on the preferred NUMA node is ideal, a process-wide scan must remain flexible because the "preferred node" is a per-task attribute. Different threads within the same process may have different preferred nodes, causing the process-wide preference to migrate. Maintaining a mask that covers both the preferred and active running nodes ensures accuracy while significantly reducing the number of CPUs inspected.
To address the issue of scanning overhead, there is a more targeted approach: only scanning the CPUs actually accessed by the process, and evicting these CPUs when they remain unaccessed for a specific period of time.
This significantly reduces unnecessary scanning in most scenario. I have attached the patch below for review. Please feel free to integrate or modify these changes.
Thansk!
Luo Gengkun
From de33b29f31a882ac8c0038cac4ec659c7fdfe60d Mon Sep 17 00:00:00 2001
From: Luo Gengkun <[email protected]>
Date: Thu, 9 Apr 2026 07:22:16 +0000
Subject: [PATCH] sched/cache: Reduce the overhead of task_cache_work by only
scan the visisted cpus.
The overhead of task_cache_work is high, espeically in multi-NUMA system. Currently, task_cache_work try to find the pref_llc by scan all cpus in the system. However, most of these scans are meaningless, such as those for
cpus that have never been visited or were accessed a long time ago.
To address this problem, this patch introduces visited_cpus to track the
visited cpus and uses llc_epoch_visited_timeout to evict cpus that have
timed out.
---
include/linux/sched.h | 1 +
kernel/sched/debug.c | 2 ++
kernel/sched/fair.c | 19 ++++++++++++++++---
kernel/sched/sched.h | 1 +
4 files changed, 20 insertions(+), 3 deletions(-)
include/linux/sched.h +0 -0
index dfa4bfd099c6..f2327a13fda8 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -2390,6 +2390,7 @@ struct sched_cache_time {
struct sched_cache_stat {
struct sched_cache_time __percpu *pcpu_sched;
+ struct cpumask visited_cpus;
raw_spinlock_t lock;
unsigned long epoch;
u64 nr_running_avg; kernel/sched/debug.c +0 -0
index 4469e1c152c8..da66acabff4f 100644
--- a/kernel/sched/debug.c
+++ b/kernel/sched/debug.c
@@ -675,6 +675,8 @@ static __init int sched_init_debug(void)
&llc_epoch_period);
debugfs_create_u32("epoch_affinity_timeout", 0644, llc,
&llc_epoch_affinity_timeout); + debugfs_create_u32("epoch_visited_timeout", 0644, llc,
+ &llc_epoch_visited_timeout);
debugfs_create_u32("overaggr_pct", 0644, llc,
&llc_overaggr_pct);
debugfs_create_u32("imb_pct", 0644, llc, kernel/sched/fair.c +0 -0
index e4e22696a0b1..4ccabc412aa1 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -1285,6 +1285,7 @@ static void set_next_buddy(struct sched_entity *se);
__read_mostly unsigned int llc_aggr_tolerance = 1;
__read_mostly unsigned int llc_epoch_period = EPOCH_PERIOD;
__read_mostly unsigned int llc_epoch_affinity_timeout =EPOCH_LLC_AFFINITY_TIMEOUT;
+__read_mostly unsigned int llc_epoch_visited_timeout = EPOCH_LLC_AFFINITY_TIMEOUT;
__read_mostly unsigned int llc_imb_pct = 20;
__read_mostly unsigned int llc_overaggr_pct = 50;
@@ -1466,6 +1467,7 @@ void mm_init_sched(struct mm_struct *mm,
raw_spin_lock_init(&mm->sc_stat.lock);
mm->sc_stat.epoch = epoch;
mm->sc_stat.cpu = -1; + cpumask_clear(&mm->sc_stat.visited_cpus);
/*
* The update to mm->sc_stat should not be reordered
@@ -1582,6 +1584,7 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)
pcpu_sched->runtime += delta_exec;
rq->cpu_runtime += delta_exec;
epoch = rq->cpu_epoch; + cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
}
/* @@ -1724,7 +1727,10 @@ static void task_cache_work(struct callback_head *work)
return;
scoped_guard (cpus_read_lock) { - get_scan_cpumasks(cpus, p);
+ if (unlikely(llc_epoch_visited_timeout == 0))
+ get_scan_cpumasks(cpus, p);
+ else
+ cpumask_and(cpus, cpu_online_mask, &mm->sc_stat.visited_cpus);
for_each_cpu(cpu, cpus) {
/* XXX sched_cluster_active */ @@ -1736,8 +1742,15 @@ static void task_cache_work(struct callback_head *work)
continue;
for_each_cpu(i, sched_domain_span(sd)) { - occ = fraction_mm_sched(cpu_rq(i),
- per_cpu_ptr(mm->sc_stat.pcpu_sched, i));
+ struct rq *rq = cpu_rq(i);
+ struct sched_cache_time *pcpu_sched = per_cpu_ptr(mm->sc_stat.pcpu_sched, i); + /* Skip the rq that has not been hit for a long time */ + if (llc_epoch_visited_timeout && (rq->cpu_epoch - pcpu_sched->epoch) >
+ llc_epoch_visited_timeout) {
+ cpumask_clear_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
+ continue;
+ }
+ occ = fraction_mm_sched(rq, pcpu_sched);
a_occ += occ;
if (occ > m_occ) {
m_occ = occ;kernel/sched/sched.h +1 -0
@@ -4041,6 +4041,7 @@ extern int sysctl_sched_cache_user;extern unsigned int llc_aggr_tolerance;extern unsigned int llc_epoch_period;extern unsigned int llc_epoch_affinity_timeout; +extern unsigned int llc_epoch_visited_timeout;extern unsigned int llc_imb_pct;extern unsigned int llc_overaggr_pct;
--
2.34.1
Quoted 80 lines
Future work may integrate
numa_groupto further refine task aggregation.Suggested-by Madadi Vineeth Reddy <[email protected]>Signed-off-by Chen Yu <[email protected]>Co-developed-by Tim Chen <[email protected]>Signed-off-by Tim Chen <[email protected]>---
Notes:
v3->v4: New patch.kernel/sched/fair.c | 46 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-)kernel/sched/fair.c +45
-1@@ -1431,6 +1431,50 @@ static void task_tick_cache(struct rq *rq, struct task_struct *p) } } +static void get_scan_cpumasks (cpumask_var_t cpus,struct task_struct *p) +{ +#ifdef CONFIG_NUMA_BALANCING +int cpu, curr_cpu, pref_nid; + +if (!static_branch_likely (&sched_numa_balancing)) + goto out; + + cpu = p->mm->sc_stat.cpu; + curr_cpu =task_cpu (p); + +/* +* Scanning in the preferred NUMA node is ideal. However, the NUMA +* preferred node is per-task rather than per-process. It is possible +* for different threads of the process to have distinct preferred +* nodes; consequently, the process-wide preferred LLC may bounce +* between different nodes. As a workaround, maintain the scan +* CPU mask to also cover the process's current preferred LLC and the +* current running node to mitigate the bouncing risk. +* TBD: numa_group should be considered during task aggregation. +*/ + pref_nid = p->numa_preferred_nid; +/* honor the task's preferred node */ +if (pref_nid ==NUMA_NO_NODE ) + goto out; + +cpumask_or (cpus, cpus,cpumask_of_node (pref_nid)); + +/* honor the task's preferred LLC CPU */ +if (cpu !=-1 && !cpumask_test_cpu (cpu, cpus)) +cpumask_or (cpus, cpus, +cpumask_of_node (cpu_to_node (cpu))); + +/* make sure the task's current running node is included */ +if (!cpumask_test_cpu (curr_cpu, cpus)) +cpumask_or (cpus, cpus,cpumask_of_node (cpu_to_node (curr_cpu))); + +return ; + +out: +#endif +cpumask_copy (cpus, cpu_online_mask); +} +static void task_cache_work (struct callback_head *work) {struct task_struct *p = current;@@ -1451,7 +1495,7 @@ static void task_cache_work(struct callback_head *work)return ;scoped_guard (cpus_read_lock) { -cpumask_copy (cpus, cpu_online_mask); +get_scan_cpumasks (cpus, p);for_each_cpu (cpu, cpus) {/* XXX sched_cluster_active */
Peter Zijlstra
maintainerRe: [Patch v4 18/22] sched/cache: Enable cache aware scheduling for multi LLCs NUMA node
In reply to Tim ChenQuoted 25 lines · Tim Chen
kernel/sched/topology.c +2
-1@@ -809,6 +809,7 @@ enum s_alloc { };#ifdef CONFIG_SCHED_CACHE +DEFINE_STATIC_KEY_FALSE (sched_cache_present);static bool alloc_sd_llc (const struct cpumask *cpu_map,struct s_data *d) {@@ -2674,6 +2675,7 @@ static int build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr) { enum s_alloc alloc_state = sa_none; +bool has_multi_llcs = false;struct sched_domain *sd;struct s_data d;struct rq *rq =NULL ;@@ -2784,10 +2786,12 @@ build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att* between LLCs and memory channels. */ nr_llcs = sd->span_weight / child->span_weight; -if (nr_llcs ==1 )
kernel/sched/topology.c build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att · line 2797
Quoted 10 lines
kernel/sched/topology.c +4
-1+if (nr_llcs ==1 ) { imb = sd->span_weight >>3 ; - else + }else { imb = nr_llcs; + has_multi_llcs = true; + } imb =max (1U , imb); sd->imb_numa_nr = imb;
Well that all don't apply :/
Also, this seems sub-optimal, we can have multi-llc without NUMA.
Doesn't the LLC domain having a parent more or less imply there being multiple and we should be doing this, irrespective of having NUMA?
Peter Zijlstra
maintainerRe: [Patch v4 02/22] sched/cache: Limit the scan number of CPUs when calculating task occupancy
In reply to Luo GengkunQuoted 27 lines · Luo Gengkun
Quoted 11 lines · Tim Chen
From: Chen Yu <[email protected]>
When NUMA balancing is enabled, the kernel currently iterates over all online CPUs to aggregate process-wide occupancy data. On large systems, this global scan introduces significant overhead.
To reduce scan latency, limit the search to a subset of relevant CPUs:
1. The task's preferred NUMA node.
2. The node where the task is currently running.
3. The node that contains the task's current preferred LLC..Quoted 7 lines
While focusing solely on the preferred NUMA node is ideal, a process-wide scan must remain flexible because the "preferred node" is a per-task attribute. Different threads within the same process may have different preferred nodes, causing the process-wide preference to migrate. Maintaining a mask that covers both the preferred and active running nodes ensures accuracy while significantly reducing the number of CPUs inspected.
To address the issue of scanning overhead, there is a more targeted
approach: only scanning the CPUs actually accessed by the process, and evicting these CPUs when they remain unaccessed for a specific period of time.
Quoted 6 lines
This significantly reduces unnecessary scanning in most scenario. I have attached the patch below for review. Please feel free to integrate or modify these changes.
Thansk!
Luo Gengkun
Please fix your MUA, whatever you tried to send is horribly white space mangled.
Quoted 19 lines · Tim Chen
Chen Yu (10):
sched/cache: Limit the scan number of CPUs when calculating task
occupancy
sched/cache: Record per LLC utilization to guide cache aware
scheduling decisions
sched/cache: Introduce helper functions to enforce LLC migration
policy
sched/cache: Disable cache aware scheduling for processes with high
thread counts
sched/cache: Avoid cache-aware scheduling for memory-heavy processes sched/cache: Enable cache aware scheduling for multi LLCs NUMA node sched/cache: Allow the user space to turn on and off cache aware
scheduling
sched/cache: Add user control to adjust the aggressiveness of
cache-aware schedulingPeter Zijlstra (Intel) (1):
sched/cache: Introduce infrastructure for cache-aware load balancing
Quoted 14 lines
Tim Chen (11):
sched/cache: Make LLC id continuous
sched/cache: Assign preferred LLC ID to processes sched/cache: Track LLC-preferred tasks per runqueue sched/cache: Introduce per CPU's tasks LLC preference counter sched/cache: Calculate the percpu sd task LLC preference sched/cache: Count tasks prefering destination LLC in a sched group sched/cache: Checklocal_grouponly once inupdate_sg_lb_stats()sched/cache: Prioritize tasks preferring destination LLC during
balancing
sched/cache: Addmigrate_llc_taskmigration type for cache-aware
balancing
sched/cache: Handle moving single tasks to/from their preferred LLC sched/cache: Respect LLC preference in task migration and detach
I've applied a random subset of patches with random edits into queue.git sched/cache (based on tip/sched/core).
It builds, but is otherwise untested.
Please send patches against this tree; I'm hoping to stick this into sched/core after the next merge window.
If any one commit really needs amending, just send a replacement patch and I'll rebase. Just make sure to not loose the edits I made.
Re: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
In reply to Peter ZijlstraQuoted 38 lines · Peter Zijlstra
Quoted 24 lines · Tim Chen
kernel/sched/fair.c +24
-0+static inline +void account_mm_sched (struct rq *rq,struct task_struct *p,s64 delta_exec) +{ +struct sched_cache_time *pcpu_sched; +struct mm_struct *mm = p->mm; +unsigned long epoch; + +if (!sched_cache_enabled ()) +return ; + +if (p->sched_class != &fair_sched_class) +return ; +/* +* init_task, kthreads and user thread created +* by user_mode_thread() don't have mm. +*/ +if (!mm || !mm->sc_stat.pcpu_sched) +return ; + + pcpu_sched =per_cpu_ptr (p->mm->sc_stat.pcpu_sched,cpu_of (rq)); + + scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) { +__update_mm_sched (rq, pcpu_sched); + pcpu_sched->runtime += delta_exec;kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1402
Quoted 10 lines
kernel/sched/fair.c +10
-0+ rq->cpu_runtime += delta_exec; + epoch = rq->cpu_epoch; + } + +/* +* If this process hasn't hit task_cache_work() for a while, or it +* has only 1 thread, invalidate its preferred state. +*/ + if (time_after(epoch, + READ_ONCE(mm->sc_stat.epoch) + EPOCH_LLC_AFFINITY_TIMEOUT) ||I really think that:
Quoted 1 line
if (epoch - READ_ONCE(mm->sc_stat.epoch) > EPOCH_LLC_AFFINITY_TIMEOUT)
Sure. We can change it.
Quoted 9 lines
is simpler to read.
kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1403
Quoted 1 line
kernel/sched/fair.c +1
-0+ get_nr_threads(p) <= 1) {And this, I just noticed this, why are we excluding tasks with one thread? The comment just states we are (doh), but utterly fails to explain why.
The thought was that for a single thread, we will tend to place it in same LLC as it was previously running with cache hot. Incurring the added cost of tracking its residency in LLC is uneeded.
Tim
Quoted 5 lines
Quoted 5 lines
kernel/sched/fair.c +4
-0+if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; + } +}
Re: [Patch v4 16/22] sched/cache: Disable cache aware scheduling for processes with high thread counts
In reply to Peter ZijlstraQuoted 31 lines · Peter Zijlstra
Quoted 30 lines · Tim Chen
kernel/sched/fair.c +9
-1@@ -1507,7 +1513,8 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)*/ if (time_after (epoch,READ_ONCE (mm->sc_stat.epoch) +EPOCH_LLC_AFFINITY_TIMEOUT ) || -get_nr_threads (p) <=1 ) { +get_nr_threads (p) <=1 || +exceed_llc_nr (mm,cpu_of (rq))) {if (mm->sc_stat.cpu !=-1 ) mm->sc_stat.cpu =-1 ; }@@ -1608,6 +1633,13 @@ static void task_cache_work(struct callback_head *work)if (p->flags &PF_EXITING )return ; +if (get_nr_threads (p) <=1 ) { +if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; + +return ; + } +if (!zalloc_cpumask_var (&cpus,GFP_KERNEL ))return ;@@ -10105,6 +10144,13 @@ static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu,if (cpu <0 ||cpus_share_cache (src_cpu, dst_cpu))return mig_unrestricted;
Quoted 13 lines
kernel/sched/fair.c static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu, · line 10156
Quoted 10 lines
kernel/sched/fair.c +7
-0+/* skip cache aware load balance for single/too many threads */ +if (get_nr_threads (p) <=1 ||exceed_llc_nr (mm, dst_cpu)) { +if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; +return mig_unrestricted; + } +if (cpus_share_cache (dst_cpu, cpu)) to_pref = true;else if (cpus_share_cache (src_cpu, cpu))This is what that made me notice that weird
get_nr_threads()<= 1 thing.
With a single thread, we already have code like scanning in the same LLC in wake up, and migrate_degrades_locality() to keep it where its cache is hot. Adding a preferred_llc seems unnecessary.
Tim
Re: [Patch v4 18/22] sched/cache: Enable cache aware scheduling for multi LLCs NUMA node
In reply to Peter ZijlstraQuoted 40 lines · Peter Zijlstra
Quoted 25 lines · Tim Chen
kernel/sched/topology.c +2
-1@@ -809,6 +809,7 @@ enum s_alloc { };#ifdef CONFIG_SCHED_CACHE +DEFINE_STATIC_KEY_FALSE (sched_cache_present);static bool alloc_sd_llc (const struct cpumask *cpu_map,struct s_data *d) {@@ -2674,6 +2675,7 @@ static int build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr) { enum s_alloc alloc_state = sa_none; +bool has_multi_llcs = false;struct sched_domain *sd;struct s_data d;struct rq *rq =NULL ;@@ -2784,10 +2786,12 @@ build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att* between LLCs and memory channels. */ nr_llcs = sd->span_weight / child->span_weight; -if (nr_llcs ==1 )kernel/sched/topology.c build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *att · line 2797
Quoted 10 lines
kernel/sched/topology.c +4
-1+if (nr_llcs ==1 ) { imb = sd->span_weight >>3 ; - else + }else { imb = nr_llcs; + has_multi_llcs = true; + } imb =max (1U , imb); sd->imb_numa_nr = imb;Well that all don't apply :/
Quoted 4 lines
Also, this seems sub-optimal, we can have multi-llc without NUMA.
Doesn't the LLC domain having a parent more or less imply there being multiple and we should be doing this, irrespective of having NUMA?
If we have NUMA and single LLC, original thought was that NUMA balancing would be taking care of moving the tasks to preferred node. And that's why we thought it is not necessary to enable cache aware scheduling for that case. Yes, if there's no NUMA and we have a parent group for LLCs, agree that we should enable it.
Tim
Quoted 35 lines · Peter Zijlstra
Quoted 19 lines · Tim Chen
Chen Yu (10):
sched/cache: Limit the scan number of CPUs when calculating task
occupancy
sched/cache: Record per LLC utilization to guide cache aware
scheduling decisions
sched/cache: Introduce helper functions to enforce LLC migration
policy
sched/cache: Disable cache aware scheduling for processes with high
thread counts
sched/cache: Avoid cache-aware scheduling for memory-heavy processes sched/cache: Enable cache aware scheduling for multi LLCs NUMA node sched/cache: Allow the user space to turn on and off cache aware
scheduling
sched/cache: Add user control to adjust the aggressiveness of
cache-aware schedulingPeter Zijlstra (Intel) (1):
sched/cache: Introduce infrastructure for cache-aware load balancingQuoted 14 lines
Tim Chen (11):
sched/cache: Make LLC id continuous
sched/cache: Assign preferred LLC ID to processes sched/cache: Track LLC-preferred tasks per runqueue sched/cache: Introduce per CPU's tasks LLC preference counter sched/cache: Calculate the percpu sd task LLC preference sched/cache: Count tasks prefering destination LLC in a sched group sched/cache: Checklocal_grouponly once inupdate_sg_lb_stats()sched/cache: Prioritize tasks preferring destination LLC during
balancing
sched/cache: Addmigrate_llc_taskmigration type for cache-aware
balancing
sched/cache: Handle moving single tasks to/from their preferred LLC sched/cache: Respect LLC preference in task migration and detach
Quoted 4 lines
I've applied a random subset of patches with random edits into queue.git sched/cache (based on tip/sched/core).
It builds, but is otherwise untested.
Thanks Peter. We'll start testing your tree.
Tim
Quoted 6 lines
Please send patches against this tree; I'm hoping to stick this into sched/core after the next merge window.
If any one commit really needs amending, just send a replacement patch and I'll rebase. Just make sure to not loose the edits I made.
Peter Zijlstra
maintainerRe: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
In reply to Tim ChenQuoted 9 lines · Tim Chen
Quoted 5 lines
kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1403
Quoted 1 line
kernel/sched/fair.c +1
-0+ get_nr_threads(p) <= 1) {And this, I just noticed this, why are we excluding tasks with one thread? The comment just states we are (doh), but utterly fails to explain why.
The thought was that for a single thread, we will tend to place it in same LLC as it was previously running with cache hot. Incurring the added cost of tracking its residency in LLC is uneeded.
Not sure -- the moment it gets migrated away, it will stay away. There is no force to pull it back, while with cache aware it will try and come back for a short while -- until it's build an occupancy on the new llc.
Anyway, if you want to do this, it needs to be a separate patch.
Re: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
Quoted 8 lines · Peter Zijlstra
Quoted 6 lines · Tim Chen
Quoted 5 lines
kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1403
Quoted 1 line
kernel/sched/fair.c +1
-0+ get_nr_threads(p) <= 1) {And this, I just noticed this, why are we excluding tasks with one thread? The comment just states we are (doh), but utterly fails to explain why.
Quoted 8 lines
Quoted 3 lines
The thought was that for a single thread, we will tend to place it in same LLC as it was previously running with cache hot. Incurring the added cost of tracking its residency in LLC is uneeded.
Not sure -- the moment it gets migrated away, it will stay away. There is no force to pull it back, while with cache aware it will try and come back for a short while -- until it's build an occupancy on the new llc.
Besides Tim's scenario, in the original design, I thought the beneficiary of cache-aware scheduling was mainly multi-threaded processes, where threads share data with each other. Single-threaded processes normally exhibit no data sharing. This check was also introduced to prevent a single process
from concentrating excessively on one LLC. Nevertheless, we can omit this
check if the user provides hints for such single-threaded workloads, either via prctl or other interfaces in the future.
Quoted 1 line
Anyway, if you want to do this, it needs to be a separate patch.
OK, we will move this check into a separate one.
thanks,
Chenyu
Re: [Patch v4 02/22] sched/cache: Limit the scan number of CPUs when calculating task occupancy
In reply to Luo GengkunHi Gengkun,
Quoted 4 lines · Luo Gengkun
Quoted 1 line · Tim Chen
From: Chen Yu <[email protected]>
[ ... ]
Quoted 3 lines
To address the issue of scanning overhead, there is a more targeted approach: only scanning the CPUs actually accessed by the process, and evicting these CPUs when they remain unaccessed for a specific period of time.
Thanks for the patch. This approach looks quite sensible to me, and
[ ... ]
Review void account_mm_sched(struct rq *rq, struct · line 1588
Quoted 9 lines
/*
* The update tomm->sc_statshould not be reordered(quoted diff) +1
-0@@ -1582,6 +1584,7 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) pcpu_sched->runtime += delta_exec; rq->cpu_runtime += delta_exec; epoch = rq->cpu_epoch; + cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
I would refer a check before writing to avoid c2c overhead:
if (!cpumask_test_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus)) cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
Quoted 7 lines
(quoted diff) +0
-0}/*
(quoted diff) +0
-0@@ -1724,7 +1727,10 @@ static void task_cache_work(struct callback_head *work)
Review static void task_cache_work(struct callback_head · line 1736
Quoted 10 lines
(quoted diff) +4
-1return; scoped_guard (cpus_read_lock) { - get_scan_cpumasks(cpus, p); + if (unlikely(llc_epoch_visited_timeout == 0)) + get_scan_cpumasks(cpus, p); + else + cpumask_and(cpus, cpu_online_mask, &mm- >sc_stat.visited_cpus);
I believe this patch will bring significant benefits(reduce jitter) whenthe thread count is low, since it skips many CPUs. The only concern is the frequency of reading and writing the "global" mm->sc_stat.visited_cpus from multiple threads. However, if Peter's sbm can be leveraged in the future, this overhead should be further reduced. Anyway, let me run tests on our machines to seethe results. Much appreciated!
thanks,
Chenyu
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
In reply to Peter ZijlstraHi Peter,
Quoted 15 lines · Peter Zijlstra
Quoted 14 lines · Tim Chen
From: Chen Yu <[email protected]>
Prateek and Tingyin reported that memory-intensive workloads (such as stream) can saturate memory bandwidth and caches on the preferred LLC when
sched_cacheaggregates too many threads.To mitigate this, estimate a process's memory footprint by comparing its RSS (anonymous and shared pages) to the size of the LLC. If RSS exceeds the LLC size, skip cache-aware scheduling.
Note that RSS is only an approximation of the memory footprint. By default, the comparison is strict, but a later patch will allow users to provide a hint to adjust this threshold.
Quoted 8 lines
Quoted 2 lines
According to the test from Adam, some systems do not have shared L3 but with shared L2 as clusters. In this case, the L2 becomes the LLC[1].
This is pretty terrible. If you want LLC size, add it to the topology information (and ideally integrate with RDT) and make proportional to cpumask size, such that if someone cuts the domain in pieces, they get proportional size etc.
If I understand correctly, do you mean the following:
1.Introduce a generic arch_get_llc_size() as a wrapper
around the existing get_cpu_cacheinfo_level(), which returns the llc_size. Both the scheduler and RDT can use arch_get_llc_size().
2. The sched domain stores llc_size in sd->res_size = llc_size * sd_span / arch_llc_span, and the cache_aware_scheduler uses sd->res_size for the comparison.
We will adjust the code accordingly.
Quoted 5 lines
Also, if we have
NUMA_BALANCINGon, that can provide a much better estimate for the actual size.Just using RSS seems like a very bad metric here.
Got it. Currently we lack accurate memory footprint metrics in the kernel. If we support user-provided hints in the future, we can leverage RDT llc_occupancy metrics(Is it legal to use RDT's metrics directly in the kernel? It would switch from MSR-read to MMIO read thus less overhead). For now, let me have a try how to leverage NUMA fault-in stats. If NUMA balancing is off, I need to think more on how to avoid over-aggregation for memory-intensive workloads.
thanks,
Chenyu
Peter Zijlstra
maintainerRe: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Quoted 6 lines · Yu C
Quoted 5 lines
This is pretty terrible. If you want LLC size, add it to the topology information (and ideally integrate with RDT) and make proportional to cpumask size, such that if someone cuts the domain in pieces, they get proportional size etc.
Quoted 6 lines
If I understand correctly, do you mean the following:
1.Introduce a generic
arch_get_llc_size()as a wrapper
around the existingget_cpu_cacheinfo_level(), which returns thellc_size. Both the scheduler and RDT can usearch_get_llc_size().
The tie in with RDT was more to affect the return of arch_get_llc_size(). Eg. when RDT takes away some ways for specific tasks, then the total effective size gets reduced for generic use.
Quoted 4 lines
2. The sched domain stores
llc_sizeinsd->res_size=llc_size*sd_span/arch_llc_span, and thecache_aware_schedulerusessd->res_sizefor the comparison.
Just so.
Quoted 1 line
We will adjust the code accordingly.
Thanks.
Quoted 6 lines
Quoted 5 lines
Also, if we have
NUMA_BALANCINGon, that can provide a much better estimate for the actual size.Just using RSS seems like a very bad metric here.
Quoted 8 lines
Got it. Currently we lack accurate memory footprint metrics in the kernel. If we support user-provided hints in the future, we can leverage RDT
llc_occupancymetrics(Is it legal to use RDT's metrics directly in the kernel? It would switch from MSR-read to MMIO read thus less overhead). For now, let me have a try how to leverage NUMA fault-in stats. If NUMA balancing is off, I need to think more on how to avoid over-aggregation for memory-intensive workloads.
There is also things like this:
https://lkml.kernel.org/r/[email protected]
But yeah, in an ideal world we could be looking at LLC cache hit/miss information... streaming workloads would have very low hit rate.
But yes, possible prctl() controls could help, create tools to disable things per program etc.
Re: [Patch v4 02/22] sched/cache: Limit the scan number of CPUs when calculating task occupancy
In reply to Peter ZijlstraQuoted 32 lines · Peter Zijlstra
Quoted 31 lines · Luo Gengkun
Quoted 11 lines · Tim Chen
From: Chen Yu <[email protected]>
When NUMA balancing is enabled, the kernel currently iterates over all online CPUs to aggregate process-wide occupancy data. On large systems, this global scan introduces significant overhead.
To reduce scan latency, limit the search to a subset of relevant CPUs:
1. The task's preferred NUMA node.
2. The node where the task is currently running.
3. The node that contains the task's current preferred LLC..Quoted 7 lines
While focusing solely on the preferred NUMA node is ideal, a process-wide scan must remain flexible because the "preferred node" is a per-task attribute. Different threads within the same process may have different preferred nodes, causing the process-wide preference to migrate. Maintaining a mask that covers both the preferred and active running nodes ensures accuracy while significantly reducing the number of CPUs inspected.
To address the issue of scanning overhead, there is a more targeted
approach: only scanning the CPUs actually accessed by the process, and evicting these CPUs when they remain unaccessed for a specific period of time.This significantly reduces unnecessary scanning in most scenario. I have attached the patch below for review. Please feel free to integrate or modify these changes.
Quoted 6 lines
Quoted 2 lines
Thansk!
Luo GengkunPlease fix your MUA, whatever you tried to send is horribly white space mangled.
Apologies for the formatting mess. The following should display properly.
From de33b29f31a882ac8c0038cac4ec659c7fdfe60d Mon Sep 17 00:00:00 2001
From: Luo Gengkun <[email protected]>
Date: Thu, 9 Apr 2026 07:22:16 +0000
Subject: [PATCH] sched/cache: Reduce the overhead of task_cache_work by only
scan the visisted cpus.
The overhead of task_cache_work is high, espeically in multi-NUMA system. Currently, task_cache_work try to find the pref_llc by scan all cpus in the system. However, most of these scans are meaningless, such as those for cpus that have never been visited or were accessed a long time ago.
To address this problem, this patch introduces visited_cpus to track the visited cpus and uses llc_epoch_visited_timeout to evict cpus that have timed out.
--- include/linux/sched.h | 1 + kernel/sched/debug.c | 2 ++ kernel/sched/fair.c | 19 ++++++++++++++++--- kernel/sched/sched.h | 1 + 4 files changed, 20 insertions(+), 3 deletions(-)
include/linux/sched.h +1 -0
@@ -2390,6 +2390,7 @@ struct sched_cache_time {struct sched_cache_stat {struct sched_cache_time __percpu *pcpu_sched; +struct cpumask visited_cpus;raw_spinlock_t lock;unsigned long epoch;u64 nr_running_avg;
kernel/sched/debug.c +2 -0
@@ -675,6 +675,8 @@ static __init int sched_init_debug(void) &llc_epoch_period);debugfs_create_u32 ("epoch_affinity_timeout" ,0644 , llc, &llc_epoch_affinity_timeout); +debugfs_create_u32 ("epoch_visited_timeout" ,0644 , llc, + &llc_epoch_visited_timeout);debugfs_create_u32 ("overaggr_pct" ,0644 , llc, &llc_overaggr_pct); debugfs_create_u32("imb_pct", 0644, llc,
kernel/sched/fair.c +16 -3
@@ -1285,6 +1285,7 @@ static void set_next_buddy(struct sched_entity *se);__read_mostly unsigned int llc_aggr_tolerance =1 ;__read_mostly unsigned int llc_epoch_period =EPOCH_PERIOD ;__read_mostly unsigned int llc_epoch_affinity_timeout =EPOCH_LLC_AFFINITY_TIMEOUT ; +__read_mostly unsigned int llc_epoch_visited_timeout =EPOCH_LLC_AFFINITY_TIMEOUT ;__read_mostly unsigned int llc_imb_pct =20 ;__read_mostly unsigned int llc_overaggr_pct =50 ;
@@ -1466,6 +1467,7 @@ void mm_init_sched(struct mm_struct *mm,raw_spin_lock_init (&mm->sc_stat.lock); mm->sc_stat.epoch = epoch; mm->sc_stat.cpu =-1 ; +cpumask_clear (&mm->sc_stat.visited_cpus);/* * The update to mm->sc_stat should not be reordered
@@ -1582,6 +1584,7 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) pcpu_sched->runtime += delta_exec; rq->cpu_runtime += delta_exec; epoch = rq->cpu_epoch; +cpumask_set_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus); }/*
@@ -1724,7 +1727,10 @@ static void task_cache_work(struct callback_head *work)return ;scoped_guard (cpus_read_lock) { -get_scan_cpumasks (cpus, p); +if (unlikely (llc_epoch_visited_timeout ==0 )) +get_scan_cpumasks (cpus, p); +else +cpumask_and (cpus, cpu_online_mask, &mm->sc_stat.visited_cpus);for_each_cpu (cpu, cpus) {/* XXX sched_cluster_active */
@@ -1736,8 +1742,15 @@ static void task_cache_work(struct callback_head *work)continue ;for_each_cpu (i,sched_domain_span (sd)) { - occ =fraction_mm_sched (cpu_rq (i), -per_cpu_ptr (mm->sc_stat.pcpu_sched, i)); +struct rq *rq =cpu_rq (i); +struct sched_cache_time *pcpu_sched =per_cpu_ptr (mm->sc_stat.pcpu_sched, i); +/* Skip the rq that has not been hit for a long time */ +if (llc_epoch_visited_timeout && (rq->cpu_epoch - pcpu_sched->epoch) > + llc_epoch_visited_timeout) { +cpumask_clear_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus); +continue ; + } + occ =fraction_mm_sched (rq, pcpu_sched); a_occ += occ;if (occ > m_occ) { m_occ = occ;
kernel/sched/sched.h +1 -0
@@ -4041,6 +4041,7 @@ extern int sysctl_sched_cache_user;extern unsigned int llc_aggr_tolerance;extern unsigned int llc_epoch_period;extern unsigned int llc_epoch_affinity_timeout; +extern unsigned int llc_epoch_visited_timeout;extern unsigned int llc_imb_pct;extern unsigned int llc_overaggr_pct;
Signature · 1 line
2.34.1
Re: [Patch v4 02/22] sched/cache: Limit the scan number of CPUs when calculating task occupancy
In reply to Chen, Yu CQuoted 39 lines · Yu C
Hi Gengkun,
Quoted 4 lines · Luo Gengkun
Quoted 1 line · Tim Chen
From: Chen Yu <[email protected]>
[ ... ]
Quoted 3 lines
To address the issue of scanning overhead, there is a more targeted approach: only scanning the CPUs actually accessed by the process, and evicting these CPUs when they remain unaccessed for a specific period of time.
Thanks for the patch. This approach looks quite sensible to me, and
[ ... ]
Review void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) · line 1587
Quoted 8 lines
/*
* The update tomm->sc_statshould not be reordered(quoted diff) +1
-0@@ -1582,6 +1584,7 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) pcpu_sched->runtime += delta_exec; rq->cpu_runtime += delta_exec; epoch = rq->cpu_epoch; + cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);I would refer a check before writing to avoid c2c overhead:
if (!cpumask_test_cpu(cpu_of(rq),&mm->sc_stat.visited_cpus))cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);Quoted 8 lines
(quoted diff) +0
-0}/*
(quoted diff) +0
-0@@ -1724,7 +1727,10 @@ static void task_cache_work(struct callback_head *work) return;
Quoted 12 lines
Review static void task_cache_work(struct callback_head *work) · line 1735
Quoted 7 lines
(quoted diff) +4
-1scoped_guard (cpus_read_lock) { - get_scan_cpumasks(cpus, p); + if (unlikely(llc_epoch_visited_timeout == 0)) + get_scan_cpumasks(cpus, p); + else + cpumask_and(cpus, cpu_online_mask, &mm- >sc_stat.visited_cpus);I believe this patch will bring significant benefits(reduce jitter) whenthe thread count is low, since it skips many CPUs. The only concern is the frequency of reading and writing the "global"
mm->sc_stat.visited_cpusfrom multiple threads. However, if Peter's sbm can be leveraged in the future,
This is a problem, maybe a per-cpu version can help to avoid this problem. I'll try writing one.
Quoted 9 lines
this overhead should be further reduced. Anyway, let me run tests on our machines to seethe results. Much appreciated!
thanks,
Chenyu
Re: [Patch v4 02/22] sched/cache: Limit the scan number of CPUs when calculating task occupancy
In reply to Chen, Yu CQuoted 32 lines · Yu C
Hi Gengkun,
Quoted 4 lines · Luo Gengkun
Quoted 1 line · Tim Chen
From: Chen Yu <[email protected]>
[ ... ]
Quoted 6 lines
To address the issue of scanning overhead, there is a more targeted
approach: only scanning the CPUs actually accessed by the process, and evicting these CPUs when they remain unaccessed for a specific period of time.Thanks for the patch. This approach looks quite sensible to me, and
[ ... ]
Review void account_mm_sched(struct rq *rq, struct · line 1588
Quoted 9 lines
/*
* The update tomm->sc_statshould not be reordered(quoted diff) +1
-0@@ -1582,6 +1584,7 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) pcpu_sched->runtime += delta_exec; rq->cpu_runtime += delta_exec; epoch = rq->cpu_epoch; + cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);I would refer a check before writing to avoid c2c overhead:
Quoted 2 lines
if (!cpumask_test_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus)) cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
I think a similar check is also needed for clearing of visited CPU. It is possible that the visited_cpus mask has already been cleared long time back. Change
+ if (llc_epoch_visited_timeout && (rq->cpu_epoch - pcpu_sched->epoch) >
+ llc_epoch_visited_timeout) {
+ cpumask_clear_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
+ continue;
+ }
to
+ if (llc_epoch_visited_timeout &&
+ cpumask_test_cpu(cpu_of(rq), &mm->sc_stat.visitied_cpus) &&
+ (rq->cpu_epoch - pcpu_sched->epoch) > llc_epoch_visited_timeout) {
+ cpumask_clear_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
+ continue;
+ }
Thanks.
Tim
Re: [Patch v4 02/22] sched/cache: Limit the scan number of CPUs when calculating task occupancy
Quoted 14 lines · Tim Chen
Quoted 13 lines · Yu C
Hi Gengkun,
Quoted 9 lines · Luo Gengkun
Quoted 1 line · Tim Chen
From: Chen Yu <[email protected]>
task_struct*p, s64delta_exec)
pcpu_sched->runtime+=delta_exec;rq->cpu_runtime+=delta_exec;
epoch =rq->cpu_epoch;
+cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);
Quoted 7 lines
Quoted 3 lines
I would refer a check before writing to avoid c2c overhead:
if (!cpumask_test_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus)) cpumask_set_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus);I think a similar check is also needed for clearing of visited CPU. It is possible that the
visited_cpusmask has already been cleared long time back. Change
Yes, I agree, although we reach here when scanning the visited_cpus snapshot, there could be a race condition when we are in this loop but the CPU in visited_cpu has already been cleared.
thanks,
Chenyu
Quoted 21 lines
(quoted diff) +5
-0+ if (llc_epoch_visited_timeout && (rq->cpu_epoch - pcpu_sched->epoch) > + llc_epoch_visited_timeout) { + cpumask_clear_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus); + continue; + }to
(quoted diff) +6
-0+ if (llc_epoch_visited_timeout && + cpumask_test_cpu(cpu_of(rq), &mm->sc_stat.visitied_cpus) && + (rq->cpu_epoch - pcpu_sched->epoch) > llc_epoch_visited_timeout) { + cpumask_clear_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus); + continue; + }Thanks.
Tim
RFC PATCH 1/1 sched/fair: dynamically scale the period of cache work
When a preferred LLC is selected and remains stable, task_cache_work does not need to run frequently. Because it scans all system CPUs for computation, high-frequency execution hurts performance. We thus reduce the scan rate in such cases.
On the other hand, if the preferred node becomes suboptimal, we should increase the scan frequency to quickly find a better placement. The scan period is therefore dynamically adjusted.
---
Hi ChenYu, Tim, Gengkun,
I have another approach to address this issue, based on the observation that the scan work can be canceled if the preferred node is stable.This patch merely demonstrates the idea, but still needs more testing to verify its functionality. I'm sending it out early to gather feedback and opinions.
Thanks
Jianyong
--- include/linux/sched.h | 4 +++ kernel/sched/debug.c | 6 ++++ kernel/sched/fair.c | 69 ++++++++++++++++++++++++++++++++++++------- kernel/sched/sched.h | 3 ++ 4 files changed, 72 insertions(+), 10 deletions(-)
include/linux/sched.h +4 -0
@@ -2393,7 +2393,11 @@ struct sched_cache_stat {struct sched_cache_time __percpu *pcpu_time;raw_spinlock_t lock;unsigned long epoch; +unsigned long last_reset_tick; +unsigned long next_scan; +unsigned long scan_period;u64 nr_running_avg; +int need_scan;int cpu; }____cacheline_aligned_in_smp ;
kernel/sched/debug.c +6 -0
@@ -679,6 +679,12 @@ static __init int sched_init_debug(void) &llc_overaggr_pct);debugfs_create_u32 ("imb_pct" ,0644 , llc, &llc_imb_pct); +debugfs_create_u32 ("scan_period_max" ,0644 , llc, + &llc_scan_period_max); +debugfs_create_u32 ("scan_period_min" ,0644 , llc, + &llc_scan_period_min); +debugfs_create_u32 ("scan_period_threshold" ,0644 , llc, + &llc_scan_period_threshold);#endif debugfs_create_file ("debug" ,0444 , debugfs_sched,NULL , &sched_debug_fops);
kernel/sched/fair.c +59 -10
135 lines not on this page · raw message
kernel/sched/sched.h +3 -0
@@ -4043,6 +4043,9 @@ extern unsigned int llc_epoch_period;extern unsigned int llc_epoch_affinity_timeout;extern unsigned int llc_imb_pct;extern unsigned int llc_overaggr_pct; +extern unsigned int llc_scan_period_min; +extern unsigned int llc_scan_period_max; +extern unsigned int llc_scan_period_threshold;static inline bool sched_cache_enabled (void ) {
Signature · 1 line
2.34.1
Re: [RFC PATCH] sched/fair: dynamically scale the period of cache work
Hi Jianyong,
Quoted 11 lines · Jianyong Wu
When a preferred LLC is selected and remains stable,
task_cache_workdoes not need to run frequently. Because it scans all system CPUs for computation, high-frequency execution hurts performance. We thus reduce the scan rate in such cases.On the other hand, if the preferred node becomes suboptimal, we should increase the scan frequency to quickly find a better placement. The scan period is therefore dynamically adjusted.
Signed-off-by Jianyong Wu <[email protected]>
Quoted 9 lines
---
Hi ChenYu, Tim, Gengkun,I have another approach to address this issue, based on the observation that the scan work can be canceled if the preferred node is stable.This patch merely demonstrates the idea, but still needs more testing to verify its functionality. I'm sending it out early to gather feedback and opinions.
Thanks for providing this patch.
Quoted 11 lines
if (work->next == work) {kernel/sched/fair.c +1
-1@@ -1728,7 +1734,7 @@ static void task_cache_work(struct callback_head *work)struct task_struct *p = current, *cur;unsigned long curr_m_a_occ =0 ;struct mm_struct *mm = p->mm; -unsigned long m_a_occ =0 ; +unsigned long m_a_occ =0 , need_scan =0 , now;cpumask_var_t cpus;u64 t0, scan_cost;
kernel/sched/fair.c static void task_cache_work(struct callback_head *work) · line 1765
Quoted 7 lines
kernel/sched/fair.c +4
-0@@ -1753,6 +1759,12 @@ static void task_cache_work(struct callback_head *work) t0 =sched_clock_cpu (curr_cpu); + now = jiffies; +if (time_before (now,READ_ONCE (mm->sc_stat.next_scan))) +return ; +
I agree that limiting the scan rate would be useful, and your above change is actually similar to what NUMA balancing did in task_numa_work(). It allows only one thread within the same process to perform the statistics calculation, which avoids redundant computation.
kernel/sched/fair.c static void task_cache_work(struct callback_head *work) · line 1767
Quoted 2 lines
kernel/sched/fair.c +2
-0+WRITE_ONCE (mm->sc_stat.next_scan, (now + mm->sc_stat.scan_period)); +
I suppose the above should be try_cmpxchg()?
That is to say, with your above change, we have already limited the scan ratio for multi-threaded processes significantly. There appears to be no need to perform adaptive adjustment of scan_period - the benefit of introducing an adaptive scan_period may not offset the overhead of frequent writing to the "global" mm->sc_stat.scan_period due to c2c?
thanks,
Chenyu
RE: [RFC PATCH] sched/fair: dynamically scale the period of cache work
Hi Chenyu,
Quoted 73 lines
-----Original Message-----
From: Chen, Yu C <[email protected]>
Sent: Monday, April 13, 2026 4:38 PM
To: Jianyong Wu <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; Huangsj <[email protected]>; [email protected]
Subject: Re: [RFC PATCH] sched/fair: dynamically scale the period of cache workHi Jianyong,
Quoted 6 lines · Jianyong Wu
When a preferred LLC is selected and remains stable,
task_cache_workdoes not need to run frequently. Because it scans all system CPUs for computation, high-frequency execution hurts performance. We thus reduce the scan rate in such cases.On the other hand, if the preferred node becomes suboptimal, we
should
Quoted 5 lines
increase the scan frequency to quickly find a better placement. The scan period is therefore dynamically adjusted.
Signed-off-by Jianyong Wu <[email protected]>Quoted 9 lines
---
Hi ChenYu, Tim, Gengkun,I have another approach to address this issue, based on the observation that the scan work can be canceled if the preferred node is stable.This patch merely demonstrates the idea, but still needs more testing to verify its functionality. I'm sending it out early to gather feedback and opinions.
Thanks for providing this patch.
Review static void task_cache_work(struct
Quoted 2 lines
if (work->next == work) {(quoted diff) +0
-0@@ -1728,7 +1734,7 @@ static void task_cache_work(struct
callback_head*work)Quoted 9 lines
kernel/sched/fair.c +1
-1struct task_struct *p = current, *cur;unsigned long curr_m_a_occ =0 ;struct mm_struct *mm = p->mm; -unsigned long m_a_occ =0 ; +unsigned long m_a_occ =0 , need_scan =0 , now;cpumask_var_t cpus;u64 t0, scan_cost;kernel/sched/fair.c static void task_cache_work(struct · line 1766
Quoted 8 lines
kernel/sched/fair.c +4
-0@@ -1753,6 +1759,12 @@ static void task_cache_work(struct callback_head *work) t0 =sched_clock_cpu (curr_cpu); + now = jiffies; +if (time_before (now,READ_ONCE (mm->sc_stat.next_scan))) +return ; +I agree that limiting the scan rate would be useful, and your above change is actually similar to what NUMA balancing did in
task_numa_work(). It allows only one thread within the same process to perform the statistics calculation, which avoids redundant computation.
Quoted 5 lines
Review static void task_cache_work(struct · line 1767
Quoted 1 line
(quoted diff) +1
-0+ WRITE_ONCE(mm->sc_stat.next_scan, (now +
mm->sc_stat.scan_period));Review static void task_cache_work(struct · line 1768
Quoted 1 line
(quoted diff) +1
-0+I suppose the above should be
try_cmpxchg()?
Even though the update is not observed by others, it may not be a big problem. However, using try_cmpxchg may incur more overhead than WRITE_ONCE.
So, I wonder if we can tolerate such a loss of "correctness" for the sake of performance.
Quoted 7 lines
That is to say, with your above change, we have already limited the scan ratio for multi-threaded processes significantly. There appears to be no need to perform adaptive adjustment of
scan_period- the benefit of introducing an adaptivescan_periodmay not offset the overhead of frequent writing to the "global"mm->sc_stat.scan_perioddue to c2c?
If we can increase the scan period, the operations inside the scan work will
not be executed frequently. Thus, there is little overhead from writing to the global variable. This only occurs when the preferred node is unstable and the scan work runs frequently. If the preferred node remains stable most of the time, we can still benefit from it.
Thanks
Jianyong
Quoted 5 lines
thanks,
Chenyu
Thanks for your patch series.
I've tested the changes on my hygon servers (model 4h, 6h, 7h, 8h)
with kernel version 7.0.0-rc7 and no performance regression is observed.P.S. the patch from https://lore.kernel.org/lkml/[email protected]/ is include in these tests.
PATCH v2 1/1 sched/cache: Reduce the overhead of task_cache_work by only scan the visisted cpus.
In reply to Chen, Yu CThe overhead of task_cache_work is high, espeically in multi-NUMA system. Currently, task_cache_work try to find the pref_llc by scan all cpus in the system. However, most of these scans are meaningless, such as those for cpus that have never been visited or were accessed a long time ago.
To address this problem, this patch introduces visited_cpus to track the visited cpus and uses llc_epoch_visited_timeout to evict cpus that have timed out.
---
Thanks for the reviews. I've updated the patch based on your feedback.
v2 Changes:
1. Added a pre-check before set/clear visited_cpus to avoid C2C overhead.
2. Optimized llc_epoch_visited_timeout by using a static key to minimize overhead.
--- include/linux/sched.h | 1 + kernel/sched/debug.c | 50 +++++++++++++++++++++++++++++++++++++++++++ kernel/sched/fair.c | 25 +++++++++++++++++++--- kernel/sched/sched.h | 6 ++++++ 4 files changed, 79 insertions(+), 3 deletions(-)
include/linux/sched.h +1 -0
@@ -2390,6 +2390,7 @@ struct sched_cache_time {struct sched_cache_stat {struct sched_cache_time __percpu *pcpu_sched; +struct cpumask visited_cpus;raw_spinlock_t lock;unsigned long epoch;u64 nr_running_avg;
kernel/sched/debug.c +50 -0
62 lines not on this page · raw message
kernel/sched/fair.c +22 -3
@@ -1285,9 +1285,12 @@ static void set_next_buddy(struct sched_entity *se);__read_mostly unsigned int llc_aggr_tolerance =1 ;__read_mostly unsigned int llc_epoch_period =EPOCH_PERIOD ;__read_mostly unsigned int llc_epoch_affinity_timeout =EPOCH_LLC_AFFINITY_TIMEOUT ; +__read_mostly unsigned int llc_epoch_visited_timeout =EPOCH_LLC_AFFINITY_TIMEOUT ;__read_mostly unsigned int llc_imb_pct =20 ;__read_mostly unsigned int llc_overaggr_pct =50 ; +DEFINE_STATIC_KEY_TRUE (sched_cache_timeout); +static int llc_id (int cpu) {if (cpu <0 )
@@ -1466,6 +1469,7 @@ void mm_init_sched(struct mm_struct *mm,raw_spin_lock_init (&mm->sc_stat.lock); mm->sc_stat.epoch = epoch; mm->sc_stat.cpu =-1 ; +cpumask_clear (&mm->sc_stat.visited_cpus);/* * The update to mm->sc_stat should not be reordered
@@ -1582,6 +1586,9 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) pcpu_sched->runtime += delta_exec; rq->cpu_runtime += delta_exec; epoch = rq->cpu_epoch; +if (sched_cache_timeout_enabled () && + !cpumask_test_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus)) +cpumask_set_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus); }/*
@@ -1724,7 +1731,10 @@ static void task_cache_work(struct callback_head *work)return ;scoped_guard (cpus_read_lock) { -get_scan_cpumasks (cpus, p); +if (!sched_cache_timeout_enabled ()) +get_scan_cpumasks (cpus, p); +else +cpumask_and (cpus, cpu_online_mask, &mm->sc_stat.visited_cpus);for_each_cpu (cpu, cpus) {/* XXX sched_cluster_active */
@@ -1736,8 +1746,17 @@ static void task_cache_work(struct callback_head *work)continue ;for_each_cpu (i,sched_domain_span (sd)) { - occ =fraction_mm_sched (cpu_rq (i), -per_cpu_ptr (mm->sc_stat.pcpu_sched, i)); +struct rq *rq =cpu_rq (i); +struct sched_cache_time *pcpu_sched =per_cpu_ptr (mm->sc_stat.pcpu_sched, i); +/* Skip the rq that has not been hit for a long time */ +if (sched_cache_timeout_enabled () && +cpumask_test_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus) && + (rq->cpu_epoch - pcpu_sched->epoch) > + llc_epoch_visited_timeout) { +cpumask_clear_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus); +continue ; + } + occ =fraction_mm_sched (rq, pcpu_sched); a_occ += occ;if (occ > m_occ) { m_occ = occ;
kernel/sched/sched.h +6 -0
@@ -4037,10 +4037,12 @@ static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct#ifdef CONFIG_SCHED_CACHE DECLARE_STATIC_KEY_FALSE (sched_cache_present);DECLARE_STATIC_KEY_FALSE (sched_cache_active); +DECLARE_STATIC_KEY_TRUE (sched_cache_timeout);extern int sysctl_sched_cache_user;extern unsigned int llc_aggr_tolerance;extern unsigned int llc_epoch_period;extern unsigned int llc_epoch_affinity_timeout; +extern unsigned int llc_epoch_visited_timeout;extern unsigned int llc_imb_pct;extern unsigned int llc_overaggr_pct;
@@ -4051,6 +4053,10 @@ static inline bool sched_cache_enabled(void)extern void sched_cache_active_set_unlocked (void ); +static inline bool sched_cache_timeout_enabled (void ) +{ +return static_branch_unlikely (&sched_cache_timeout); +}#endif void sched_domains_free_llc_id (int cpu);
Signature · 1 line
2.34.1
Re: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
In reply to Tim ChenHi Tim,
Quoted 342 lines · Tim Chen
From: "Peter Zijlstra (Intel)" <[email protected]>
Adds infrastructure to enable cache-aware load balancing, which improves cache locality by grouping tasks that share resources within the same cache domain. This reduces cache misses and improves overall data access efficiency.
In this initial implementation, threads belonging to the same process are treated as entities that likely share working sets. The mechanism tracks per-process CPU occupancy across cache domains and attempts to migrate threads toward cache-hot domains where their process already has active threads, thereby enhancing locality.
This provides a basic model for cache affinity. While the current code targets the last-level cache (LLC), the approach could be extended to other domain types such as clusters (L2) or node-internal groupings.
At present, the mechanism selects the CPU within an LLC that has the highest recent runtime. Subsequent patches in this series will use this information in the load-balancing path to guide task placement toward preferred LLCs.
In the future, more advanced policies could be integrated through NUMA balancing-for example, migrating a task to its preferred LLC when spare capacity exists, or swapping tasks across LLCs to improve cache affinity. Grouping of tasks could also be generalized from that of a process to be that of a NUMA group, or be user configurable.
Signed-off-by Peter Zijlstra (Intel) <[email protected]>Signed-off-by Chen Yu <[email protected]>Signed-off-by Tim Chen <[email protected]>---
Notes:
v3->v4: No change.include/linux/mm_types.h | 32 +++++ include/linux/sched.h | 24 ++++ init/Kconfig | 11 ++ kernel/fork.c | 6 + kernel/sched/core.c | 6 + kernel/sched/fair.c | 266 +++++++++++++++++++++++++++++++++++++++ kernel/sched/sched.h | 14 +++ 7 files changed, 359 insertions(+)include/linux/mm_types.h +32
-0@@ -1173,6 +1173,8 @@ struct mm_struct {/* MM CID related storage */ struct mm_mm_cid mm_cid; +/* sched_cache related statistics */ +struct sched_cache_stat sc_stat;#ifdef CONFIG_MMU atomic_long_t pgtables_bytes;/* size of all page tables */ #endif @@ -1575,6 +1577,36 @@ static inline unsigned int mm_cid_size(void)# define MM_CID_STATIC_SIZE 0#endif /* CONFIG_SCHED_MM_CID */ +#ifdef CONFIG_SCHED_CACHE +void mm_init_sched (struct mm_struct *mm, +struct sched_cache_time __percpu *pcpu_sched); + +static inline int mm_alloc_sched_noprof (struct mm_struct *mm) +{ +struct sched_cache_time __percpu *pcpu_sched = + alloc_percpu_noprof(struct sched_cache_time); + +if (!pcpu_sched) +return -ENOMEM ; + +mm_init_sched (mm, pcpu_sched); +return 0 ; +} + +#define mm_alloc_sched (...) alloc_hooks(mm_alloc_sched_noprof(__VA_ARGS__)) + +static inline void mm_destroy_sched (struct mm_struct *mm) +{ +free_percpu (mm->sc_stat.pcpu_sched); + mm->sc_stat.pcpu_sched =NULL ; +} +#else /* !CONFIG_SCHED_CACHE */ + +static inline int mm_alloc_sched (struct mm_struct *mm) {return 0 ; } +static inline void mm_destroy_sched (struct mm_struct *mm) { } + +#endif /* CONFIG_SCHED_CACHE */ +struct mmu_gather ;extern void tlb_gather_mmu (struct mmu_gather *tlb,struct mm_struct *mm);extern void tlb_gather_mmu_fullmm (struct mmu_gather *tlb,struct mm_struct *mm);include/linux/sched.h +24
-0@@ -1406,6 +1406,10 @@ struct task_struct {unsigned long numa_pages_migrated;#endif /* CONFIG_NUMA_BALANCING */ +#ifdef CONFIG_SCHED_CACHE +struct callback_head cache_work; +#endif +struct rseq_data rseq;struct sched_mm_cid mm_cid;@@ -2376,6 +2380,26 @@ static __always_inline int task_mm_cid(struct task_struct *t) }#endif +#ifdef CONFIG_SCHED_CACHE + +struct sched_cache_time { +u64 runtime; +unsigned long epoch; +}; + +struct sched_cache_stat { +struct sched_cache_time __percpu *pcpu_sched; +raw_spinlock_t lock; +unsigned long epoch; +int cpu; +}____cacheline_aligned_in_smp ; + +#else + +struct sched_cache_stat { }; + +#endif +#ifndef MODULE #ifndef COMPILE_OFFSETS init/Kconfig +11
-0@@ -1005,6 +1005,17 @@ config NUMA_BALANCING This system will be inactive on UMA systems. +config SCHED_CACHE + bool "Cache aware load balance" + default y + depends on SMP + help + When enabled, the scheduler will attempt to aggregate tasks from + the same process onto a single Last Level Cache (LLC) domain when + possible. This improves cache locality by keeping tasks that share + resources within the same cache domain, reducing cache misses and + lowering data access latency. + config NUMA_BALANCING_DEFAULT_ENABLED bool "Automatically enable NUMA aware memory/task placement" default ykernel/fork.c +6
-0@@ -724,6 +724,7 @@ void __mmdrop(struct mm_struct *mm)cleanup_lazy_tlbs (mm);WARN_ON_ONCE (mm == current->active_mm); +mm_destroy_sched (mm);mm_free_pgd (mm);mm_free_id (mm);destroy_context (mm);@@ -1124,6 +1125,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,if (mm_alloc_cid (mm, p)) goto fail_cid; +if (mm_alloc_sched (mm)) + goto fail_sched; +if (percpu_counter_init_many (mm->rss_stat,0 ,GFP_KERNEL_ACCOUNT ,NR_MM_COUNTERS )) goto fail_pcpu;@@ -1133,6 +1137,8 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,return mm; fail_pcpu: +mm_destroy_sched (mm); +fail_sched:mm_destroy_cid (mm); fail_cid:destroy_context (mm);kernel/sched/core.c +6
-0@@ -4437,6 +4437,7 @@ static void __sched_fork(u64 clone_flags, struct task_struct *p)init_numa_balancing (clone_flags, p); p->wake_entry.u_flags =CSD_TYPE_TTWU ; p->migration_pending =NULL ; +init_sched_mm (p); }DEFINE_STATIC_KEY_FALSE (sched_numa_balancing);@@ -8749,6 +8750,11 @@ void __init sched_init(void) rq->core_cookie =0UL ;#endif +#ifdef CONFIG_SCHED_CACHE +raw_spin_lock_init (&rq->cpu_epoch_lock); + rq->cpu_epoch_next = jiffies; +#endif +zalloc_cpumask_var_node (&rq->scratch_mask,GFP_KERNEL ,cpu_to_node (i)); }kernel/sched/fair.c +105
-0@@ -1228,6 +1228,8 @@ void post_init_entity_util_avg(struct task_struct *p) sa->runnable_avg = sa->util_avg; } +static inline void account_mm_sched (struct rq *rq,struct task_struct *p,s64 delta_exec); +static s64 update_se (struct rq *rq,struct sched_entity *se) {u64 now =rq_clock_task (rq);@@ -1250,6 +1252,7 @@ static s64 update_se(struct rq *rq, struct sched_entity *se)trace_sched_stat_runtime (running, delta_exec);account_group_exec_runtime (running, delta_exec); +account_mm_sched (rq, running, delta_exec);/* cgroup time is always accounted against the donor */ cgroup_account_cputime (donor, delta_exec);@@ -1271,6 +1274,267 @@ static s64 update_se(struct rq *rq, struct sched_entity *se)static void set_next_buddy (struct sched_entity *se); +#ifdef CONFIG_SCHED_CACHE + +/* +* XXX numbers come from a place the sun don't shine -- probably wants to be SD +* tunable or so. +*/ +#define EPOCH_PERIOD (HZ / 100)/* 10 ms */ +#define EPOCH_LLC_AFFINITY_TIMEOUT 5/* 50 ms */ + +static int llc_id (int cpu) +{ +if (cpu <0 ) +return -1 ; + +return per_cpu (sd_llc_id, cpu); +} + +void mm_init_sched (struct mm_struct *mm, +struct sched_cache_time __percpu *_pcpu_sched) +{ +unsigned long epoch =0 ; +int i; + +for_each_possible_cpu (i) { +struct sched_cache_time *pcpu_sched =per_cpu_ptr (_pcpu_sched, i); +struct rq *rq =cpu_rq (i); + + pcpu_sched->runtime =0 ; +/* a slightly stale cpu epoch is acceptible */ + pcpu_sched->epoch = rq->cpu_epoch; + epoch = rq->cpu_epoch; + } + +raw_spin_lock_init (&mm->sc_stat.lock); + mm->sc_stat.epoch = epoch; + mm->sc_stat.cpu =-1 ; + +/* +* The update to mm->sc_stat should not be reordered +* before initialization to mm's other fields, in case +* the readers may get invalid mm_sched_epoch, etc. +*/ +smp_store_release (&mm->sc_stat.pcpu_sched, _pcpu_sched); +} + +/* because why would C be fully specified */ +static __always_inline void __shr_u64(u64 *val, unsigned int n) +{ +if (n >=64 ) { + *val =0 ; +return ; + } + *val >>= n; +} + +static inline void __update_mm_sched (struct rq *rq, +struct sched_cache_time *pcpu_sched) +{ +lockdep_assert_held (&rq->cpu_epoch_lock); + +unsigned long n, now = jiffies; +long delta = now - rq->cpu_epoch_next; + +if (delta >0 ) { + n = (delta +EPOCH_PERIOD -1 ) /EPOCH_PERIOD ; + rq->cpu_epoch += n; + rq->cpu_epoch_next += n *EPOCH_PERIOD ; +__shr_u64 (&rq->cpu_runtime, n); + } + + n = rq->cpu_epoch - pcpu_sched->epoch; +if (n) { + pcpu_sched->epoch += n; +__shr_u64 (&pcpu_sched->runtime, n); + } +} + +static unsigned long fraction_mm_sched (struct rq *rq, +struct sched_cache_time *pcpu_sched) +{ +guard (raw_spinlock_irqsave)(&rq->cpu_epoch_lock); + +__update_mm_sched (rq, pcpu_sched); + +/* +* Runtime is a geometric series (r=0.5) and as such will sum to twice +* the accumulation period, this means the multiplcation here should +* not overflow. +*/ +return div64_u64 (NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime +1 ); +} + +static inline +void account_mm_sched (struct rq *rq,struct task_struct *p,s64 delta_exec) +{ +struct sched_cache_time *pcpu_sched; +struct mm_struct *mm = p->mm; +unsigned long epoch; + +if (!sched_cache_enabled ()) +return ; +
kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1388
Quoted 10 lines
kernel/sched/fair.c +10
-0+if (p->sched_class != &fair_sched_class) +return ; +/* +* init_task, kthreads and user thread created +* by user_mode_thread() don't have mm. +*/ +if (!mm || !mm->sc_stat.pcpu_sched) +return ; + + pcpu_sched =per_cpu_ptr (p->mm->sc_stat.pcpu_sched,cpu_of (rq));
I do some test, when i see many pids schedstat, such as cat proc/xxx/schedstat, there will cause a panic,maybe the 'p' is exit or others reason, sorry, i dont record these msg. how about fix it like below.
pcpu_sched = per_cpu_ptr(mm->sc_stat.pcpu_sched, cpu_of(rq));
and "[Patch v4 21/22] -- DO NOT APPLY!!! -- sched/cache/debug: Display the per LLC occupancy for each process via proc fs" has the same problem.
Quoted 193 lines
kernel/sched/fair.c +151
-0+ + scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) { +__update_mm_sched (rq, pcpu_sched); + pcpu_sched->runtime += delta_exec; + rq->cpu_runtime += delta_exec; + epoch = rq->cpu_epoch; + } + +/* +* If this process hasn't hit task_cache_work() for a while, or it +* has only 1 thread, invalidate its preferred state. +*/ +if (time_after (epoch, +READ_ONCE (mm->sc_stat.epoch) +EPOCH_LLC_AFFINITY_TIMEOUT ) || +get_nr_threads (p) <=1 ) { +if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; + } +} + +static void task_tick_cache (struct rq *rq,struct task_struct *p) +{ +struct callback_head *work = &p->cache_work; +struct mm_struct *mm = p->mm; +unsigned long epoch; + +if (!sched_cache_enabled ()) +return ; + +if (!mm || !mm->sc_stat.pcpu_sched) +return ; + + epoch = rq->cpu_epoch; +/* avoid moving backwards */ +if (time_after_eq (mm->sc_stat.epoch, epoch)) +return ; + +guard (raw_spinlock)(&mm->sc_stat.lock); + +if (work->next == work) { +task_work_add (p, work,TWA_RESUME ); +WRITE_ONCE (mm->sc_stat.epoch, epoch); + } +} + +static void task_cache_work (struct callback_head *work) +{ +struct task_struct *p = current; +struct mm_struct *mm = p->mm; +unsigned long m_a_occ =0 ; +unsigned long curr_m_a_occ =0 ; +int cpu, m_a_cpu =-1 ; +cpumask_var_t cpus; + +WARN_ON_ONCE (work != &p->cache_work); + + work->next = work; + +if (p->flags &PF_EXITING ) +return ; + +if (!zalloc_cpumask_var (&cpus,GFP_KERNEL )) +return ; + +scoped_guard (cpus_read_lock) { +cpumask_copy (cpus, cpu_online_mask); + +for_each_cpu (cpu, cpus) { +/* XXX sched_cluster_active */ +struct sched_domain *sd =per_cpu (sd_llc, cpu); +unsigned long occ, m_occ =0 , a_occ =0 ; +int m_cpu =-1 , i; + +if (!sd) +continue ; + +for_each_cpu (i,sched_domain_span (sd)) { + occ =fraction_mm_sched (cpu_rq (i), +per_cpu_ptr (mm->sc_stat.pcpu_sched, i)); + a_occ += occ; +if (occ > m_occ) { + m_occ = occ; + m_cpu = i; + } + } + +/* +* Compare the accumulated occupancy of each LLC. The +* reason for using accumulated occupancy rather than average +* per CPU occupancy is that it works better in asymmetric LLC +* scenarios. +* For example, if there are 2 threads in a 4CPU LLC and 3 +* threads in an 8CPU LLC, it might be better to choose the one +* with 3 threads. However, this would not be the case if the +* occupancy is divided by the number of CPUs in an LLC (i.e., +* if average per CPU occupancy is used). +* Besides, NUMA balancing fault statistics behave similarly: +* the total number of faults per node is compared rather than +* the average number of faults per CPU. This strategy is also +* followed here. +*/ +if (a_occ > m_a_occ) { + m_a_occ = a_occ; + m_a_cpu = m_cpu; + } + +if (llc_id (cpu) ==llc_id (mm->sc_stat.cpu)) + curr_m_a_occ = a_occ; + +cpumask_andnot (cpus, cpus,sched_domain_span (sd)); + } + } + +if (m_a_occ > (2 * curr_m_a_occ)) { +/* +* Avoid switching sc_stat.cpu too fast. +* The reason to choose 2X is because: +* 1. It is better to keep the preferred LLC stable, +* rather than changing it frequently and cause migrations +* 2. 2X means the new preferred LLC has at least 1 more +* busy CPU than the old one(200% vs 100%, eg) +* 3. 2X is chosen based on test results, as it delivers +* the optimal performance gain so far. +*/ + mm->sc_stat.cpu = m_a_cpu; + } + +free_cpumask_var (cpus); +} + +void init_sched_mm (struct task_struct *p) +{ +struct callback_head *work = &p->cache_work; + +init_task_work (work, task_cache_work); + work->next = work; +} + +#else /* CONFIG_SCHED_CACHE */ + +static inline void account_mm_sched (struct rq *rq,struct task_struct *p, +s64 delta_exec) { } + +void init_sched_mm (struct task_struct *p) { } + +static void task_tick_cache (struct rq *rq,struct task_struct *p) { } + +#endif /* CONFIG_SCHED_CACHE */ +/* * Used by other classes to account runtime. */ @@ -13448,6 +13712,8 @@ static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)if (static_branch_unlikely (&sched_numa_balancing))task_tick_numa (rq, curr); +task_tick_cache (rq, curr); +update_misfit_status (curr, rq);check_update_overutilized_status (task_rq (curr));kernel/sched/sched.h +14
-0@@ -1177,6 +1177,12 @@ struct rq {struct scx_rq scx;struct sched_dl_entity ext_server;#endif +#ifdef CONFIG_SCHED_CACHE +raw_spinlock_t cpu_epoch_lock____cacheline_aligned ; +u64 cpu_runtime; +unsigned long cpu_epoch; +unsigned long cpu_epoch_next; +#endif struct sched_dl_entity fair_server;@@ -4007,6 +4013,14 @@ static inline void mm_cid_switch_to(struct task_struct *prev, struct task_structstatic inline void mm_cid_switch_to (struct task_struct *prev,struct task_struct *next) { }#endif /* !CONFIG_SCHED_MM_CID */ +#ifdef CONFIG_SCHED_CACHE +static inline bool sched_cache_enabled (void ) +{ +return false; +} +#endif +extern void init_sched_mm (struct task_struct *p); +extern u64 avg_vruntime (struct cfs_rq *cfs_rq);extern int entity_eligible (struct cfs_rq *cfs_rq,struct sched_entity *se); static inline
Re: [PATCH v2] sched/cache: Reduce the overhead of task_cache_work by only scan the visisted cpus.
In reply to Luo GengkunHi Gengkun,
Quoted 9 lines · Luo Gengkun
The overhead of
task_cache_workis high, espeically in multi-NUMA system. Currently,task_cache_worktry to find thepref_llcby scan all cpus in the system. However, most of these scans are meaningless, such as those for cpus that have never been visited or were accessed a long time ago.To address this problem, this patch introduces
visited_cpusto track the visited cpus and usesllc_epoch_visited_timeoutto evict cpus that have timed out.
Quoted 7 lines
Signed-off-by Luo Gengkun <[email protected]>---
Thanks for the reviews. I've updated the patch based on your feedback.v2 Changes:
1. Added a pre-check before set/clearvisited_cpusto avoid C2C overhead.
2. Optimizedllc_epoch_visited_timeoutby using a static key to minimize overhead.
Since the visited CPUs optimization should help reduce the scan cost, I wonder if we should enable it by default, regardless of the timeout value set by the user. This mainly helps avoid introducing extra debugfs controls/static key.
kernel/sched/debug.c static __init int sched_init_debug(void) · line 721
Quoted 7 lines
#ifdef CONFIG_PREEMPT_DYNAMICkernel/sched/debug.c +2
-0@@ -669,6 +717,8 @@ static __init int sched_init_debug(void) llc =debugfs_create_dir ("llc_balancing" , debugfs_sched);debugfs_create_file ("enabled" ,0644 , llc,NULL , &sched_cache_enable_fops); +debugfs_create_file ("epoch_visited_timeout" ,0644 , llc,NULL , + &sched_cache_timeout_enable_fops);
Is it possible to reuse llc_epoch_affinity_timeout without introducing epoch_visited_timeout? The idea is that if a task has not run on that CPU for 10 ms (by default), its footprint will be cleared.
[ ... ]
kernel/sched/fair.c static void task_cache_work(struct callback_head *work) · line 1753
Quoted 11 lines
kernel/sched/fair.c +5
-2@@ -1736,8 +1746,17 @@ static void task_cache_work(struct callback_head *work)continue ;for_each_cpu (i,sched_domain_span (sd)) { - occ =fraction_mm_sched (cpu_rq (i), -per_cpu_ptr (mm->sc_stat.pcpu_sched, i)); +struct rq *rq =cpu_rq (i); +struct sched_cache_time *pcpu_sched =per_cpu_ptr (mm->sc_stat.pcpu_sched, i); +/* Skip the rq that has not been hit for a long time */ + if (sched_cache_timeout_enabled() && + cpumask_test_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus) &&
cpumask_test_cpu(i) should be fine. The rq access above doesn't hold cpu_epoch_lock. I wonder if we can safely calculate rq->cpu_epoch - pcpu_sched->epoch inside fraction_mm_sched while holding the lock?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I'll test your patch after fixing the bug reported by sashiko.dev.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
thanks,
Chenyu
Re: [RFC PATCH] sched/fair: dynamically scale the period of cache work
In reply to Jianyong WuHi Jianyong,
Quoted 2 lines · Jianyong Wu
Hi Chenyu,
[ ... ]
Quoted 10 lines
Quoted 5 lines
Review
Quoted 1 line
(quoted diff) +1
-0+ WRITE_ONCE(mm->sc_stat.next_scan, (now +
mm->sc_stat.scan_period));Quoted 1 line
+
I suppose the above should be
try_cmpxchg()?Even though the update is not observed by others, it may not be a big problem. However, using
try_cmpxchgmay incur more overhead thanWRITE_ONCE.
So, I wonder if we can tolerate such a loss of "correctness" for the sake of performance.
try_cmpxchg is triggered not very frequently(10 ms) so the overhead might not be that high? try_cmpxchg "strictly" avoid two threads entering the same loop, and it seems that in the end of task_cache_work() there is a update_avg_scale() which involves
u64 *avg += xxx
which is not atomic so maybe try_cmpxchg could help with that?
Quoted 8 lines
Quoted 7 lines
That is to say, with your above change, we have already limited the scan ratio for multi-threaded processes significantly. There appears to be no need to perform adaptive adjustment of
scan_period- the benefit of introducing an adaptivescan_periodmay not offset the overhead of frequent writing to the "global"mm->sc_stat.scan_perioddue to c2c?
Quoted 5 lines
If we can increase the scan period, the operations inside the scan work will
not be executed frequently. Thus, there is little overhead from writing to the global variable. This only occurs when the preferred node is unstable and the scan work runs frequently. If the preferred node remains stable most of the time, we can still benefit from it.
I see. BTW, why mm->sc_stat.need_scan is needed? With sc_stat.next_scan and sc_stat.scan_period, we should be able to adjust the timeout.
Is it because you want other condition to shrink the scan_period? Like below:
+ if (to_pref && ret == mig_forbid)
+ mm->sc_stat.need_scan = 1;
thanks,
Chenyu
Re: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
In reply to Vern HaoQuoted 2 lines · Vern Hao
Hi Tim,
[ ... ]
Quoted 25 lines
Quoted 12 lines
kernel/sched/fair.c +3
-0+ +static inline +void account_mm_sched(struct rq *rq, struct task_struct *p, s64
delta_exec)kernel/sched/fair.c +8
-0+{ + struct sched_cache_time *pcpu_sched; + struct mm_struct *mm = p->mm; + unsigned long epoch; + + if (!sched_cache_enabled()) + return; +kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1388
Quoted 10 lines
kernel/sched/fair.c +10
-0+ if (p->sched_class != &fair_sched_class) + return; + /* + * init_task, kthreads and user thread created + * by user_mode_thread() don't have mm. + */ + if (!mm || !mm->sc_stat.pcpu_sched) + return; + + pcpu_sched = per_cpu_ptr(p->mm->sc_stat.pcpu_sched, cpu_of(rq));I do some test, when i see many pids schedstat, such as cat proc/xxx/ schedstat, there will cause a panic,maybe the 'p' is exit or others reason, sorry, i dont record these msg. how about fix it like below.
Quoted 2 lines
pcpu_sched=per_cpu_ptr(mm->sc_stat.pcpu_sched, cpu_of(rq));
Right, we have also received a report at
https://sashiko.dev/#/patchset/cover.1775065312.git.tim.c.chen%40linux.int.com
indicating that this issue needs to be fixed. We are working on it. Thanks for the investigation.
thanks,
Chenyu
Re: [RFC PATCH] sched/fair: dynamically scale the period of cache work
In reply to Jianyong WuQuoted 5 lines · Jianyong Wu
When a preferred LLC is selected and remains stable,
task_cache_workdoes not need to run frequently. Because it scans all system CPUs for computation, high-frequency execution hurts performance. We thus reduce the scan rate in such cases.
Thanks for your patch proposal.
Quoted 1 line
On the other hand, if the preferred node becomes suboptimal, we should
You mean preferred LLC right? preferred node is from NUMA balancing.
Quoted 15 lines
increase the scan frequency to quickly find a better placement. The scan period is therefore dynamically adjusted.
Signed-off-by Jianyong Wu <[email protected]>---
Hi ChenYu, Tim, Gengkun,I have another approach to address this issue, based on the observation that the scan work can be canceled if the preferred node is stable.This patch merely demonstrates the idea, but still needs more testing to verify its functionality. I'm sending it out early to gather feedback and opinions.
<...>
Quoted 18 lines
kernel/sched/fair.c +13
-1@@ -1822,9 +1835,35 @@ static void task_cache_work(struct callback_head *work)* 3. 2X is chosen based on test results, as it delivers * the optimal performance gain so far. */ - mm->sc_stat.cpu = m_a_cpu; +if (m_a_occ > (2 * curr_m_a_occ)) + mm->sc_stat.cpu = m_a_cpu; + +if (!mm->sc_stat.last_reset_tick) + mm->sc_stat.last_reset_tick = now; + +/* Change scan_period when preferred LLC changed */ +if (((mm->sc_stat.cpu !=-1 ) && (m_a_cpu !=-1 ) + && (llc_id (mm->sc_stat.cpu) !=llc_id (m_a_cpu))) + || need_scan) { +if (!need_scan) + need_scan =1 ; +
kernel/sched/fair.c static void task_cache_work(struct callback_head *work) · line 1860
Quoted 10 lines
kernel/sched/fair.c +10
-0+WRITE_ONCE (mm->sc_stat.scan_period, +max (mm->sc_stat.scan_period >>1 , llc_scan_period_min)); +WRITE_ONCE (mm->sc_stat.last_reset_tick, now); + } + } + +if ((now -READ_ONCE (mm->sc_stat.last_reset_tick) > llc_scan_period_threshold) + && !need_scan) { +WRITE_ONCE (mm->sc_stat.scan_period,min (mm->sc_stat.scan_period <<1 , + llc_scan_period_max));
I think that llc_scan_period_max should be the same as llc_epoch_affinity_timeout. We should not increase the scan period beyond that as that's the time scale where we consider cache data relevant.
Tim
Quoted 8 lines · Duan Tingyin
Thanks for your patch series.
I've tested the changes on my hygon servers (model 4h, 6h, 7h, 8h)
with kernel version 7.0.0-rc7 and no performance regression is observed.P.S. the patch from https://lore.kernel.org/lkml/[email protected]/ is include in these tests.Tested-by Tingyin Duan <[email protected]>
Thank you!
Tim
Quoted 21 lines · Tim Chen
This patch series introduces infrastructure for cache-aware load balancing, with the goal of co-locating tasks that share data within the same Last Level Cache (LLC) domain. By improving cache locality, the scheduler can reduce cache bouncing and cache misses, ultimately improving data access efficiency. The design builds on the initial prototype from Peter [1].
This initial implementation treats threads within the same process as entities that are likely to share data. During load balancing, the scheduler attempts to aggregate such threads onto the same LLC domain whenever possible.
Most of the feedback received on v3 has been addressed. Some aspects could be enhanced later after the basic cache-aware portion has landed:
There were discussions around grouping tasks using mechanisms other than process membership. While we agree that more flexible grouping is desirable, this series intentionally focuses on establishing basic process-based grouping first, with alternative grouping mechanisms to be explored in a follow-on series.
Quoted 8 lines
There was also discussion in v3 that the task wakeup path should be used to perform cache-aware scheduling. According to previous test results, performing task aggregation in the wakeup path introduced task migration bouncing. Primarily that was due to the wake up path not having the up to date LLC load information. That led to over-aggregation that needed to be corrected later in load balancing. Load balancing path was chosen as the conservative path to perform task aggregation. The task wakeup path will be investigated as a future enhancement.
I posted schedqos announcement yesterday, which I think (hope) would be the right way to address these concerns about tagging tasks.
https://lore.kernel.org/lkml/20260415000910.2h5misvwc45bdumu@airbuntu/
It would be trivial to add experimental branch to add new QoS flavour to say NUMA_SENSITIVE etc. I am still trying to think of a generic description to address a number of use cases (see Execution Profiles in README.md), not just this particular numa sensitive one, but the experimental branch should help iterate and drive the kernel development for wake up path + push lb instead of using load balance which I really doubt will work well in practice since this is slow to react, and you're relying on overcommitting the system by default by making every task of every process data dependent and require it to be co-located. I think in practice admins will care about specific applications to be kept within a single LLC, and if they are willing to spend the effort, they can tag specific tasks of a specific application.
We are trying to make sure we have one coherent story to define these type of QoS requirements, and delegate to userspace to make these decisions/policies. The current line of thinking is that wakeup + push lb should be generally good to address the different needs for various placement requirements. I understood you believe the same. If not, it would be good so we can think how to further generalize.
Also QoS IMHO should be viewed as a scarce resource. For best effort delivery (which is the best we can do in reality, this is not hard real time system), it is easier to provide good best effort when the average noise level is low, ie:
few tasks are required to be kept within the same LLC. If we overcommit often, we will crumble often. So IMHO the key is to delegate to userspace to tag, and make them take responsibility of handling potential overcommit and decide which workload is really important to tag and which one they can let go of or move to another machine to get their desired perf/latencies.
For the kernel interface to tag tasks and set a cookie, I plan to rebase and repost [1] as I need it for rampup multiplier to help counter DVFS related latencies and slow migration in HMP systems. The idea was for it to be generic and flexible to add whatever; in this case I think we need to add a QoS to tell scheduler these tasks are data co-dependent with a unique cookie, which implies that they need to stay within the same LLC, and can be extended to help keep these tasks within the same L2 or L1 if it makes sense (ie: they are small and can be packed on the same CPU).
I am not opposed to merging this first, but I think the load balanced based approach is wrong and if merged must be removed later in favour of wakeup
+ push lb one with user space based tagging.
Based on what Peter said the wake up path is trivial to add, push lb is almost ready, and I hope we have the tools to auto tag processes/tasks now to potentially try to work on this approach first instead.
RE: [RFC PATCH] sched/fair: dynamically scale the period of cache work
In reply to Chen, Yu CHi Chenyu,
Quoted 8 lines
try_cmpxchgis triggered not very frequently(10 ms) so the overhead might not be that high?try_cmpxchg"strictly" avoid two threads entering the same loop, and it seems that in the end oftask_cache_work()there is aupdate_avg_scale()
which involves
u64 *avg += xxx
which is not atomic so maybetry_cmpxchgcould help with that?
Ok, looks like try_cmpxchg has little performance overhead. I'll use it in the next version.
Quoted 23 lines
Quoted 6 lines
Quoted 6 lines
That is to say, with your above change, we have already limited the scan ratio for multi-threaded processes significantly. There appears to be no need to perform adaptive adjustment of
scan_period- the benefit of introducing an adaptivescan_periodmay not offset the overhead of frequent writing to the "global"mm->sc_stat.scan_perioddue to c2c?
Quoted 4 lines
Quoted 1 line
If we can increase the scan period, the operations inside the scan work will not be executed frequently. Thus, there is little overhead from
writing to the global variable.
Quoted 2 lines
This only occurs when the preferred node is unstable and the scan work runs frequently. If the preferred node remains stable most of the time,
we can still benefit from it.
Quoted 1 line
I see. BTW, why
mm->sc_stat.need_scanis needed? With sc_stat.next_scan and sc_stat.scan_period, we should be able to adjust the timeout.Is it because you want other condition to shrink the
scan_period? Like below:
kernel/sched/fair.c static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu, · line 10338
Quoted 2 lines
kernel/sched/fair.c +2
-0+if (to_pref && ret == mig_forbid) + mm->sc_stat.need_scan =1 ;
Yes, here I intend to shorten the scan period once the current preferred LLC may be no longer suitable for the task.
Thanks
Jianyong
Quoted 2 lines
thanks,
Chenyu
RE: [RFC PATCH] sched/fair: dynamically scale the period of cache work
In reply to Tim ChenHi Tim,
Quoted 7 lines · Jianyong Wu
Quoted 5 lines
When a preferred LLC is selected and remains stable,
task_cache_workdoes not need to run frequently. Because it scans all system CPUs for computation, high-frequency execution hurts performance. We thus reduce the scan rate in such cases.
Quoted 6 lines
Thanks for your patch proposal.
Quoted 1 line
On the other hand, if the preferred node becomes suboptimal, we
should
You mean preferred LLC right? preferred node is from NUMA balancing.
Sorry for the misunderstanding. Yes, I meant the preferred LLC here.
Quoted 33 lines
Review static void task_cache_work(struct
Quoted 3 lines
(quoted diff) +0
-0@@ -1822,9 +1835,35 @@ static void task_cache_work(struct
callback_head*work)Quoted 9 lines
kernel/sched/fair.c +5
-1* 3. 2X is chosen based on test results, as it delivers * the optimal performance gain so far. */ - mm->sc_stat.cpu = m_a_cpu; +if (m_a_occ > (2 * curr_m_a_occ)) + mm->sc_stat.cpu = m_a_cpu; + +if (!mm->sc_stat.last_reset_tick) + mm->sc_stat.last_reset_tick = now;kernel/sched/fair.c static void task_cache_work(struct callback_head *work)
Quoted 10 lines
kernel/sched/fair.c +10
-0+ +/* Change scan_period when preferred LLC changed */ +if (((mm->sc_stat.cpu !=-1 ) && (m_a_cpu !=-1 ) + && (llc_id (mm->sc_stat.cpu) !=llc_id (m_a_cpu))) + || need_scan) { +if (!need_scan) + need_scan =1 ; + + WRITE_ONCE(mm->sc_stat.scan_period, + max(mm->sc_stat.scan_period >> 1,
llc_scan_period_min));kernel/sched/fair.c static void task_cache_work(struct callback_head *work)
Quoted 5 lines
kernel/sched/fair.c +5
-0+WRITE_ONCE (mm->sc_stat.last_reset_tick, now); + } + } + + if ((now - READ_ONCE(mm->sc_stat.last_reset_tick) >
llc_scan_period_threshold)Review static void task_cache_work(struct · line 1859
Quoted 2 lines
(quoted diff) +2
-0+ && !need_scan) { + WRITE_ONCE(mm->sc_stat.scan_period,min(mm->sc_stat.scan_period << 1,
Quoted 6 lines
kernel/sched/fair.c static void task_cache_work(struct callback_head *work) · line 1860
Quoted 1 line
kernel/sched/fair.c +1
-0+ llc_scan_period_max));I think that
llc_scan_period_maxshould be the same asllc_epoch_affinity_timeout.
We should not increase the scan period beyond that as that's the time scale where we consider cache data relevant.
Sounds reasonable. I'll run some tests to verify if this is sufficient.
Thanks
Jianyong
Quoted 4 lines
Tim
Re: [PATCH v2] sched/cache: Reduce the overhead of task_cache_work by only scan the visisted cpus.
In reply to Chen, Yu CQuoted 16 lines · Yu C
Hi Gengkun,
Quoted 13 lines · Luo Gengkun
The overhead of
task_cache_workis high, espeically in multi-NUMA system. Currently,task_cache_worktry to find thepref_llcby scan all cpus in the system. However, most of these scans are meaningless, such as those for cpus that have never been visited or were accessed a long time ago.To address this problem, this patch introduces
visited_cpusto track the visited cpus and usesllc_epoch_visited_timeoutto evict cpus that have timed out.Signed-off-by Luo Gengkun <[email protected]>---
Thanks for the reviews. I've updated the patch based on your feedback.
Quoted 8 lines
Quoted 3 lines
v2 Changes:
1. Added a pre-check before set/clearvisited_cpusto avoid C2C overhead.
2. Optimizedllc_epoch_visited_timeoutby using a static key to minimize overhead.Since the visited CPUs optimization should help reduce the scan cost, I wonder if we should enable it by default, regardless of the timeout value set by the user. This mainly helps avoid introducing extra debugfs controls/static key.
I would be happy to do this.
Quoted 12 lines
kernel/sched/debug.c static __init int sched_init_debug(void) · line 721
Quoted 8 lines
#ifdef
CONFIG_PREEMPT_DYNAMICkernel/sched/debug.c +2
-0@@ -669,6 +717,8 @@ static __init int sched_init_debug(void) llc = debugfs_create_dir("llc_balancing", debugfs_sched); debugfs_create_file("enabled", 0644, llc, NULL, &sched_cache_enable_fops); + debugfs_create_file("epoch_visited_timeout", 0644, llc, NULL, + &sched_cache_timeout_enable_fops);Is it possible to reuse
llc_epoch_affinity_timeoutwithout introducingepoch_visited_timeout? The idea is that if a task has not run on that CPU for 10 ms (by default), its footprint will be cleared.
I think this is also acceptable, because visited_timeout is inspired by affinity_timeout.
Quoted 17 lines
[ ... ]
kernel/sched/fair.c static void task_cache_work(struct callback_head *work) · line 1752
Quoted 10 lines
kernel/sched/fair.c +5
-2@@ -1736,8 +1746,17 @@ static void task_cache_work(struct callback_head *work) continue; for_each_cpu(i, sched_domain_span(sd)) { - occ = fraction_mm_sched(cpu_rq(i), - per_cpu_ptr(mm->sc_stat.pcpu_sched, i)); + struct rq *rq = cpu_rq(i); + struct sched_cache_time *pcpu_sched = per_cpu_ptr(mm->sc_stat.pcpu_sched, i); + /* Skip the rq that has not been hit for a long time */ + if (sched_cache_timeout_enabled() && + cpumask_test_cpu(cpu_of(rq), &mm->sc_stat.visited_cpus) &&
cpumask_test_cpu(i)should be fine. The rq access above doesn't holdcpu_epoch_lock. I wonder if we can safely calculaterq->cpu_epoch-pcpu_sched->epochinsidefraction_mm_schedwhile holding the lock?
Do we really need to access rq->cpu_epoch under the lock for read scenarios? I noticed task_tick_cache accesses it directly. Plus, moving this access outside the lock would help reduce lock contention.
thanks,
Luo Gengkun
Quoted 12 lines
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I'll test your patch after fixing the bug reported by sashiko.dev.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++thanks,
Chenyu
Re: [PATCH v2] sched/cache: Reduce the overhead of task_cache_work by only scan the visisted cpus.
Quoted 5 lines · Luo Gengkun
Quoted 2 lines · Yu C
Hi Gengkun,
[ ... ]
Quoted 12 lines
Quoted 12 lines
Quoted 12 lines
kernel/sched/fair.c +5
-2@@ -1736,8 +1746,17 @@ static void task_cache_work(struct callback_head *work) continue; for_each_cpu(i, sched_domain_span(sd)) { - occ = fraction_mm_sched(cpu_rq(i), - per_cpu_ptr(mm->sc_stat.pcpu_sched, i)); + struct rq *rq = cpu_rq(i); + struct sched_cache_time *pcpu_sched =per_cpu_ptr (mm->sc_stat.pcpu_sched, i); + /* Skip the rq that has not been hit for a long time */ + if (sched_cache_timeout_enabled() && + cpumask_test_cpu(cpu_of(rq), &mm-
Quoted 9 lines
Quoted 5 lines
Quoted 1 line
Quoted 1 line
sc_stat.visited_cpus) &&
cpumask_test_cpu(i)should be fine. The rq access above doesn't holdcpu_epoch_lock. I wonder if we can safely calculaterq->cpu_epoch-pcpu_sched->epochinsidefraction_mm_schedwhile holding the lock?Do we really need to access
rq->cpu_epochunder the lock for read scenarios? I noticedtask_tick_cacheaccesses it directly. Plus, moving this access outside the lock would help reduce lock contention.
Good question. task_tick_cache() access local rq->cpu_epoch with rq->lock held and irq disabled, while task_cache_work() is running with irq enabled without any rq->lock hold, and might not be run on local rq - see __exit_to_user_mode_loop(), it checks _TIF_NEED_RESCHED before _TIF_NOTIFY_RESUME, so p could be switched out and woken up and run task_cache_work() on a different CPU.
That is to say, I just wonder if there could be a race window
that bring inconsistency between two reads of rq->cpu_epoch - pcpu_sched->epoch
- not necessary a critical issue though.
thanks,
Chenyu
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
Quoted 6 lines
I posted schedqos announcement yesterday, which I think (hope) would be the right way to address these concerns about tagging tasks.
https://lore.kernel.org/lkml/20260415000910.2h5misvwc45bdumu@airbuntu/
Thanks, I'll take a look at this.
Quoted 9 lines
It would be trivial to add experimental branch to add new QoS flavour to say
NUMA_SENSITIVEetc. I am still trying to think of a generic description to address a number of use cases (see Execution Profiles in README.md), not just this particular numa sensitive one, but the experimental branch should help iterate and drive the kernel development for wake up path + push lb instead of using load balance which I really doubt will work well in practice since this is slow to react, and you're relying on overcommitting the system by default by making every task of every process data dependent and require it to be co-located.
I am not certain which strategy is preferable, as it largely depends on the use case and workload. We intend to evaluate push-based load balancing on top of the existing lb-based cache-aware placement logic.
Quoted 4 lines
I think in practice admins will care about specific applications to be kept within a single LLC, and if they are willing to spend the effort, they can tag specific tasks of a specific application.
It seems to me that there are multiple use cases. In one scenario, the administrator (including daemons) is responsible for tagging workloads. In another, users prefer the OS to handle automatic placement without any userspace involvement.
Quoted 5 lines
Also QoS IMHO should be viewed as a scarce resource. For best effort delivery (which is the best we can do in reality, this is not hard real time system), it is easier to provide good best effort when the average noise level is low, ie:
few tasks are required to be kept within the same LLC. If we overcommit often, we will crumble often. So IMHO the key is to delegate to userspace to tag, and
I suppose there are two scenarios. The first is enabling/disabling aggregation for a group of tasks, and the second is task tagging. For the first scenario, this can be applied either process-wide or cgroup-wide by providing a flag, without requiring users to explicitly tag individual tasks. The second scenario
is an enhancement to support fine-grained control over a specific
task. If
schedqos only supports scenario2, the user has to tag every task to support scenario1.
thanks,
Chenyu
Quoted 24 lines · Yu C
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
Quoted 6 lines
I posted schedqos announcement yesterday, which I think (hope) would be the right way to address these concerns about tagging tasks.
https://lore.kernel.org/lkml/20260415000910.2h5misvwc45bdumu@airbuntu/Thanks, I'll take a look at this.
Quoted 9 lines
It would be trivial to add experimental branch to add new QoS flavour to say
NUMA_SENSITIVEetc. I am still trying to think of a generic description to address a number of use cases (see Execution Profiles in README.md), not just this particular numa sensitive one, but the experimental branch should help iterate and drive the kernel development for wake up path + push lb instead of using load balance which I really doubt will work well in practice since this is slow to react, and you're relying on overcommitting the system by default by making every task of every process data dependent and require it to be co-located.
Quoted 3 lines
I am not certain which strategy is preferable, as it largely depends on the use case and workload. We intend to evaluate push-based load balancing on top of the existing lb-based cache-aware placement logic.
I'll defer to Vincent here, but I would have thought lb-based approach can go away.
Quoted 10 lines
Quoted 5 lines
I think in practice admins will care about specific applications to be kept within a single LLC, and if they are willing to spend the effort, they can tag specific tasks of a specific application.
It seems to me that there are multiple use cases. In one scenario, the administrator (including daemons) is responsible for tagging workloads. In another, users prefer the OS to handle automatic placement without any userspace involvement.
How do you define this automatic placement? AFAICS you're just grouping all tasks of a specific process to stay within the same LLC and hitting overcommit issues which you're workingaround with this load balancer only based approach?
I think in practice there will be many corner cases where state is not optimal and we'd end up with heuristics to 'balance' things out and sensitivity to independent changes disturbing this fragile balance causing weird regressions and us slowly has less flexibility to move and shuffle code (okay, maybe too much doom and gloom, but we've been by this in the past :)).
I am not sure how many of these tests stressed the system with multiple critical processes running concurrently?
By making it a userspace problem they have to figure out the right balance and we can focus on providing the right mechanism.
Quoted 7 lines
Quoted 6 lines
Also QoS IMHO should be viewed as a scarce resource. For best effort delivery (which is the best we can do in reality, this is not hard real time system), it is easier to provide good best effort when the average noise level is low, ie:
few tasks are required to be kept within the same LLC. If we overcommit often, we will crumble often. So IMHO the key is to delegate to userspace to tag, and
Quoted 5 lines
I suppose there are two scenarios. The first is enabling/disabling aggregation
for a group of tasks, and the second is task tagging. For the first scenario,
this can be applied either process-wide or cgroup-wide by providing a flag,
Cgroup-wide tagging doesn't make sense IMO. Process-wide yes.
What does it mean to group all processes in the same cgroup from cache locality PoV? It just seems random setup based on something specific in userspace on how these cgroups are setup that assumes one process per group? I don't think we can generalize if that's the case.
Admins can use cpuset to statically partition based on cgroup if they want to ensure a group of processes are confined to the same LLC?
Quoted 5 lines
without requiring users to explicitly tag individual tasks. The second scenario
is an enhancement to support fine-grained control over a specific task. If
schedqos only supports scenario2, the user has to tag every task to support scenario1.
You can do tagging process-wide (as I mentioned in the announcement, I think it's a poor man's way for quick tagging until people learn to do better), not just per-task eg:
{
"PostgreSQL": {
"qos": ["QOS_USER_INTERACTIVE", "QOS_NUMA_SENSITIVE"]
}
}which will tag every task forked by this binary with a cookie and QoS data dependency tag tell the scheduler all tasks with the same cookie need to stay within the same LLC.
We can bikeshed naming and the tagging details, but the actual implementation principal should be the same: keep tasks with the same cookie and data dep tag on the same LLC at wake up; and let push lb handle occasional strayed task.
If users want to be smart and tag specific tasks only, the implementation would be identical, it's just there are fewer tasks tagged.
Quoted 7 lines · Qais Yousef
Quoted 6 lines · Yu C
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
Quoted 1 line
Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
I posted schedqos announcement yesterday, which I think (hope) would be the right way to address these concerns about tagging tasks.
https://lore.kernel.org/lkml/20260415000910.2h5misvwc45bdumu@airbuntu/
I think that's great. Will be a nice way to tag tasks that should be grouped and aggregated together.
Quoted 25 lines
Quoted 12 lines
Thanks, I'll take a look at this.
Quoted 9 lines
It would be trivial to add experimental branch to add new QoS flavour to say
NUMA_SENSITIVEetc. I am still trying to think of a generic description to address a number of use cases (see Execution Profiles in README.md), not just this particular numa sensitive one, but the experimental branch should help iterate and drive the kernel development for wake up path + push lb instead of using load balance which I really doubt will work well in practice since this is slow to react, and you're relying on overcommitting the system by default by making every task of every process data dependent and require it to be co-located.Quoted 3 lines
I am not certain which strategy is preferable, as it largely depends on the use case and workload. We intend to evaluate push-based load balancing on top of the existing lb-based cache-aware placement logic.
I'll defer to Vincent here, but I would have thought lb-based approach can go away.
Quoted 6 lines
Quoted 5 lines
I think in practice admins will care about specific applications to be kept within a single LLC, and if they are willing to spend the effort, they can tag specific tasks of a specific application.
Quoted 8 lines
Quoted 4 lines
It seems to me that there are multiple use cases. In one scenario, the administrator (including daemons) is responsible for tagging workloads. In another, users prefer the OS to handle automatic placement without any userspace involvement.
How do you define this automatic placement? AFAICS you're just grouping all tasks of a specific process to stay within the same LLC and hitting overcommit issues which you're workingaround with this load balancer only based approach?
The LLC chosen for aggregation (preferred LLC) is the one with most occupancy by tasks in a process.
However aggregation needs to be done with the load in target LLC and current in mind. It is better to keep a task in its current LLC if plenty of idle CPUs are available than move to an LLC where most of the threads are, but CPUs are frequently busy. This is the main reason why we put the migration logic in the load balancer where accurate load information is available and we could put
in load aware migration policy.
It is fine to migrate tasks in the wake up path. But we need to resolve the issue of over-aggregation, when multiple CPUs may push tasks
to a LLC independently of each other. It worsen things with
frequent tasks bouncing if we over-aggregate
and have to migrate tasks out of the LLC again. We encounter
such issues in our earlier implementations that have task migrations in the wake up path.
Quoted 20 lines
I think in practice there will be many corner cases where state is not optimal and we'd end up with heuristics to 'balance' things out and sensitivity to independent changes disturbing this fragile balance causing weird regressions and us slowly has less flexibility to move and shuffle code (okay, maybe too much doom and gloom, but we've been by this in the past :)).
I am not sure how many of these tests stressed the system with multiple critical processes running concurrently?
By making it a userspace problem they have to figure out the right balance and we can focus on providing the right mechanism.
Quoted 7 lines
Quoted 6 lines
Also QoS IMHO should be viewed as a scarce resource. For best effort delivery (which is the best we can do in reality, this is not hard real time system), it is easier to provide good best effort when the average noise level is low, ie:
few tasks are required to be kept within the same LLC. If we overcommit often, we will crumble often. So IMHO the key is to delegate to userspace to tag, and
Quoted 8 lines
Quoted 5 lines
I suppose there are two scenarios. The first is enabling/disabling aggregation
for a group of tasks, and the second is task tagging. For the first scenario,
this can be applied either process-wide or cgroup-wide by providing a flag,Cgroup-wide tagging doesn't make sense IMO. Process-wide yes.
I think this depends on the usage scenario. In private discussion with Vern from Tencent, he mentioned that such a cgroup based tagging is useful for them.
Tim
Quoted 34 lines
What does it mean to group all processes in the same cgroup from cache locality PoV? It just seems random setup based on something specific in userspace on how these cgroups are setup that assumes one process per group? I don't think we can generalize if that's the case.
Admins can use cpuset to statically partition based on cgroup if they want to ensure a group of processes are confined to the same LLC?
Quoted 5 lines
without requiring users to explicitly tag individual tasks. The second scenario
is an enhancement to support fine-grained control over a specific task. If
schedqos only supports scenario2, the user has to tag every task to support scenario1.You can do tagging process-wide (as I mentioned in the announcement, I think it's a poor man's way for quick tagging until people learn to do better), not just per-task eg:
{ "PostgreSQL": { "qos": ["QOS_USER_INTERACTIVE", "QOS_NUMA_SENSITIVE"] } }which will tag every task forked by this binary with a cookie and QoS data dependency tag tell the scheduler all tasks with the same cookie need to stay within the same LLC.
We can bikeshed naming and the tagging details, but the actual implementation principal should be the same: keep tasks with the same cookie and data dep tag on the same LLC at wake up; and let push lb handle occasional strayed task.
If users want to be smart and tag specific tasks only, the implementation would be identical, it's just there are fewer tasks tagged.
PATCH v3 1/1 sched/cache: Reduce the overhead of task_cache_work by only scan the visisted cpus.
In reply to Chen, Yu CThe overhead of task_cache_work is high, espeically in multi-NUMA system. Currently, task_cache_work try to find the pref_llc by scan all cpus in the system. However, most of these scans are meaningless, such as those for cpus that have never been visited or were accessed a long time ago.
To address this problem, this patch introduces visited_cpus to track the visited cpus and uses llc_epoch_affinity_timeout to evict cpus that have timed out.
---
Changes history
**v3 Changes:**
1. Remove the static key and enable this feature by default.
2. Reuse llc_epoch_affinity_timeout instead of introducing llc_epoch_visited_timeout.
3. Move the calculation of rq->cpu_epoch - pcpu_sched->epoch into fraction_mm_sched() to avoid race between task_cache_work() and __update_mm_sched().
4. Reset work->next at the end of task_cache_work() to prevent concurrent executions by multiple threads within the same process.
**v2 Changes:**
1. Added a pre-check before set/clear visited_cpus to avoid C2C overhead.
2. Optimized llc_epoch_visited_timeout by using a static key to minimize overhead.
--- include/linux/sched.h | 1 + kernel/sched/fair.c | 38 ++++++++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 8 deletions(-)
include/linux/sched.h +1 -0
@@ -2390,6 +2390,7 @@ struct sched_cache_time {struct sched_cache_stat {struct sched_cache_time __percpu *pcpu_sched; +struct cpumask visited_cpus;raw_spinlock_t lock;unsigned long epoch;u64 nr_running_avg;
kernel/sched/fair.c +30 -8
@@ -1466,6 +1466,7 @@ void mm_init_sched(struct mm_struct *mm,raw_spin_lock_init (&mm->sc_stat.lock); mm->sc_stat.epoch = epoch; mm->sc_stat.cpu =-1 ; +cpumask_clear (&mm->sc_stat.visited_cpus);/* * The update to mm->sc_stat should not be reordered
@@ -1507,11 +1508,18 @@ static inline void __update_mm_sched(struct rq *rq, } } -static unsigned long fraction_mm_sched (struct rq *rq, -struct sched_cache_time *pcpu_sched) +static unsigned long fraction_mm_sched (int cpu,struct mm_struct *mm) { +struct rq *rq =cpu_rq (cpu); +struct sched_cache_time *pcpu_sched =per_cpu_ptr (mm->sc_stat.pcpu_sched, cpu);guard (raw_spinlock_irqsave)(&rq->cpu_epoch_lock); +/* Skip the rq that has not been hit for a long time */ +if ((rq->cpu_epoch - pcpu_sched->epoch) > llc_epoch_affinity_timeout) { +cpumask_clear_cpu (cpu, &mm->sc_stat.visited_cpus); +return 0 ; + } +__update_mm_sched (rq, pcpu_sched);/*
@@ -1582,6 +1590,8 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) pcpu_sched->runtime += delta_exec; rq->cpu_runtime += delta_exec; epoch = rq->cpu_epoch; +if (!cpumask_test_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus)) +cpumask_set_cpu (cpu_of (rq), &mm->sc_stat.visited_cpus); }/*
@@ -1627,7 +1637,11 @@ static void task_tick_cache(struct rq *rq, struct task_struct *p)guard (raw_spinlock)(&mm->sc_stat.lock); -if (work->next == work) { +/* +* Pairs with smp_store_release in task_cache_work() to ensure that +* tash_cache_work() has finished before re-queueing the work. +*/ +if (smp_load_acquire (&work->next) == work) {task_work_add (p, work,TWA_RESUME );WRITE_ONCE (mm->sc_stat.epoch, epoch); }
@@ -1695,6 +1709,8 @@ static inline void update_avg_scale(u64 *avg, u64 sample) *avg +=div64_s64 (diff, divisor); } +DEFINE_FREE(reset_work, struct callback_head *, smp_store_release(&_T->next, _T)) +static void task_cache_work (struct callback_head *work) {int cpu, m_a_cpu =-1 , nr_running =0 , curr_cpu;
@@ -1703,11 +1719,14 @@ static void task_cache_work(struct callback_head *work)struct mm_struct *mm = p->mm;unsigned long m_a_occ =0 ;cpumask_var_t cpus; +/* +* Reset work->next at the end to avoid race between threads +* within a process. +*/ + struct callback_head *_w __free(reset_work) = work;WARN_ON_ONCE (work != &p->cache_work); - work->next = work; -if (p->flags &PF_EXITING )return ;
@@ -1725,6 +1744,7 @@ static void task_cache_work(struct callback_head *work)scoped_guard (cpus_read_lock) {get_scan_cpumasks (cpus, p); +cpumask_and (cpus, cpus, &mm->sc_stat.visited_cpus);for_each_cpu (cpu, cpus) {/* XXX sched_cluster_active */
@@ -1735,9 +1755,11 @@ static void task_cache_work(struct callback_head *work)if (!sd)continue ; -for_each_cpu (i,sched_domain_span (sd)) { - occ =fraction_mm_sched (cpu_rq (i), -per_cpu_ptr (mm->sc_stat.pcpu_sched, i)); +for_each_cpu_and (i,sched_domain_span (sd), &mm->sc_stat.visited_cpus) { + occ =fraction_mm_sched (i, mm); +if (occ ==0 ) +continue ; + a_occ += occ;if (occ > m_occ) { m_occ = occ;
Signature · 1 line
2.34.1
Quoted 11 lines · Tim Chen
Quoted 10 lines · Qais Yousef
Quoted 9 lines · Yu C
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
Quoted 4 lines
I posted schedqos announcement yesterday, which I think (hope) would be the right way to address these concerns about tagging tasks.
Quoted 6 lines
Quoted 3 lines
Quoted 3 lines
I think that's great. Will be a nice way to tag tasks that should be grouped and aggregated together.
To ensure it is clear, you can tag processes too, not just tasks. Though this is wasteful, but will allow easy tagging and quick results.
Quoted 45 lines
Quoted 26 lines
Quoted 13 lines
Thanks, I'll take a look at this.
Quoted 9 lines
It would be trivial to add experimental branch to add new QoS flavour to say
NUMA_SENSITIVEetc. I am still trying to think of a generic description to address a number of use cases (see Execution Profiles in README.md), not just this particular numa sensitive one, but the experimental branch should help iterate and drive the kernel development for wake up path + push lb instead of using load balance which I really doubt will work well in practice since this is slow to react, and you're relying on overcommitting the system by default by making every task of every process data dependent and require it to be co-located.Quoted 3 lines
I am not certain which strategy is preferable, as it largely depends on the use case and workload. We intend to evaluate push-based load balancing on top of the existing lb-based cache-aware placement logic.
I'll defer to Vincent here, but I would have thought lb-based approach can go away.
Quoted 6 lines
Quoted 5 lines
I think in practice admins will care about specific applications to be kept within a single LLC, and if they are willing to spend the effort, they can tag specific tasks of a specific application.
Quoted 8 lines
Quoted 4 lines
It seems to me that there are multiple use cases. In one scenario, the administrator (including daemons) is responsible for tagging workloads. In another, users prefer the OS to handle automatic placement without any userspace involvement.
How do you define this automatic placement? AFAICS you're just grouping all tasks of a specific process to stay within the same LLC and hitting overcommit issues which you're workingaround with this load balancer only based approach?
The LLC chosen for aggregation (preferred LLC) is the one with most occupancy by tasks in a process.
However aggregation needs to be done with the load in target LLC and current in mind. It is better to keep a task in its current LLC if plenty of idle CPUs are available than move to an LLC where most of the threads are, but CPUs are frequently busy. This is the main reason why we put the migration logic in the load balancer where accurate load information is available and we could put
in load aware migration policy.
Quoted 6 lines
It is fine to migrate tasks in the wake up path. But we need to resolve the issue of over-aggregation, when multiple CPUs may push tasks
to a LLC independently of each other. It worsen things with
frequent tasks bouncing if we over-aggregate
and have to migrate tasks out of the LLC again. We encounter
such issues in our earlier implementations that have task migrations in the wake up path.
Hmm I am still struggling to see how we can end up with these problem when we have few processes asking to be in the same LLC. With this series all processes are being grouped which I can see how this can lead to excessive ping ponging.
But I acknowledge the task might not be straight forward due to lack of accurate load information. But this can't be fixable at all under more controlled and relaxed environment is where I struggle. We are simplifying the problem essentially to help the kernel do better and easier.
Anyway. My goal is to help simplify the kernel details and defer the policy to the userspace completely. I am happy to work with you and Vincent to make sure we can address general QoS placement details on NUMA systems.
FWIW, if we want to implement wake up based on latency, it's the exact same problems. That's why I am stressing this point. We need to be able to extend and scale.
Quoted 28 lines
Quoted 28 lines
I think in practice there will be many corner cases where state is not optimal and we'd end up with heuristics to 'balance' things out and sensitivity to independent changes disturbing this fragile balance causing weird regressions and us slowly has less flexibility to move and shuffle code (okay, maybe too much doom and gloom, but we've been by this in the past :)).
I am not sure how many of these tests stressed the system with multiple critical processes running concurrently?
By making it a userspace problem they have to figure out the right balance and we can focus on providing the right mechanism.
Quoted 12 lines
Quoted 6 lines
Also QoS IMHO should be viewed as a scarce resource. For best effort delivery (which is the best we can do in reality, this is not hard real time system), it is easier to provide good best effort when the average noise level is low, ie:
few tasks are required to be kept within the same LLC. If we overcommit often, we will crumble often. So IMHO the key is to delegate to userspace to tag, andI suppose there are two scenarios. The first is enabling/disabling aggregation
for a group of tasks, and the second is task tagging. For the first scenario,
this can be applied either process-wide or cgroup-wide by providing a flag,
Quoted 5 lines
Quoted 2 lines
Cgroup-wide tagging doesn't make sense IMO. Process-wide yes.
I think this depends on the usage scenario. In private discussion with Vern from Tencent, he mentioned that such a cgroup based tagging is useful for them.
We all want ponies :)
I think this needs a why. It doesn't make sense to group procsses in general. It seems this requirement is tied to elaborate setup to force the kernel to deal with this elaborate setup in a generic manner.
Anyway with the tagging approach we can easily allow process level LLC sharing via simple description like
// shared cookie definition
{
"WEB_SERVICE_COOKIE": [ "nginx", "postgresql"],
"TRANSCODING_COOKIE": [ "decoder", "encoder"]
}Which simply tell the utility to reuse the cookie for these processes using the key as a unique identifier.
By the way, cookie generation might need kernel help to create a unique id.
Still, if someone wants such elaborate setup the first thing to suggest is static portioning via cpuset. Do you know why this is not sufficient?
Quoted 6 lines · Qais Yousef
Quoted 5 lines · Tim Chen
Quoted 4 lines · Qais Yousef
Quoted 3 lines · Yu C
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
Quoted 5 lines
I suppose there are two scenarios. The first is enabling/disabling aggregation
for a group of tasks, and the second is task tagging. For the first scenario,
this can be applied either process-wide or cgroup-wide by providing a flag,Cgroup-wide tagging doesn't make sense IMO. Process-wide yes.
Quoted 8 lines
Quoted 2 lines
I think this depends on the usage scenario. In private discussion with Vern from Tencent, he mentioned that such a cgroup based tagging is useful for them.
We all want ponies :)
I think this needs a why. It doesn't make sense to group procsses in general. It seems this requirement is tied to elaborate setup to force the kernel to deal with this elaborate setup in a generic manner.
Using cgroup tagging appears to be a trade-off intended to reduce users' overhead from interface migration. Based on feedback from several cloud providers (Vern, please correct me if my understanding is wrong), cgroups are the basic unit for infrastructure construction:
there could be a large process with N threads: N/2 of them are assigned to cgroup1, and the remaining N/2 to cgroup2. Updating the attributes associated with a cgroup is straightforward - using process-based aggregation might not work for this scenario - using task-based aggregation would require to re-write the mid-layer.
Quoted 10 lines
Anyway with the tagging approach we can easily allow process level LLC sharing via simple description like
// shared cookie definition
{ "WEB_SERVICE_COOKIE": [ "nginx", "postgresql"], "TRANSCODING_COOKIE": [ "decoder", "encoder"] }
Quoted 7 lines
Which simply tell the utility to reuse the cookie for these processes using the key as a unique identifier.
By the way, cookie generation might need kernel help to create a unique id.
Still, if someone wants such elaborate setup the first thing to suggest is static portioning via cpuset. Do you know why this is not sufficient?
I suppose it is because the admin want a high system utilization by mixing latency-sensitive tasks and batch tasks together to share the CPU resource. Using cpuset to isolate them might bring lower utilization.
thanks,
Chenyu
Quoted 15 lines · Qais Yousef
Quoted 9 lines · Yu C
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
It seems to me that there are multiple use cases. In one scenario, the administrator (including daemons) is responsible for tagging workloads. In another, users prefer the OS to handle automatic placement without any userspace involvement.
How do you define this automatic placement? AFAICS you're just grouping all tasks of a specific process to stay within the same LLC and hitting overcommit issues which you're workingaround with this load balancer only based approach?
Quoted 9 lines
I think in practice there will be many corner cases where state is not optimal and we'd end up with heuristics to 'balance' things out and sensitivity to independent changes disturbing this fragile balance causing weird regressions and us slowly has less flexibility to move and shuffle code (okay, maybe too much doom and gloom, but we've been by this in the past :)).
I am not sure how many of these tests stressed the system with multiple critical processes running concurrently?
In the initial RFC patches, we ran multi-process tests, where workloads were assigned by cache-aware LB to dedicated LLCs when under-loaded. I just conducted additional multi-process hackbench tests, and the results demonstrate improved stabilization with cache-aware LB enabled. Thus, I think for multi-process cases, there is no difference from single-process cases - the tasks can be aggregated to one LLC as long as it is under-loaded, no matter what process this migrating task belongs to.
Quoted 3 lines
By making it a userspace problem they have to figure out the right balance and we can focus on providing the right mechanism.
I totally agree that with the help from userspace, the task aggregation would become more usable. The test data would speak. Once we have resolved the issues reported by Sashiko we will evaluate the schedqos provided interface.
thanks,
Chenyu
Quoted 28 lines · Yu C
Quoted 6 lines · Qais Yousef
Quoted 5 lines · Tim Chen
Quoted 4 lines · Qais Yousef
Quoted 3 lines · Yu C
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
Quoted 5 lines
I suppose there are two scenarios. The first is enabling/disabling aggregation
for a group of tasks, and the second is task tagging. For the first scenario,
this can be applied either process-wide or cgroup-wide by providing a flag,Cgroup-wide tagging doesn't make sense IMO. Process-wide yes.
Quoted 8 lines
Quoted 2 lines
I think this depends on the usage scenario. In private discussion with Vern from Tencent, he mentioned that such a cgroup based tagging is useful for them.
We all want ponies :)
I think this needs a why. It doesn't make sense to group procsses in general. It seems this requirement is tied to elaborate setup to force the kernel to deal with this elaborate setup in a generic manner.
Quoted 6 lines
Using cgroup tagging appears to be a trade-off intended to reduce users' overhead from interface migration. Based on feedback from several cloud providers (Vern, please correct me if my understanding is wrong), cgroups are the basic unit for infrastructure construction:
there could be a large process with N threads: N/2 of them are assigned to cgroup1, and the remaining N/2 to cgroup2.
Ah so the problem is single large process. Shouldn't the kernel manage that and split into LLCs automatically as part of its best effort?
I don't think there's any migration cost for tagging a whole process. It is just wasting resources. Those who want to squeeze more, they have the option to do better, but don't have to.
Quoted 2 lines
Updating the attributes associated with a cgroup is straightforward - using process-based aggregation might not work
Why not? wake up or LB based, we should be able to see a process has loaded an LLC and spill to another LLC, no?
Quoted 2 lines
for this scenario - using task-based aggregation would require to re-write the mid-layer.
As mentioned above, this is the smartest opportunity to squeeze more out of the system. It will require more work yes, but totally optional too.
Quoted 14 lines
Quoted 14 lines
Anyway with the tagging approach we can easily allow process level LLC sharing via simple description like
// shared cookie definition
{ "WEB_SERVICE_COOKIE": [ "nginx", "postgresql"], "TRANSCODING_COOKIE": [ "decoder", "encoder"] }Which simply tell the utility to reuse the cookie for these processes using the key as a unique identifier.
Quoted 8 lines
Quoted 4 lines
By the way, cookie generation might need kernel help to create a unique id.
Still, if someone wants such elaborate setup the first thing to suggest is static portioning via cpuset. Do you know why this is not sufficient?
I suppose it is because the admin want a high system utilization by mixing latency-sensitive tasks and batch tasks together to share the CPU resource. Using cpuset to isolate them might bring lower utilization.
Hmm yes I get and advocate that. I just don't get it if the request is to tag multiple process to share LLC. This is not cache aware scheduling, this is a partitioning problem.
Note we want to use the concept to help with co-locating tasks in a single LLC to take advantage of bigger L2. Currently it seems the approach is hardwired to a particular need.
Quoted 26 lines · Yu C
Quoted 15 lines · Qais Yousef
Quoted 9 lines · Yu C
Quoted 1 line · Qais Yousef
On 04/01/26 14:52, Tim Chen wrote:
[ ... ]
It seems to me that there are multiple use cases. In one scenario, the administrator (including daemons) is responsible for tagging workloads. In another, users prefer the OS to handle automatic placement without any userspace involvement.
How do you define this automatic placement? AFAICS you're just grouping all tasks of a specific process to stay within the same LLC and hitting overcommit issues which you're workingaround with this load balancer only based approach?
Quoted 9 lines
I think in practice there will be many corner cases where state is not optimal and we'd end up with heuristics to 'balance' things out and sensitivity to independent changes disturbing this fragile balance causing weird regressions and us slowly has less flexibility to move and shuffle code (okay, maybe too much doom and gloom, but we've been by this in the past :)).
I am not sure how many of these tests stressed the system with multiple critical processes running concurrently?
Quoted 9 lines
In the initial RFC patches, we ran multi-process tests, where workloads were assigned by cache-aware LB to dedicated LLCs when under-loaded. I just conducted additional multi-process hackbench tests, and the results demonstrate improved stabilization with cache-aware LB enabled. Thus, I think for multi-process cases, there is no difference from single-process cases - the tasks can be aggregated to one LLC as long as it is under-loaded, no matter what process this migrating task belongs to.
Multi as in > num_llcs?
Doing my own tests with schedqos and monitor the schedqos log, I was surprised how many processes are created from simplest of operations.
My worry is that since you assume all processes must be grouped, in real life scenario you will end up with processes > num_llc in many corner cases.
With opt-in approach, you know exactly how many there will be and admins can design for it.
Quoted 9 lines
Quoted 4 lines
By making it a userspace problem they have to figure out the right balance and we can focus on providing the right mechanism.
I totally agree that with the help from userspace, the task aggregation would become more usable. The test data would speak. Once we have resolved the issues reported by Sashiko we will evaluate the schedqos provided interface.
Great. Happy to work closely with you to help iron out problems.
Re: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
In reply to Tim ChenQuoted 361 lines · Tim Chen
From: "Peter Zijlstra (Intel)" <[email protected]>
Adds infrastructure to enable cache-aware load balancing, which improves cache locality by grouping tasks that share resources within the same cache domain. This reduces cache misses and improves overall data access efficiency.
In this initial implementation, threads belonging to the same process are treated as entities that likely share working sets. The mechanism tracks per-process CPU occupancy across cache domains and attempts to migrate threads toward cache-hot domains where their process already has active threads, thereby enhancing locality.
This provides a basic model for cache affinity. While the current code targets the last-level cache (LLC), the approach could be extended to other domain types such as clusters (L2) or node-internal groupings.
At present, the mechanism selects the CPU within an LLC that has the highest recent runtime. Subsequent patches in this series will use this information in the load-balancing path to guide task placement toward preferred LLCs.
In the future, more advanced policies could be integrated through NUMA balancing-for example, migrating a task to its preferred LLC when spare capacity exists, or swapping tasks across LLCs to improve cache affinity. Grouping of tasks could also be generalized from that of a process to be that of a NUMA group, or be user configurable.
Signed-off-by Peter Zijlstra (Intel) <[email protected]>Signed-off-by Chen Yu <[email protected]>Signed-off-by Tim Chen <[email protected]>---
Notes:
v3->v4: No change.include/linux/mm_types.h | 32 +++++ include/linux/sched.h | 24 ++++ init/Kconfig | 11 ++ kernel/fork.c | 6 + kernel/sched/core.c | 6 + kernel/sched/fair.c | 266 +++++++++++++++++++++++++++++++++++++++ kernel/sched/sched.h | 14 +++ 7 files changed, 359 insertions(+)include/linux/mm_types.h +32
-0@@ -1173,6 +1173,8 @@ struct mm_struct {/* MM CID related storage */ struct mm_mm_cid mm_cid; +/* sched_cache related statistics */ +struct sched_cache_stat sc_stat;#ifdef CONFIG_MMU atomic_long_t pgtables_bytes;/* size of all page tables */ #endif @@ -1575,6 +1577,36 @@ static inline unsigned int mm_cid_size(void)# define MM_CID_STATIC_SIZE 0#endif /* CONFIG_SCHED_MM_CID */ +#ifdef CONFIG_SCHED_CACHE +void mm_init_sched (struct mm_struct *mm, +struct sched_cache_time __percpu *pcpu_sched); + +static inline int mm_alloc_sched_noprof (struct mm_struct *mm) +{ +struct sched_cache_time __percpu *pcpu_sched = + alloc_percpu_noprof(struct sched_cache_time); + +if (!pcpu_sched) +return -ENOMEM ; + +mm_init_sched (mm, pcpu_sched); +return 0 ; +} + +#define mm_alloc_sched (...) alloc_hooks(mm_alloc_sched_noprof(__VA_ARGS__)) + +static inline void mm_destroy_sched (struct mm_struct *mm) +{ +free_percpu (mm->sc_stat.pcpu_sched); + mm->sc_stat.pcpu_sched =NULL ; +} +#else /* !CONFIG_SCHED_CACHE */ + +static inline int mm_alloc_sched (struct mm_struct *mm) {return 0 ; } +static inline void mm_destroy_sched (struct mm_struct *mm) { } + +#endif /* CONFIG_SCHED_CACHE */ +struct mmu_gather ;extern void tlb_gather_mmu (struct mmu_gather *tlb,struct mm_struct *mm);extern void tlb_gather_mmu_fullmm (struct mmu_gather *tlb,struct mm_struct *mm);include/linux/sched.h +24
-0@@ -1406,6 +1406,10 @@ struct task_struct {unsigned long numa_pages_migrated;#endif /* CONFIG_NUMA_BALANCING */ +#ifdef CONFIG_SCHED_CACHE +struct callback_head cache_work; +#endif +struct rseq_data rseq;struct sched_mm_cid mm_cid;@@ -2376,6 +2380,26 @@ static __always_inline int task_mm_cid(struct task_struct *t) }#endif +#ifdef CONFIG_SCHED_CACHE + +struct sched_cache_time { +u64 runtime; +unsigned long epoch; +}; + +struct sched_cache_stat { +struct sched_cache_time __percpu *pcpu_sched; +raw_spinlock_t lock; +unsigned long epoch; +int cpu; +}____cacheline_aligned_in_smp ; + +#else + +struct sched_cache_stat { }; + +#endif +#ifndef MODULE #ifndef COMPILE_OFFSETS init/Kconfig +11
-0@@ -1005,6 +1005,17 @@ config NUMA_BALANCING This system will be inactive on UMA systems. +config SCHED_CACHE + bool "Cache aware load balance" + default y + depends on SMP + help + When enabled, the scheduler will attempt to aggregate tasks from + the same process onto a single Last Level Cache (LLC) domain when + possible. This improves cache locality by keeping tasks that share + resources within the same cache domain, reducing cache misses and + lowering data access latency. + config NUMA_BALANCING_DEFAULT_ENABLED bool "Automatically enable NUMA aware memory/task placement" default ykernel/fork.c +6
-0@@ -724,6 +724,7 @@ void __mmdrop(struct mm_struct *mm)cleanup_lazy_tlbs (mm);WARN_ON_ONCE (mm == current->active_mm); +mm_destroy_sched (mm);mm_free_pgd (mm);mm_free_id (mm);destroy_context (mm);@@ -1124,6 +1125,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,if (mm_alloc_cid (mm, p)) goto fail_cid; +if (mm_alloc_sched (mm)) + goto fail_sched; +if (percpu_counter_init_many (mm->rss_stat,0 ,GFP_KERNEL_ACCOUNT ,NR_MM_COUNTERS )) goto fail_pcpu;@@ -1133,6 +1137,8 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,return mm; fail_pcpu: +mm_destroy_sched (mm); +fail_sched:mm_destroy_cid (mm); fail_cid:destroy_context (mm);kernel/sched/core.c +6
-0@@ -4437,6 +4437,7 @@ static void __sched_fork(u64 clone_flags, struct task_struct *p)init_numa_balancing (clone_flags, p); p->wake_entry.u_flags =CSD_TYPE_TTWU ; p->migration_pending =NULL ; +init_sched_mm (p); }DEFINE_STATIC_KEY_FALSE (sched_numa_balancing);@@ -8749,6 +8750,11 @@ void __init sched_init(void) rq->core_cookie =0UL ;#endif +#ifdef CONFIG_SCHED_CACHE +raw_spin_lock_init (&rq->cpu_epoch_lock); + rq->cpu_epoch_next = jiffies; +#endif +zalloc_cpumask_var_node (&rq->scratch_mask,GFP_KERNEL ,cpu_to_node (i)); }kernel/sched/fair.c +124
-0@@ -1228,6 +1228,8 @@ void post_init_entity_util_avg(struct task_struct *p) sa->runnable_avg = sa->util_avg; } +static inline void account_mm_sched (struct rq *rq,struct task_struct *p,s64 delta_exec); +static s64 update_se (struct rq *rq,struct sched_entity *se) {u64 now =rq_clock_task (rq);@@ -1250,6 +1252,7 @@ static s64 update_se(struct rq *rq, struct sched_entity *se)trace_sched_stat_runtime (running, delta_exec);account_group_exec_runtime (running, delta_exec); +account_mm_sched (rq, running, delta_exec);/* cgroup time is always accounted against the donor */ cgroup_account_cputime (donor, delta_exec);@@ -1271,6 +1274,267 @@ static s64 update_se(struct rq *rq, struct sched_entity *se)static void set_next_buddy (struct sched_entity *se); +#ifdef CONFIG_SCHED_CACHE + +/* +* XXX numbers come from a place the sun don't shine -- probably wants to be SD +* tunable or so. +*/ +#define EPOCH_PERIOD (HZ / 100)/* 10 ms */ +#define EPOCH_LLC_AFFINITY_TIMEOUT 5/* 50 ms */ + +static int llc_id (int cpu) +{ +if (cpu <0 ) +return -1 ; + +return per_cpu (sd_llc_id, cpu); +} + +void mm_init_sched (struct mm_struct *mm, +struct sched_cache_time __percpu *_pcpu_sched) +{ +unsigned long epoch =0 ; +int i; + +for_each_possible_cpu (i) { +struct sched_cache_time *pcpu_sched =per_cpu_ptr (_pcpu_sched, i); +struct rq *rq =cpu_rq (i); + + pcpu_sched->runtime =0 ; +/* a slightly stale cpu epoch is acceptible */ + pcpu_sched->epoch = rq->cpu_epoch; + epoch = rq->cpu_epoch; + } + +raw_spin_lock_init (&mm->sc_stat.lock); + mm->sc_stat.epoch = epoch; + mm->sc_stat.cpu =-1 ; + +/* +* The update to mm->sc_stat should not be reordered +* before initialization to mm's other fields, in case +* the readers may get invalid mm_sched_epoch, etc. +*/ +smp_store_release (&mm->sc_stat.pcpu_sched, _pcpu_sched); +} + +/* because why would C be fully specified */ +static __always_inline void __shr_u64(u64 *val, unsigned int n) +{ +if (n >=64 ) { + *val =0 ; +return ; + } + *val >>= n; +} + +static inline void __update_mm_sched (struct rq *rq, +struct sched_cache_time *pcpu_sched) +{ +lockdep_assert_held (&rq->cpu_epoch_lock); + +unsigned long n, now = jiffies; +long delta = now - rq->cpu_epoch_next; + +if (delta >0 ) { + n = (delta +EPOCH_PERIOD -1 ) /EPOCH_PERIOD ; + rq->cpu_epoch += n; + rq->cpu_epoch_next += n *EPOCH_PERIOD ; +__shr_u64 (&rq->cpu_runtime, n); + } + + n = rq->cpu_epoch - pcpu_sched->epoch; +if (n) { + pcpu_sched->epoch += n; +__shr_u64 (&pcpu_sched->runtime, n); + } +} + +static unsigned long fraction_mm_sched (struct rq *rq, +struct sched_cache_time *pcpu_sched) +{ +guard (raw_spinlock_irqsave)(&rq->cpu_epoch_lock); + +__update_mm_sched (rq, pcpu_sched); + +/* +* Runtime is a geometric series (r=0.5) and as such will sum to twice +* the accumulation period, this means the multiplcation here should +* not overflow. +*/ +return div64_u64 (NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime +1 ); +} + +static inline +void account_mm_sched (struct rq *rq,struct task_struct *p,s64 delta_exec) +{ +struct sched_cache_time *pcpu_sched; +struct mm_struct *mm = p->mm; +unsigned long epoch; + +if (!sched_cache_enabled ()) +return ; + +if (p->sched_class != &fair_sched_class) +return ; +/* +* init_task, kthreads and user thread created +* by user_mode_thread() don't have mm. +*/ +if (!mm || !mm->sc_stat.pcpu_sched) +return ; + + pcpu_sched =per_cpu_ptr (p->mm->sc_stat.pcpu_sched,cpu_of (rq)); + + scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) { +__update_mm_sched (rq, pcpu_sched); + pcpu_sched->runtime += delta_exec; + rq->cpu_runtime += delta_exec; + epoch = rq->cpu_epoch; + } + +/*
kernel/sched/fair.c static s64 update_se(struct rq *rq, struct sched_entity *se) · line 1407
Quoted 10 lines
kernel/sched/fair.c +10
-0+* If this process hasn't hit task_cache_work() for a while, or it +* has only 1 thread, invalidate its preferred state. +*/ +if (time_after (epoch, +READ_ONCE (mm->sc_stat.epoch) +EPOCH_LLC_AFFINITY_TIMEOUT ) || +get_nr_threads (p) <=1 ) { +if (mm->sc_stat.cpu !=-1 ) + mm->sc_stat.cpu =-1 ; + } +}
I sporadically hit the SLUB "Poison overwritten" reports on the mm_struct cache while running mm-new:
[Poison overwritten] 0xffff8001076ec8e8-0xffff8001076ec8eb @offset=51432. First byte 0xff instead of 0x6b
=============================================================================
BUG mm_struct (Tainted: G N ): Object corrupt
-----------------------------------------------------------------------------
Allocated in copy_process+0x1e48/0x2078 age=2 cpu=7 pid=11866
copy_process+0x1e48/0x2078 kernel_clone+0xa4/0x498 __do_sys_clone+0x5c/0x88 __arm64_sys_clone+0x1c/0x28 invoke_syscall+0x54/0x110 el0_svc_common.constprop.0+0x40/0xe0 do_el0_svc+0x1c/0x28 el0_svc+0x54/0x424 el0t_64_sync_handler+0xa0/0xe4 el0t_64_sync+0x1b0/0x1b4 Freed in __mmdrop+0x108/0x180 age=2 cpu=3 pid=11955 kmem_cache_free+0x290/0x53c __mmdrop+0x108/0x180 __mmput+0x150/0x154 mmput+0x50/0x5c exec_mm_put_old+0x74/0x84 setup_new_exec+0x7c/0x90 load_elf_binary+0x4b0/0x1914 bprm_execve+0x300/0x83c do_execveat_common+0x168/0x1cc __arm64_sys_execve+0x44/0x68 invoke_syscall+0x54/0x110 el0_svc_common.constprop.0+0x40/0xe0 do_el0_svc+0x1c/0x28 el0_svc+0x54/0x424 el0t_64_sync_handler+0xa0/0xe4 el0t_64_sync+0x1b0/0x1b4 Slab 0xffffffbfc1076e00 objects=23 used=18 fp=0xffff8001076e2140 flags=0x13fffe0000000240(workingset|head|node=1|zone=0|lastcpupid=0x1ffff) Object 0xffff8001076ec640 @offset=50752 fp=0xffff8001076e2140
[...]
The corruption is always exactly 4 bytes (0xffffffff) with everything around still being intact poison. The in-object offset (51432 - 50752 =
680) resolves to &mm->sc_stat.cpu, and 0xffffffff is just -1. My AI model points me to this write in account_mm_sched():
if (READ_ONCE(mm->sc_stat.cpu) != -1) WRITE_ONCE(mm->sc_stat.cpu, -1);
and helps with analyzing and fixing the issue like below :-) . Please have a look.
Thanks,
Zenghui
---8<---
From 992b515f18710e77308cf5f88943cc3ce918a525 Mon Sep 17 00:00:00 2001
From: "Zenghui Yu (Huawei)" <[email protected]>
Date: Mon, 14 Sep 2026 22:00:18 +0800
Subject: [PATCH] sched/cache: Fix use-after-free of mm in account_mm_sched()
account_mm_sched() accounts runtime against rq->curr and dereferences its ->mm: it updates the percpu chunk mm->sc_stat.pcpu_sched and may write mm->sc_stat.cpu = -1.
update_se(), which samples rq->curr and calls account_mm_sched(), is not only called from local contexts (tick, context switch) but also through update_curr() from enqueue/dequeue paths, which frequently run on a remote CPU while holding this rq's lock (cross-CPU try_to_wake_up(), load balancing).
In those remote contexts rq->curr is a task concurrently running on its home CPU. The rq lock guarantees that rq->curr's identity does not change, but it says nothing about the lifetime of rq->curr->mm: that task does not need the rq lock to execute execve or exit, and switches and drops its ->mm under task_lock() and mmput(), neither of which orders against the remote CPU. A remote CPU can therefore sample a valid mm pointer right before it is freed and write to it afterwards, corrupting the freed mm_struct (and the pcpu_sched percpu chunk, which mm_destroy_sched() frees even earlier).
Observed with CONFIG_SLUB_DEBUG=y as a sporadic "Poison overwritten" report on the mm_struct cache, with the overwritten bytes resolving to &mm->sc_stat.cpu.
Only account the physically running task (p == current), whose ->mm cannot go away while it is the one executing this code. Local tick, context switch and sched_ttwu_pending() paths are unaffected; updates skipped in remote contexts only cause minor under-accounting of the sc_stat runtime heuristics.
--- kernel/sched/fair.c | 3 +++ 1 file changed, 3 insertions(+)
kernel/sched/fair.c +3 -0
@@ -1731,6 +1731,9 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)int mm_sched_llc =-1 ;unsigned long epoch; +if (p != current) +return ; +if (!sched_cache_enabled ())return ;
Signature · 1 line
2.53.0
Re: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
Quoted 1 line · Zenghui Yu
[snip]
Quoted 55 lines
I sporadically hit the SLUB "Poison overwritten" reports on the
mm_structcache while running mm-new:[Poison overwritten] 0xffff8001076ec8e8-0xffff8001076ec8eb @offset=51432. First byte
0xffinstead of0x6b
=============================================================================
BUGmm_struct(Tainted: G N ): Object corrupt
-----------------------------------------------------------------------------Allocated in
copy_process+0x1e48/0x2078age=2 cpu=7 pid=11866copy_process+0x1e48/0x2078 kernel_clone+0xa4/0x498 __do_sys_clone+0x5c/0x88 __arm64_sys_clone+0x1c/0x28 invoke_syscall+0x54/0x110 el0_svc_common.constprop.0+0x40/0xe0 do_el0_svc+0x1c/0x28 el0_svc+0x54/0x424 el0t_64_sync_handler+0xa0/0xe4 el0t_64_sync+0x1b0/0x1b4 Freed in __mmdrop+0x108/0x180 age=2 cpu=3 pid=11955 kmem_cache_free+0x290/0x53c __mmdrop+0x108/0x180 __mmput+0x150/0x154 mmput+0x50/0x5c exec_mm_put_old+0x74/0x84 setup_new_exec+0x7c/0x90 load_elf_binary+0x4b0/0x1914 bprm_execve+0x300/0x83c do_execveat_common+0x168/0x1cc __arm64_sys_execve+0x44/0x68 invoke_syscall+0x54/0x110 el0_svc_common.constprop.0+0x40/0xe0 do_el0_svc+0x1c/0x28 el0_svc+0x54/0x424 el0t_64_sync_handler+0xa0/0xe4 el0t_64_sync+0x1b0/0x1b4 Slab 0xffffffbfc1076e00 objects=23 used=18 fp=0xffff8001076e2140 flags=0x13fffe0000000240(workingset|head|node=1|zone=0|lastcpupid=0x1ffff) Object 0xffff8001076ec640 @offset=50752 fp=0xffff8001076e2140[...]
The corruption is always exactly 4 bytes (
0xffffffff) with everything around still being intact poison. The in-object offset (51432 - 50752 =
680) resolves to&mm->sc_stat.cpu, and0xffffffffis just -1. My AI model points me to this write inaccount_mm_sched():if (READ_ONCE(mm->sc_stat.cpu) != -1) WRITE_ONCE(mm->sc_stat.cpu, -1);and helps with analyzing and fixing the issue like below :-) . Please have a look.
Thanks,
Zenghui
Quoted 6 lines
---8<---
From
992b515f18710e77308cf5f88943cc3ce918a525Mon Sep 17 00:00:00 2001
From: "Zenghui Yu (Huawei)" <[email protected]>
Date: Mon, 14 Sep 2026 22:00:18 +0800
Subject: [PATCH] sched/cache: Fix use-after-free of mm inaccount_mm_sched()
I think you have hit a similar use after free issue that was discussed in this thread.
https://lore.kernel.org/lkml/apPb-Dr4nPYuHQOK@v4bel/
Can you try the last two patches in this 4 patch series that address this issue in a comprehensive way
https://lore.kernel.org/lkml/[email protected]/
Thanks.
Tim
Quoted 51 lines
account_mm_sched()accounts runtime againstrq->currand dereferences its ->mm: it updates the percpu chunkmm->sc_stat.pcpu_schedand may writemm->sc_stat.cpu= -1.
update_se(), which samplesrq->currand callsaccount_mm_sched(), is not only called from local contexts (tick, context switch) but also throughupdate_curr()from enqueue/dequeue paths, which frequently run on a remote CPU while holding this rq's lock (cross-CPUtry_to_wake_up(), load balancing).In those remote contexts
rq->curris a task concurrently running on its home CPU. The rq lock guarantees that rq->curr's identity does not change, but it says nothing about the lifetime ofrq->curr->mm: that task does not need the rq lock to execute execve or exit, and switches and drops its ->mm undertask_lock()andmmput(), neither of which orders against the remote CPU. A remote CPU can therefore sample a valid mm pointer right before it is freed and write to it afterwards, corrupting the freedmm_struct(and thepcpu_schedpercpu chunk, whichmm_destroy_sched()frees even earlier).Observed with
CONFIG_SLUB_DEBUG=yas a sporadic "Poison overwritten" report on themm_structcache, with the overwritten bytes resolving to&mm->sc_stat.cpu.Only account the physically running task (p == current), whose ->mm cannot go away while it is the one executing this code. Local tick, context switch and
sched_ttwu_pending()paths are unaffected; updates skipped in remote contexts only cause minor under-accounting of thesc_statruntime heuristics.Fixes df0d98475954 ("sched/cache: Introduce infrastructure for cache-aware load balancing")Assisted-by GLM-5.3 OpenCodeSigned-off-by Zenghui Yu (Huawei) <[email protected]>--- kernel/sched/fair.c | 3 +++ 1 file changed, 3 insertions(+)kernel/sched/fair.c +3
-0@@ -1731,6 +1731,9 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)int mm_sched_llc =-1 ;unsigned long epoch; +if (p != current) +return ; +if (!sched_cache_enabled ())return ;
Re: [Patch v4 01/22] sched/cache: Introduce infrastructure for cache-aware load balancing
Quoted 59 lines · Tim Chen
Quoted 1 line · Zenghui Yu
[snip]
Quoted 54 lines
I sporadically hit the SLUB "Poison overwritten" reports on the
mm_structcache while running mm-new:[Poison overwritten] 0xffff8001076ec8e8-0xffff8001076ec8eb @offset=51432. First byte
0xffinstead of0x6b
=============================================================================
BUGmm_struct(Tainted: G N ): Object corrupt
-----------------------------------------------------------------------------Allocated in
copy_process+0x1e48/0x2078age=2 cpu=7 pid=11866copy_process+0x1e48/0x2078 kernel_clone+0xa4/0x498 __do_sys_clone+0x5c/0x88 __arm64_sys_clone+0x1c/0x28 invoke_syscall+0x54/0x110 el0_svc_common.constprop.0+0x40/0xe0 do_el0_svc+0x1c/0x28 el0_svc+0x54/0x424 el0t_64_sync_handler+0xa0/0xe4 el0t_64_sync+0x1b0/0x1b4 Freed in __mmdrop+0x108/0x180 age=2 cpu=3 pid=11955 kmem_cache_free+0x290/0x53c __mmdrop+0x108/0x180 __mmput+0x150/0x154 mmput+0x50/0x5c exec_mm_put_old+0x74/0x84 setup_new_exec+0x7c/0x90 load_elf_binary+0x4b0/0x1914 bprm_execve+0x300/0x83c do_execveat_common+0x168/0x1cc __arm64_sys_execve+0x44/0x68 invoke_syscall+0x54/0x110 el0_svc_common.constprop.0+0x40/0xe0 do_el0_svc+0x1c/0x28 el0_svc+0x54/0x424 el0t_64_sync_handler+0xa0/0xe4 el0t_64_sync+0x1b0/0x1b4 Slab 0xffffffbfc1076e00 objects=23 used=18 fp=0xffff8001076e2140 flags=0x13fffe0000000240(workingset|head|node=1|zone=0|lastcpupid=0x1ffff) Object 0xffff8001076ec640 @offset=50752 fp=0xffff8001076e2140[...]
The corruption is always exactly 4 bytes (
0xffffffff) with everything around still being intact poison. The in-object offset (51432 - 50752 =
680) resolves to&mm->sc_stat.cpu, and0xffffffffis just -1. My AI model points me to this write inaccount_mm_sched():if (READ_ONCE(mm->sc_stat.cpu) != -1) WRITE_ONCE(mm->sc_stat.cpu, -1);and helps with analyzing and fixing the issue like below :-) . Please have a look.
---8<---
Quoted 8 lines
Quoted 4 lines
From
992b515f18710e77308cf5f88943cc3ce918a525Mon Sep 17 00:00:00 2001
From: "Zenghui Yu (Huawei)" <[email protected]>
Date: Mon, 14 Sep 2026 22:00:18 +0800
Subject: [PATCH] sched/cache: Fix use-after-free of mm inaccount_mm_sched()I think you have hit a similar use after free issue that was discussed in this thread.
https://lore.kernel.org/lkml/apPb-Dr4nPYuHQOK@v4bel/
I agree.
Quoted 3 lines
Can you try the last two patches in this 4 patch series that address this issue in a comprehensive way
https://lore.kernel.org/lkml/[email protected]/
I'll have a try. Thanks for the heads up!
Thanks,
Zenghui
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
In reply to Peter ZijlstraHi Peter, Chen Yu, Tim,
We have a workload where cache-aware scheduling (CAS) causes a large regression: NAS MG class D [3] - a memory-bandwidth-bound multigrid, 112 OpenMP threads, 26.4 GiB working set - runs 65% slower with the llc_balancing switch on (25.5s -> 42.2s median, n=5), because CAS aggregates all 112 threads onto one LLC. On this system each LLC is a whole socket, so the process is left with one socket's memory bandwidth for a working set 250x the LLC size.
The check that should keep such a process out of aggregation is this patch, merged as 808915f982c2 via the May enhancements series, with the RSS comparison replaced by a footprint estimate from NUMA balancing fault statistics following the discussion here. On this Sierra Forest system that estimate stays at 0 for MG even with NUMA balancing active, and the NUMA balancing off case Chen Yu left open here costs the same.
On this platform the footprint check is the only safeguard that can catch such a process. Of the safety valves listed in the new sched-cache.rst [1], the thread limit is ~115 threads (80% of 144 CPUs) and the busy threshold is 75% utilization (no SMT): the 112-thread run above sits just under the limit and passes both, and so does the 64-thread one (44% utilization). And unlike platforms with several LLCs per node, where aggregation trades a node's bandwidth for one LLC's, here it simply halves the bandwidth available to the process.
PLATFORM
2x Intel Xeon 6780E (Sierra Forest), 144 cores each, SMT off, 288 CPUs. One 108 MiB LLC per socket; each LLC coincides with one NUMA node. Kernel: v7.4-rc2-based, kernel.numa_balancing=1, aggr_tolerance=1. n=5 independent runs per configuration, CAS master switch off (baseline) vs on.
RESULTS (runtime, lower is better)
workload CAS OFF CAS ON delta
NAS MG class D, 1 proc x 112thr 25.53s med 42.23s med +65% NAS MG class D, 1 proc x 64thr 26.45s med 41.78s med +58% NAS MG class D, 1 proc x 32thr 35.06s med 51.04s med +46% NAS MG class C, 1 proc x 4thr 9.34s med 11.99s med +28%
THE FOOTPRINT ESTIMATE NEVER LEAVES ZERO (MG class D, 64 threads)
Traced live on the stock kernel with bpftrace (comm-filtered), across three CAS-on runs:
- grp->footprint: 0 in 44,670 and 40,638 task_cache_work() samples over two full runs (min = max = 0), while ~7M pages (26.4 GiB) were resident. NUMA balancing was active: 8k-20k hint faults and up to 3.3M pages migrated per run.
- In those two runs the footprint write never executed: all ~8k-13k task_numa_placement() calls per run (one per hint fault, via task_numa_fault()) returned at the scan_seq gate.
WHY THE SIGNAL NEVER ACCUMULATES
1. grp->footprint is only written in task_numa_placement(), which runs only when mm->numa_scan_seq changes. That counter increments only in reset_ptenuma_scan(): when the NUMA scanner has wrapped the whole address space.
2. The scanner walks the 26.4 GiB of mappings at ~0.3-1 GiB/s (traced via mm->numa_scan_offset and change_prot_numa() return values), so one sweep takes 30-40s or more. The 43s benchmark completed 0 sweeps in two runs, 1 sweep (at t=33s) in a third. The accounting runs at most once per task per run.
3. The signal is also small: a run accumulates only 8k-20k hint-fault events, 0.1-0.3% of the working set, below the 108 MiB threshold even when a sweep does complete.
4. And it is a rate signal, not a size: the increment is diff = numa_faults[MEMBUF] - numa_faults[MEM] / 2, which is zero at any steady fault rate.
Cadence, coverage and formula each independently hold the footprint orders of magnitude below the resident set.
exceed_llc_capacity() is evaluated on every tick and every scan epoch, but with footprint at 0 the comparison
llc_bytes * scale < footprint * PAGE_SIZE
is never true, so grp->cpu is never reset. After a 1.8s warm-up it pointed at the same LLC for all 44,661 remaining samples.
Without NUMA balancing the check never triggers, as sched-cache.rst documents. With CAS on and numa_balancing=0 the same run takes 42.2s, the same as with NUMA balancing on (42.0s).
WHAT THE AGGREGATION COSTS (MG class D, 64 threads)
- With CAS on, 97% of thread-samples are on one node. The 26.4 GiB
working set starts ~50/50 across the nodes and NUMA balancing
then pulls it to the busy node (numa_maps 3.3M/2.7M pages ->
6.7M/0.2M; 1.42M pages migrated during the run). - The cost is not on the CPU side: average CPU utilization is essentially unchanged (6164% vs 6029% - about 61 of the 64 threads on-CPU in both configurations), and wakeup latency is 49us on average, 0.73ms max (perf sched). What grows is UserTime, +48%: the threads keep running, each operation just stalls longer on memory.
- The cost is the placement itself, not migration or remote accesses:
a) 32 threads: memory fully converges to the busy node well before the run ends, and the run is still 46% slower;
b) CAS on with numa_balancing=0: no migrations, pages stay 65/35, and the runtime is unchanged (42.2s);
c) CAS off with the process simply taskset-pinned to one socket (memory 100% local from first touch, no migrations): 40.3s, within the CAS-on range (40.6-42.9s).
64 memory-streaming threads on one socket get about two thirds of the throughput they get spread across both sockets (Mop/s -34%), wherever the pages live. So the only effective fix is to not aggregate such a process in the first place.
QUESTIONS
1. Was the sweep-boundary gating of this accounting known or intended? For a workload with a large address space it means the footprint sees at most one update per run; for a shorter one, none at all.
2. Could the check fail closed when there is no usable estimate (warm-up, footprint still 0, NUMA balancing off)? RSS is a poor estimate of the working set, as Peter said, but it is an upper
bound: if RSS fits in the LLC, so does the working set. Using it only on the permit side - aggregate without a footprint estimate only if RSS fits - would keep the gains for small processes and not aggregate the ones we cannot judge. The costs are
asymmetric: a missed aggregation forfeits a gain, a wrong one cost 65% here.
3. Our data supports Peter's point that LLC hit/miss information would be the better signal: the damage is purely memory-side (UserTime +59% at flat CPU% in the 112-thread run), and a memory-streaming process would show a low hit rate regardless of how well its footprint is estimated. Is anyone looking at that?
4. Chen Yu mentioned that you are reworking the footprint accounting for the prctl v2 series [2]. Could the detection fix be part of that rework?
[1] <50a8055e38958cdc39e07435aaad56e4719b2bd3.1794507151.git.tim.c.chen@linux.intel.com>
[2] <[email protected]>
[3] NAS Parallel Benchmarks: https://www.nas.nasa.gov/software/npb.html
MG is the multigrid kernel: four V-cycles of 27-point stencil
sweeps over a 3D grid hierarchy (finest grid 512^3 for class C,
1024^3 for class D) solving a Poisson equation. Each sweep
streams through a few double-precision arrays - a 3.3 GiB working
set for class C, 26.4 GiB for class D - far beyond any LLC, with little reuse between sweeps: the kernel is memory-bandwidth-bound
by construction.
The per-run logs, the placement/migration/sweep traces, and the bpftrace scripts behind them are available if useful.
Regards,
Jirka Hladky
Red Hat
Quoted 57 lines · Peter Zijlstra
Quoted 6 lines · Yu C
Quoted 5 lines
This is pretty terrible. If you want LLC size, add it to the topology information (and ideally integrate with RDT) and make proportional to cpumask size, such that if someone cuts the domain in pieces, they get proportional size etc.
Quoted 6 lines
If I understand correctly, do you mean the following:
1.Introduce a generic
arch_get_llc_size()as a wrapper
around the existingget_cpu_cacheinfo_level(), which returns thellc_size. Both the scheduler and RDT can usearch_get_llc_size().The tie in with RDT was more to affect the return of
arch_get_llc_size(). Eg. when RDT takes away some ways for specific tasks, then the total effective size gets reduced for generic use.Quoted 4 lines
2. The sched domain stores
llc_sizeinsd->res_size=llc_size*sd_span/arch_llc_span, and thecache_aware_schedulerusessd->res_sizefor the comparison.Just so.
Quoted 1 line
We will adjust the code accordingly.
Thanks.
Quoted 6 lines
Quoted 5 lines
Also, if we have
NUMA_BALANCINGon, that can provide a much better estimate for the actual size.Just using RSS seems like a very bad metric here.
Quoted 8 lines
Got it. Currently we lack accurate memory footprint metrics in the kernel. If we support user-provided hints in the future, we can leverage RDT
llc_occupancymetrics(Is it legal to use RDT's metrics directly in the kernel? It would switch from MSR-read to MMIO read thus less overhead). For now, let me have a try how to leverage NUMA fault-in stats. If NUMA balancing is off, I need to think more on how to avoid over-aggregation for memory-intensive workloads.There is also things like this:
https://lkml.kernel.org/r/[email protected]
But yeah, in an ideal world we could be looking at LLC cache hit/miss information... streaming workloads would have very low hit rate.
But yes, possible
prctl()controls could help, create tools to disable things per program etc.
Signature · 1 line
-Jirka
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Quoted 4 lines · Jirka Hladky
Hi Peter, Chen Yu, Tim,
[snip]
Quoted 61 lines
THE FOOTPRINT ESTIMATE NEVER LEAVES ZERO (MG class D, 64 threads)
Traced live on the stock kernel with bpftrace (comm-filtered), across three CAS-on runs:-
grp->footprint: 0 in 44,670 and 40,638task_cache_work()samples over two full runs (min = max = 0), while ~7M pages (26.4 GiB) were resident. NUMA balancing was active: 8k-20k hint faults and up to 3.3M pages migrated per run.
- In those two runs the footprint write never executed: all ~8k-13ktask_numa_placement()calls per run (one per hint fault, viatask_numa_fault()) returned at thescan_seqgate.WHY THE SIGNAL NEVER ACCUMULATES
1.grp->footprintis only written intask_numa_placement(), which runs only whenmm->numa_scan_seqchanges. That counter increments only inreset_ptenuma_scan(): when the NUMA scanner has wrapped the whole address space.
2. The scanner walks the 26.4 GiB of mappings at ~0.3-1 GiB/s (traced viamm->numa_scan_offsetandchange_prot_numa()return values), so one sweep takes 30-40s or more. The 43s benchmark completed 0 sweeps in two runs, 1 sweep (at t=33s) in a third. The accounting runs at most once per task per run.
3. The signal is also small: a run accumulates only 8k-20k hint-fault events, 0.1-0.3% of the working set, below the 108 MiB threshold even when a sweep does complete.
4. And it is a rate signal, not a size: the increment is diff = numa_faults[MEMBUF] - numa_faults[MEM] / 2, which is zero at any steady fault rate.Cadence, coverage and formula each independently hold the footprint orders of magnitude below the resident set.
exceed_llc_capacity()is evaluated on every tick and every scan epoch, but with footprint at 0 the comparison
llc_bytes* scale < footprint *PAGE_SIZEis never true, so
grp->cpuis never reset. After a 1.8s warm-up it pointed at the same LLC for all 44,661 remaining samples.Without NUMA balancing the check never triggers, as
sched-cache.rstdocuments. With CAS on and numa_balancing=0 the same run takes 42.2s, the same as with NUMA balancing on (42.0s).WHAT THE AGGREGATION COSTS (MG class D, 64 threads)
- With CAS on, 97% of thread-samples are on one node. The 26.4 GiBworking set starts ~50/50 across the nodes and NUMA balancing then pulls it to the busy node (numa_maps 3.3M/2.7M pages -> 6.7M/0.2M; 1.42M pages migrated during the run).- The cost is not on the CPU side: average CPU utilization is essentially unchanged (6164% vs 6029% - about 61 of the 64 threads on-CPU in both configurations), and wakeup latency is 49us on average, 0.73ms max (perf sched). What grows is UserTime, +48%: the threads keep running, each operation just stalls longer on memory.
- The cost is the placement itself, not migration or remote accesses:
a) 32 threads: memory fully converges to the busy node well before the run ends, and the run is still 46% slower;
b) CAS on with numa_balancing=0: no migrations, pages stay
Quoted 9 lines
65/35, and the runtime is unchanged (42.2s);
c) CAS off with the process simply taskset-pinned to one socket (memory 100% local from first touch, no migrations): 40.3s, within the CAS-on range (40.6-42.9s).
64 memory-streaming threads on one socket get about two thirds of the throughput they get spread across both sockets (Mop/s -34%), wherever the pages live. So the only effective fix is to not aggregate such a process in the first place.
Thanks for your detailed analysis of the regression on NAS MG and its root cause. Much appreciated.
Quoted 5 lines
QUESTIONS
1. Was the sweep-boundary gating of this accounting known or intended? For a workload with a large address space it means the footprint sees at most one update per run; for a shorter one, none at all.
Not intended. Your reading of the code is right. The footprint is only written from task_numa_placement(), and that function returns early unless mm->numa_scan_seq has moved, which happens once per full sweep of the address space. The cadence is fine for NUMA placement. But it may be too long for large footprints. The tests we validated against had a small enough RSS that the first sweep finished within the first seconds of the run.
One correction to your point 3. numa_faults counts pages, not fault events. A THP hint fault adds HPAGE_PMD_NR (512) pages per fault. Your 3.3M migrated pages from 8k-20k faults suggests THP was in use. If so, one completed sweep would push the footprint to millions of pages, far above the 27.6k pages that equal a 108 MiB LLC. Two things would help confirm this:
- Was THP enabled for the MG run?
- In the third run, did grp->footprint become non-zero after the sweep completed at t=33s?
If both are yes, then sweep cadence is the problem and the size estimate is not.
Quoted 9 lines
2. Could the check fail closed when there is no usable estimate (warm-up, footprint still 0, NUMA balancing off)? RSS is a poor estimate of the working set, as Peter said, but it is an upper
bound: if RSS fits in the LLC, so does the working set. Using it only on the permit side - aggregate without a footprint estimate only if RSS fits - would keep the gains for small processes and not aggregate the ones we cannot judge. The costs are
asymmetric: a missed aggregation forfeits a gain, a wrong one cost 65% here.
I think you have a point. I see two ways to fix this issue, and they are complementary.
Fix 1:
- When footprint is 0, or NUMA balancing is off, compare the RSS of the mm against llc_bytes * scale. Aggregate only if RSS fits.
- Once a footprint estimate exists, use it as today.
RSS is not used as the estimate here, only as an upper bound while there is no footprint from the sweep. That is consistent with Peter's objection in April. It also closes the NUMA-balancing-off gap that sched-cache.rst documents.
The downside: a process with a large RSS but a small hot set will not be aggregated until an estimate exists, and with a very large RSS that can be the whole run. A process that runs for less than one sweep never gets an estimate at all.
Fix 2:
On the cadence side: accumulate the pages reported by task_numa_fault() into the footprint as they arrive within the current sweep, instead of waiting for task_numa_placement(). The footprint then grows during the first sweep and the check trips quickly for your MG run. At the sweep boundary task_numa_placement() only applies the decay of the previous window, so the steady state value is unchanged.
The downside: for a workload like yours there is still a short window where we aggregate before the footprint crosses the LLC size. With THP each hint fault adds 512 pages, so the 27.6k pages of a 108 MiB LLC are reached after about 54 faults. At the few hundred faults per second you measured that is under a second once scanning starts, and scanning starts after the 1s scan delay. That is about the 1.8s warm-up you saw before grp->cpu settled.
Fix 2 depends on NUMA balancing. Fix 1 also covers your numa_balancing=0 run.
I lean toward doing both: Fix 2 for the cadence, Fix 1 for NUMA balancing off and for the first sweep. Peter, is the RSS bound acceptable when it is used only as a gate and never as the estimate?
Quoted 6 lines
3. Our data supports Peter's point that LLC hit/miss information would be the better signal: the damage is purely memory-side (UserTime +59% at flat CPU% in the 112-thread run), and a memory-streaming process would show a low hit rate regardless of how well its footprint is estimated. Is anyone looking at that?
I am not aware of patches posted along these lines.
The two possible routes are RDT (CMT llc_occupancy and MBM bandwidth per RMID) and PMU miss counters. RDT needs an RMID per cache group, which resctrl owns. Mixing RMID management with scheduler will be tricky.
The scheduler does not own the PMU, so the PMU route is unlikely to be accepted. Near term the usable signals are the RSS bound above and user hints through prctl to enable/disable cache aware scheduling or modify tuning knobs per sched group.
Quoted 4 lines
4. Chen Yu mentioned that you are reworking the footprint accounting for the prctl v2 series [2]. Could the detection fix be part of that rework?
The v2 work on footprint is about correctness, not cadence.
Fix 2 I mentioned above touches the same footprint code that the v2 series reworks, so the two are not independent. I think we would consider whether to add the proposed fixes in the same series or leave it as a follow on.
Would you consider testing the patches when we post them? We will CC you.
Tim
Quoted 18 lines
[1] <50a8055e38958cdc39e07435aaad56e4719b2bd3.1794507151.git.tim.c.chen@linux.intel.com>
[2] <[email protected]>
[3] NAS Parallel Benchmarks: https://www.nas.nasa.gov/software/npb.html
MG is the multigrid kernel: four V-cycles of 27-point stencil
sweeps over a 3D grid hierarchy (finest grid 512^3 for class C,
1024^3 for class D) solving a Poisson equation. Each sweep
streams through a few double-precision arrays - a 3.3 GiB working
set for class C, 26.4 GiB for class D - far beyond any LLC, with little reuse between sweeps: the kernel is memory-bandwidth-bound
by construction.The per-run logs, the placement/migration/sweep traces, and the bpftrace scripts behind them are available if useful.
Regards,
Jirka Hladky
Red Hat
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Hi Tim,
Quoted 1 line
Was THP enabled for the MG run?
Yes, set to [always], and the MG working set is essentially entirely
THP-backed: AnonHugePages 27,738,112 kB of Rss 27,748,260 kB (99.96%), measured mid-run. That also explains a number we had not
reconciled: 3.3M pages migrated from ~20k hint faults (160:1) is only possible with 512-page faults.
Quoted 2 lines
In the third run, did
grp->footprintbecome non-zero after the sweep completed at t=33s?
I had not measured footprint in that run, so I re-ran the combined trace until a sweep completed (completion is stochastic on this
workload: 0 in three earlier 43-53s runs, 1 in a fourth, 1 in this one, at t=37.6s of 43s). The moment the scan sequence advanced, all 64 tasks ran task_numa_placement() within ~4 ms, each adding ~105k
pages: grp->footprint went 0 -> 111,785 -> 215,225 -> ... -> ~6.7M pages, i.e. about the full working set, crossing the 27.6k-page LLC threshold at the second placement. The aggregation was withdrawn for the remaining ~7 s of the run.
So: sweep cadence is the problem and the size estimate is not. Agreed. Our point 3 (0.1-0.3% coverage) was wrong in the THP
reading: the fault count is small but each fault carries 512 pages, and a completed sweep's estimate is accurate.
Quoted 3 lines
I lean toward doing both: Fix 2 for the cadence, Fix 1 for NUMA balancing off and for the first sweep. Peter, is the RSS bound acceptable when it is used only as a gate and never as the estimate?
Both fixes look right to us. Fix 2's predicted trip point matches our data nicely: 54 THP faults is well under a second of faulting once scanning starts, which lines up with the ~1.8 s warm-up we measured before grp->cpu settles. With Fix 2, the MG run would likely never aggregate at all. Fix 1 closing the NUMA-balancing-off gap is also what our numa_balancing=0 test argues for. From my side, the RSS-as-gate-only framing answers the April objection: it is never used as the estimate, only as the bound while no estimate exists.
Quoted 2 lines
Would you consider testing the patches when we post them? We will CC you.
Yes, absolutely! We would be glad to test them. Please count us in as early testers.
One data point for the validation matrix: nr_running_avg is a smoothed average (~89% of the busy threads in our MG runs), and the threshold is 80% of the LLC's CPUs (115 on this server), so around 128 busy threads it sits right on the line and aggregation becomes nondeterministic run to run. We need to keep test thread counts clear of that zone on large-LLC parts.
Thanks again,
Jirka
On Sat, Nov 14, 2026 at 12:07 AM Tim Chen <[email protected]> wrote:
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
In reply to Tim ChenHi Jirka, Tim,
Quoted 134 lines · Tim Chen
Quoted 4 lines · Jirka Hladky
Hi Peter, Chen Yu, Tim,
[snip]
Quoted 61 lines
THE FOOTPRINT ESTIMATE NEVER LEAVES ZERO (MG class D, 64 threads)
Traced live on the stock kernel with bpftrace (comm-filtered), across three CAS-on runs:-
grp->footprint: 0 in 44,670 and 40,638task_cache_work()samples over two full runs (min = max = 0), while ~7M pages (26.4 GiB) were resident. NUMA balancing was active: 8k-20k hint faults and up to 3.3M pages migrated per run.
- In those two runs the footprint write never executed: all ~8k-13ktask_numa_placement()calls per run (one per hint fault, viatask_numa_fault()) returned at thescan_seqgate.WHY THE SIGNAL NEVER ACCUMULATES
1.grp->footprintis only written intask_numa_placement(), which runs only whenmm->numa_scan_seqchanges. That counter increments only inreset_ptenuma_scan(): when the NUMA scanner has wrapped the whole address space.
2. The scanner walks the 26.4 GiB of mappings at ~0.3-1 GiB/s (traced viamm->numa_scan_offsetandchange_prot_numa()return values), so one sweep takes 30-40s or more. The 43s benchmark completed 0 sweeps in two runs, 1 sweep (at t=33s) in a third. The accounting runs at most once per task per run.
3. The signal is also small: a run accumulates only 8k-20k hint-fault events, 0.1-0.3% of the working set, below the 108 MiB threshold even when a sweep does complete.
4. And it is a rate signal, not a size: the increment is diff = numa_faults[MEMBUF] - numa_faults[MEM] / 2, which is zero at any steady fault rate.Cadence, coverage and formula each independently hold the footprint orders of magnitude below the resident set.
exceed_llc_capacity()is evaluated on every tick and every scan epoch, but with footprint at 0 the comparison
llc_bytes* scale < footprint *PAGE_SIZEis never true, so
grp->cpuis never reset. After a 1.8s warm-up it pointed at the same LLC for all 44,661 remaining samples.Without NUMA balancing the check never triggers, as
sched-cache.rstdocuments. With CAS on and numa_balancing=0 the same run takes 42.2s, the same as with NUMA balancing on (42.0s).WHAT THE AGGREGATION COSTS (MG class D, 64 threads)
- With CAS on, 97% of thread-samples are on one node. The 26.4 GiBworking set starts ~50/50 across the nodes and NUMA balancing then pulls it to the busy node (numa_maps 3.3M/2.7M pages -> 6.7M/0.2M; 1.42M pages migrated during the run).- The cost is not on the CPU side: average CPU utilization is essentially unchanged (6164% vs 6029% - about 61 of the 64 threads on-CPU in both configurations), and wakeup latency is 49us on average, 0.73ms max (perf sched). What grows is UserTime, +48%: the threads keep running, each operation just stalls longer on memory.
- The cost is the placement itself, not migration or remote accesses:
a) 32 threads: memory fully converges to the busy node well before the run ends, and the run is still 46% slower;
b) CAS on with numa_balancing=0: no migrations, pages stayQuoted 9 lines
65/35, and the runtime is unchanged (42.2s);
c) CAS off with the process simply taskset-pinned to one socket (memory 100% local from first touch, no migrations): 40.3s, within the CAS-on range (40.6-42.9s).
64 memory-streaming threads on one socket get about two thirds of the throughput they get spread across both sockets (Mop/s -34%), wherever the pages live. So the only effective fix is to not aggregate such a process in the first place.Thanks for your detailed analysis of the regression on NAS MG and its root cause. Much appreciated.
Quoted 5 lines
QUESTIONS
1. Was the sweep-boundary gating of this accounting known or intended? For a workload with a large address space it means the footprint sees at most one update per run; for a shorter one, none at all.Not intended. Your reading of the code is right. The footprint is only written from
task_numa_placement(), and that function returns early unlessmm->numa_scan_seqhas moved, which happens once per full sweep of the address space. The cadence is fine for NUMA placement. But it may be too long for large footprints. The tests we validated against had a small enough RSS that the first sweep finished within the first seconds of the run.One correction to your point 3.
numa_faultscounts pages, not fault events. A THP hint fault addsHPAGE_PMD_NR(512) pages per fault. Your 3.3M migrated pages from 8k-20k faults suggests THP was in use. If so, one completed sweep would push the footprint to millions of pages, far above the 27.6k pages that equal a 108 MiB LLC. Two things would help confirm this:- Was THP enabled for the MG run?
- In the third run, didgrp->footprintbecome non-zero after the sweep completed at t=33s?If both are yes, then sweep cadence is the problem and the size estimate is not.
Quoted 9 lines
2. Could the check fail closed when there is no usable estimate (warm-up, footprint still 0, NUMA balancing off)? RSS is a poor estimate of the working set, as Peter said, but it is an upper
bound: if RSS fits in the LLC, so does the working set. Using it only on the permit side - aggregate without a footprint estimate only if RSS fits - would keep the gains for small processes and not aggregate the ones we cannot judge. The costs are
asymmetric: a missed aggregation forfeits a gain, a wrong one cost 65% here.I think you have a point. I see two ways to fix this issue, and they are complementary.
Fix 1:
- When footprint is 0, or NUMA balancing is off, compare the RSS of the mm against
llc_bytes* scale. Aggregate only if RSS fits.
- Once a footprint estimate exists, use it as today.RSS is not used as the estimate here, only as an upper bound while there is no footprint from the sweep. That is consistent with Peter's objection in April. It also closes the NUMA-balancing-off gap that
sched-cache.rstdocuments.
Quoted 5 lines
The downside: a process with a large RSS but a small hot set will not be aggregated until an estimate exists, and with a very large RSS that can be the whole run. A process that runs for less than one sweep never gets an estimate at all.
In the original patch that leverages RSS[1], it uses the per-mm RSS:get_mm_counter(mm, MM_ANONPAGES) + get_mm_counter(mm, MM_SHMEMPAGES). In, the future we do not want cache-aware scheduling to be tied to mm_struct, it will be turned into per-sched_cache_group, and we might need to support per-sched_cache_group RSS.
Quoted 5 lines
Fix 2:
On the cadence side: accumulate the pages reported by
task_numa_fault()into the footprint as they arrive within the current sweep, instead of waiting fortask_numa_placement().
Do you mean accumulate the pages into the group in task_numa_fault()? As we are trying to convert the footprint into atomic[2], this might increase the overhead since multiple threads write this counter in parallel. A workaround is to accumulate the pages every N pages into the group to mitigate the overhead.
Quoted 3 lines
The footprint then grows during the first sweep and the check trips quickly for your MG run. At the sweep boundary
task_numa_placement()only applies the decay of the previous window,
Would this decay cause a jitter of the footprint? Anyway, I thought what you suggested is the following for fix2(although this version racy with concurrent updates from other threads sharing this mm). BTW, with this mechanism, I don't think we need to subtract the footprint during exit() or exec(), because the footprint will decay gradually?
[1] https://lore.kernel.org/all/339bb2636c7306e17540268a9295a8e673b92804.1775065312.git.tim.c.chen@linux.intel.com/
[2] https://lore.kernel.org/all/[email protected]/
thanks,
Chenyu
include/linux/sched.h +1 -0
@@ -1444,6 +1444,7 @@ struct task_struct {int preferred_llc;/* 1: task was enqueued to its preferred LLC, 0 otherwise */ int pref_llc_queued; +unsigned long total_footprint;#endif struct rseq_data rseq;
init/init_task.c +1 -0
@@ -231,6 +231,7 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = {#ifdef CONFIG_SCHED_CACHE .preferred_llc = -1, .pref_llc_queued =0 , + .total_footprint = 0;#endif #if defined(CONFIG_KASAN_GENERIC ) || defined(CONFIG_KASAN_SW_TAGS ) .kasan_depth = 1,
kernel/sched/fair.c +40 -43
119 lines not on this page · raw message
Signature · 1 line
2.43.0
Quoted 73 lines
so the steady state
value is unchanged.The downside: for a workload like yours there is still a short window where we aggregate before the footprint crosses the LLC size. With THP each hint fault adds 512 pages, so the 27.6k pages of a 108 MiB LLC are reached after about 54 faults. At the few hundred faults per second you measured that is under a second once scanning starts, and scanning starts after the 1s scan delay. That is about the 1.8s warm-up you saw before
grp->cpusettled.Fix 2 depends on NUMA balancing. Fix 1 also covers your numa_balancing=0 run.
I lean toward doing both: Fix 2 for the cadence, Fix 1 for NUMA balancing off and for the first sweep. Peter, is the RSS bound acceptable when it is used only as a gate and never as the estimate?
Quoted 6 lines
3. Our data supports Peter's point that LLC hit/miss information would be the better signal: the damage is purely memory-side (UserTime +59% at flat CPU% in the 112-thread run), and a memory-streaming process would show a low hit rate regardless of how well its footprint is estimated. Is anyone looking at that?
I am not aware of patches posted along these lines.
The two possible routes are RDT (CMT
llc_occupancyand MBM bandwidth per RMID) and PMU miss counters. RDT needs an RMID per cache group, which resctrl owns. Mixing RMID management with scheduler will be tricky.The scheduler does not own the PMU, so the PMU route is unlikely to be accepted. Near term the usable signals are the RSS bound above and user hints through prctl to enable/disable cache aware scheduling or modify tuning knobs per sched group.
Quoted 4 lines
4. Chen Yu mentioned that you are reworking the footprint accounting for the prctl v2 series [2]. Could the detection fix be part of that rework?
The v2 work on footprint is about correctness, not cadence.
Fix 2 I mentioned above touches the same footprint code that the v2 series reworks, so the two are not independent. I think we would consider whether to add the proposed fixes in the same series or leave it as a follow on.
Would you consider testing the patches when we post them? We will CC you.
Tim
Quoted 18 lines
[1] <50a8055e38958cdc39e07435aaad56e4719b2bd3.1794507151.git.tim.c.chen@linux.intel.com>
[2] <[email protected]>
[3] NAS Parallel Benchmarks: https://www.nas.nasa.gov/software/npb.html
MG is the multigrid kernel: four V-cycles of 27-point stencil
sweeps over a 3D grid hierarchy (finest grid 512^3 for class C,
1024^3 for class D) solving a Poisson equation. Each sweep
streams through a few double-precision arrays - a 3.3 GiB working
set for class C, 26.4 GiB for class D - far beyond any LLC, with little reuse between sweeps: the kernel is memory-bandwidth-bound
by construction.The per-run logs, the placement/migration/sweep traces, and the bpftrace scripts behind them are available if useful.
Regards,
Jirka Hladky
Red Hat
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Hi Chen Yu, Tim,
Quoted 4 lines
Do you mean accumulate the pages into the group in
task_numa_fault()?
...
Would this decay cause a jitter of the footprint? Anyway, I thought what you suggested is the following for fix2 ...
I built and tested the sketch on the Sierra Forest box: a kernel built from the same 7.4.0-0.rc2.19.eln159 source as my baselines, patched with your sketch plus the fixes needed to compile it, and with one
change: the decay is applied once per group per sweep via a last_decay_seq stamp, since decaying per task would halve the group footprint once per thread per sweep.
The accounting mechanism works exactly as designed:
- The footprint accumulates during the sweep and crosses the 27,648-page LLC threshold at t=4.4 s; the aggregation is withdrawn and stays withdrawn (grp->cpu = -1 in 96% of 27,796 samples). To answer the jitter question: with once-per-sweep decay I saw no oscillation in a run whose footprint reached ~3.95M pages.
- Removing the exit()/exec() subtraction held up fine as well.
But the regression is not fixed. NAS MG class D, 1x64 threads, n=5, median time:
stock rc2.19, CAS off 26.45 s
stock rc2.19, CAS on 41.78 s (+58%)
sketch, CAS off 26.57 s
sketch, CAS on 39.19 s (+47.5%)The regression drops from +58% to +47.5%: 2.6 s of the 15.3 s gap, about one sixth, and the reason is placement hysteresis. The 2.1 s window between the aggregation settling
and the gate tripping has already shaped the run: the threads re-spread at only ~1 thread per second (4/60 across the two nodes at t=5 s, 20/44 at t=28 s), and the memory first-touched during the window is 59/41 toward the aggregated node, with NUMA balancing then pulling even more memory there as the run continues. Withdrawing grp->cpu stops the steering but does not undo the placement, the fault statistics, or the page layout.
A few observations for the design:
1. Fix 1 (the RSS gate) looks critical for this workload class. MG's RSS crosses the 108 MiB LLC size within ~0.1 s of the allocation phase, so an RSS gate would refuse aggregation almost immediately, before first-touch lays down the skewed layout.
2. Fix 2's trip time is bounded below by the scanner, not by the fault
count: the 4.4 s crossing decomposes into the 1 s scan delay plus the 2-3 s the scanner needs to reach the large VMAs of a 26.4 GiB address space. Even the theoretical ~1.8 s would arrive after ~60% of the working set is first-touched.
3. One caveat on the withdrawal path, shared by both fixes: whenever the gate trips after aggregation has been in effect, passive withdrawal (clearing grp->cpu) recovers almost nothing on this workload; the tasks re-spread at ~1 per second. An effective withdrawal would need to actively re-spread the tasks or reset their NUMA preferences. With Fix 1 in place this matters less for the regression class I reported, since aggregation is refused before it settles; it applies to workloads that grow past the LLC mid-run.
Happy to re-test when the next revision is posted. The exact version I tested, on top of your sketch with the changes above, is below. The diff is against v7.4-rc2; the hunks are in code my downstream patchset does not touch, so it should apply to your tree as well.
Thanks,
Jirka
On Mon, Nov 16, 2026 at 6:45 AM Chen Yu <[email protected]> wrote:
---
include/linux/sched.h +2 -0
@@ -1446,6 +1446,7 @@int preferred_llc;/* 1: task was enqueued to its preferred LLC, 0 otherwise */ int pref_llc_queued; +unsigned long total_footprint;#endif struct rseq_data rseq;
@@ -2396,6 +2397,7 @@u64 nr_running_avg;unsigned long next_scan;unsigned long footprint; +unsigned long last_decay_seq;int cpu;refcount_t refcnt;struct rcu_head rcu;
kernel/sched/fair.c +55 -13
89 lines not on this page · raw message
int pages) { }
+static inline void sched_cache_footprint_decay(struct task_struct *p) { } +#endif
+
static void task_numa_placement(struct task_struct *p)
__context_unsafe(/* conditional locking */)
{
@@ -3911,36 +3956,6 @@
ng->total_faults += diff;
group_faults += ng->faults[mem_idx];
}
-#ifdef CONFIG_SCHED_CACHE
- /*
- * Per task p->numa_faults[mem_idx] converges,
- * so the accumulation of each task's faults
- * converges too - Given the number of threads,
- * it cannot overflow an unsigned long.
- * Racy with concurrent updates from other threads
- * sharing this mm. Acceptable since footprint is a
- * heuristic and occasional lost updates are tolerable.
- *
- * If a task exits, its corresponding footprint must
- * be subtracted from p->sched_cache_grp->footprint,
- * otherwise the footprint will not converge: the
- * exiting thread's footprint remains unchanged/undecayed.
- * See exit_mm().
- *
- * Lost updates and unsynchronized subtraction
- * in exit_mm() can cause footprint + diff to
- * go negative. Clamp to zero to prevent the
- * unsigned footprint from wrapping.
- */
- scoped_guard(rcu) {
- grp = rcu_dereference(p->sched_cache_grp);
-
- if (grp) {
- new_fp = (long)READ_ONCE(grp->footprint) + diff;
- WRITE_ONCE(grp->footprint, max(new_fp, 0L));
- }
- }
-#endif
}
if (!ng) {
@@ -3970,6 +3985,7 @@
}
update_task_scan_period(p, fault_types[0], fault_types[1]);
+ sched_cache_footprint_decay(p);
}
static inline int get_numa_group(struct numa_group *grp)
@@ -4210,6 +4226,7 @@
p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages; p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages; p->numa_faults_locality[local] += pages;
+ sched_cache_footprint_accum(p, pages);
}
static void reset_ptenuma_scan(struct task_struct *p)
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
On Mon, 2026-11-16 at 15:35 +0100, Jirka Hladky wrote:
Hi Jirka,
Thanks for testing Chen Yu's sketch patch so quickly.
Quoted 31 lines
Hi Chen Yu, Tim,
Quoted 4 lines
Do you mean accumulate the pages into the group in
task_numa_fault()?
...
Would this decay cause a jitter of the footprint? Anyway, I thought what you suggested is the following for fix2 ...I built and tested the sketch on the Sierra Forest box: a kernel built from the same 7.4.0-0.rc2.19.eln159 source as my baselines, patched with your sketch plus the fixes needed to compile it, and with one
change: the decay is applied once per group per sweep via alast_decay_seqstamp, since decaying per task would halve the group footprint once per thread per sweep.The accounting mechanism works exactly as designed:
- The footprint accumulates during the sweep and crosses the 27,648-page LLC threshold at t=4.4 s; the aggregation is withdrawn and stays withdrawn (
grp->cpu= -1 in 96% of 27,796 samples). To answer the jitter question: with once-per-sweep decay I saw no oscillation in a run whose footprint reached ~3.95M pages.
- Removing the exit()/exec() subtraction held up fine as well.But the regression is not fixed. NAS MG class D, 1x64 threads, n=5, median time:
stock rc2.19, CAS off 26.45 s stock rc2.19, CAS on 41.78 s (+58%) sketch, CAS off 26.57 s sketch, CAS on 39.19 s (+47.5%)
Quoted 10 lines
The regression drops from +58% to +47.5%: 2.6 s of the 15.3 s gap, about one sixth, and the reason is placement hysteresis. The 2.1 s window between the aggregation settling
and the gate tripping has already shaped the run: the threads re-spread at only ~1 thread per second (4/60 across the two nodes at t=5 s, 20/44 at t=28 s), and the memory first-touched during the window is 59/41 toward the aggregated node, with NUMA balancing then pulling even more memory there as the run continues. Withdrawinggrp->cpustops the steering but does not undo the placement, the fault statistics, or the page layout.
It does seem like the hysteresis is too strong, and takes too long to even out on the MG workload.
Quoted 8 lines
A few observations for the design:
1. Fix 1 (the RSS gate) looks critical for this workload class. MG's RSS crosses the 108 MiB LLC size within ~0.1 s of the allocation phase, so an RSS gate would refuse aggregation almost immediately, before first-touch lays down the skewed layout.
Yeah, perhaps some form of Fix 1 is needed. However fix 1 benefits mostly workload where aggregation is unhelpful.
There is a downside for Fix 1 for processes that actually benefit from aggregation.
RSS gate is an upper bound on the cache footprint for the default case where cache group is a process. It tends to over estimate and it will take several scan windows to shed its effect and we could miss aggregation in the mean time.
Chen Yu, on your point that a cache group will no longer be one mm and that we have no per-group RSS: I do not think we need one. I think mm's RSS serves more as a bound of the footprint when we are just starting our scan. For a group spanning several processes we can use the largest member, which still refuses when any one member cannot fit. It is just an initial value that will get decayed away.
One more thing about the decay, mostly for Chen Yu. The once-per-group version halves the whole footprint, including the sweep that just closed. The NUMA fault statistics do not: per node they compute mem = mem / 2 + membuf, so the new window is added in full and only the history is halved. With B pages per sweep the two settle at 2B and B respectively depending on your sample time.
A group whose per sweep footprint sits between
one and two LLC sizes would flip in and out of aggregation at every sweep with the current form.
I have a small patch on top of Chen Yu's patch to mitigate this issue. It keeps a count in the scan window and a history count, and combine the two when sampled to smooth out any jump.
I also generated another test patch on top to test the RSS gate idea.
Quoted 6 lines
2. Fix 2's trip time is bounded below by the scanner, not by the fault
count: the 4.4 s crossing decomposes into the 1 s scan delay plus the 2-3 s the scanner needs to reach the large VMAs of a 26.4 GiB address space. Even the theoretical ~1.8 s would arrive after ~60% of the working set is first-touched.
Quoted 9 lines
3. One caveat on the withdrawal path, shared by both fixes: whenever the gate trips after aggregation has been in effect, passive withdrawal (clearing
grp->cpu) recovers almost nothing on this workload; the tasks re-spread at ~1 per second. An effective withdrawal would need to actively re-spread the tasks or reset their NUMA preferences. With Fix 1 in place this matters less for the regression class I reported, since aggregation is refused before it settles; it applies to workloads that grow past the LLC mid-run.
This is a good find and I think it deserves its own thread. One
suspect: while the threads were aggregated, NUMA balancing moved their pages to that node, so numa_preferred_nid points there. After grp->cpu is cleared the load balancer can move a thread out, but numa_migrate_preferred() pulls it back toward its pages. On a system where the LLC is the node, the two mechanisms reinforce each other.
Wonder if NUMA balancing is preventing the re-spread?
If your traces have numa_preferred_nid and task_numa_migrate activity after the trip, that would confirm or rule it out.
Quoted 9 lines
Happy to re-test when the next revision is posted. The exact version I tested, on top of your sketch with the changes above, is below. The diff is against v7.4-rc2; the hunks are in code my downstream patchset does not touch, so it should apply to your tree as well.
Thanks,
Jirka
Two patches on top of Chen Yu's sketch patch below. Thanks.
Tim
--->8----
From: Tim Chen <[email protected]>
Subject: [PATCH 1/2] sched/cache: Keep the footprint flat across sweep
boundaries
include/linux/sched.h +8 -0
@@ -2392,7 +2392,15 @@ struct sched_cache_group {unsigned long epoch;u64 nr_running_avg;unsigned long next_scan; +/* +* Footprint estimate in pages. footprint is the decayed history of +* the completed scan sweeps, written by one task per sweep. +* footprint_cur collects the hint faults of the current sweep from +* all tasks. The estimate is max(footprint, footprint / 2 + +* footprint_cur), see sched_cache_footprint_decay(). +*/ unsigned long footprint; +atomic_long_t footprint_cur;unsigned long last_decay_seq;int cpu;refcount_t refcnt;
kernel/sched/fair.c +57 -23
137 lines not on this page · raw message
Signature · 20 lines
From: Tim Chen <[email protected]> Date: Mon, 16 Nov 2026 14:05:45 -0800 Subject: [PATCH 2/2] sched/cache: Use the RSS as an upper bound while there is no footprint The footprint check of exceed_llc_capacity() needs NUMA balancing hint faults. Until the first scan sweep of the address space completes there is no estimate, and without NUMA balancing there never is one. In both cases the check passes and a process of any size can be aggregated. Use the RSS of the mm as the footprint while there is no estimate. The RSS is a poor estimate of the working set, but it is an upper bound: if the RSS fits in the LLC, so does the working set. If it does not fit, we cannot tell, and refuse to aggregate. Not-yet-signed-off-by: Tim Chen <[email protected]> --- include/linux/sched.h | 6 +++ kernel/sched/fair.c | 95 ++++++++++++++++++++++++++++--------------- 2 files changed, 68 insertions(+), 33 deletions(-)
include/linux/sched.h +6 -0
@@ -2402,6 +2402,12 @@ struct sched_cache_group {unsigned long footprint;atomic_long_t footprint_cur;unsigned long last_decay_seq; +/* +* RSS of the mm of the last task that scanned for the group, in +* pages. An upper bound of the working set, used while there is no +* footprint estimate yet. See exceed_llc_capacity(). +*/ +unsigned long rss_bound;int cpu;refcount_t refcnt;struct rcu_head rcu;
kernel/sched/fair.c +62 -33
128 lines not on this page · raw message
Signature · 1 line
2.53.0
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Hi Tim, Jirka,
Quoted 49 lines · Tim Chen
On Mon, 2026-11-16 at 15:35 +0100, Jirka Hladky wrote:
Hi Jirka,
Thanks for testing Chen Yu's sketch patch so quickly.
Quoted 31 lines
Hi Chen Yu, Tim,
Quoted 4 lines
Do you mean accumulate the pages into the group in
task_numa_fault()?
...
Would this decay cause a jitter of the footprint? Anyway, I thought what you suggested is the following for fix2 ...I built and tested the sketch on the Sierra Forest box: a kernel built from the same 7.4.0-0.rc2.19.eln159 source as my baselines, patched with your sketch plus the fixes needed to compile it, and with one
change: the decay is applied once per group per sweep via alast_decay_seqstamp, since decaying per task would halve the group footprint once per thread per sweep.The accounting mechanism works exactly as designed:
- The footprint accumulates during the sweep and crosses the 27,648-page LLC threshold at t=4.4 s; the aggregation is withdrawn and stays withdrawn (
grp->cpu= -1 in 96% of 27,796 samples). To answer the jitter question: with once-per-sweep decay I saw no oscillation in a run whose footprint reached ~3.95M pages.
- Removing the exit()/exec() subtraction held up fine as well.But the regression is not fixed. NAS MG class D, 1x64 threads, n=5, median time:
stock rc2.19, CAS off 26.45 s stock rc2.19, CAS on 41.78 s (+58%) sketch, CAS off 26.57 s sketch, CAS on 39.19 s (+47.5%)Quoted 10 lines
The regression drops from +58% to +47.5%: 2.6 s of the 15.3 s gap, about one sixth, and the reason is placement hysteresis. The 2.1 s window between the aggregation settling
and the gate tripping has already shaped the run: the threads re-spread at only ~1 thread per second (4/60 across the two nodes at t=5 s, 20/44 at t=28 s), and the memory first-touched during the window is 59/41 toward the aggregated node, with NUMA balancing then pulling even more memory there as the run continues. Withdrawinggrp->cpustops the steering but does not undo the placement, the fault statistics, or the page layout.
Quoted 3 lines
It does seem like the hysteresis is too strong, and takes too long to even out on the MG workload.
Agreed, it seems that the window before the first full-scan round is still noticeable for MG.
Quoted 20 lines
Quoted 8 lines
A few observations for the design:
1. Fix 1 (the RSS gate) looks critical for this workload class. MG's RSS crosses the 108 MiB LLC size within ~0.1 s of the allocation phase, so an RSS gate would refuse aggregation almost immediately, before first-touch lays down the skewed layout.
Yeah, perhaps some form of Fix 1 is needed. However fix 1 benefits mostly workload where aggregation is unhelpful.
There is a downside for Fix 1 for processes that actually benefit from aggregation.
RSS gate is an upper bound on the cache footprint for the default case where cache group is a process. It tends to over estimate and it will take several scan windows to shed its effect and we could miss aggregation in the mean time.
Quoted 7 lines
Chen Yu, on your point that a cache group will no longer be one mm and that we have no per-group RSS: I do not think we need one. I think mm's RSS serves more as a bound of the footprint when we are just starting our scan. For a group spanning several processes we can use the largest member, which still refuses when any one member cannot fit. It is just an initial value that will get decayed away.
OK, this makes sense.
Quoted 7 lines
One more thing about the decay, mostly for Chen Yu. The once-per-group version halves the whole footprint, including the sweep that just closed. The NUMA fault statistics do not: per node they compute mem = mem / 2 + membuf, so the new window is added in full and only the history is halved. With B pages per sweep the two settle at 2B and B respectively depending on your sample time.
OK - mem = mem / 2 + membuf can be used to keep it consistent with the current NUMA balancing fault statistic. Although I'm not sure why the original NUMA balancing code uses this strategy, normally, for an EWMA, it should be
mem = p * mem + (1 - p) * membuf, where p is in (0, 1).
Quoted 33 lines
A group whose per sweep footprint sits between
one and two LLC sizes would flip in and out of aggregation at every sweep with the current form.I have a small patch on top of Chen Yu's patch to mitigate this issue. It keeps a count in the scan window and a history count, and combine the two when sampled to smooth out any jump.
I also generated another test patch on top to test the RSS gate idea.
Quoted 6 lines
2. Fix 2's trip time is bounded below by the scanner, not by the fault
count: the 4.4 s crossing decomposes into the 1 s scan delay plus the 2-3 s the scanner needs to reach the large VMAs of a 26.4 GiB address space. Even the theoretical ~1.8 s would arrive after ~60% of the working set is first-touched.Quoted 9 lines
3. One caveat on the withdrawal path, shared by both fixes: whenever the gate trips after aggregation has been in effect, passive withdrawal (clearing
grp->cpu) recovers almost nothing on this workload; the tasks re-spread at ~1 per second. An effective withdrawal would need to actively re-spread the tasks or reset their NUMA preferences. With Fix 1 in place this matters less for the regression class I reported, since aggregation is refused before it settles; it applies to workloads that grow past the LLC mid-run.This is a good find and I think it deserves its own thread. One
suspect: while the threads were aggregated, NUMA balancing moved their pages to that node, sonuma_preferred_nidpoints there. Aftergrp->cpuis cleared the load balancer can move a thread out, butnuma_migrate_preferred()pulls it back toward its pages. On a system where the LLC is the node, the two mechanisms reinforce each other.
Quoted 5 lines
Wonder if NUMA balancing is preventing the re-spread?
If your traces havenuma_preferred_nidandtask_numa_migrateactivity after the trip, that would confirm or rule it out.
This seems to be another issue of NUMA balancing fighting with generic load balancing, independent of the current footprint issue.
Quoted 155 lines
Quoted 9 lines
Happy to re-test when the next revision is posted. The exact version I tested, on top of your sketch with the changes above, is below. The diff is against v7.4-rc2; the hunks are in code my downstream patchset does not touch, so it should apply to your tree as well.
Thanks,
JirkaTwo patches on top of Chen Yu's sketch patch below. Thanks.
Tim
--->8----
From: Tim Chen <[email protected]>
Subject: [PATCH 1/2] sched/cache: Keep the footprint flat across sweep
boundariesinclude/linux/sched.h +8
-0@@ -2392,7 +2392,15 @@ struct sched_cache_group {unsigned long epoch;u64 nr_running_avg;unsigned long next_scan; +/* +* Footprint estimate in pages. footprint is the decayed history of +* the completed scan sweeps, written by one task per sweep. +* footprint_cur collects the hint faults of the current sweep from +* all tasks. The estimate is max(footprint, footprint / 2 + +* footprint_cur), see sched_cache_footprint_decay(). +*/ unsigned long footprint; +atomic_long_t footprint_cur;unsigned long last_decay_seq;int cpu;refcount_t refcnt;kernel/sched/fair.c +45
-21@@ -1424,7 +1424,7 @@ static inline int get_sched_cache_scale(int mul)static bool exceed_llc_capacity (struct sched_cache_group *grp,int cpu) {#ifdef CONFIG_NUMA_BALANCING -unsigned long llc, footprint; +unsigned long llc, footprint, hist, cur;struct sched_domain *sd;int scale;@@ -1440,7 +1440,14 @@ static bool exceed_llc_capacity(struct sched_cache_group *grp, int cpu)* excluded. */ llc = sd->llc_bytes; - footprint =READ_ONCE (grp->footprint); +/* +* The history, or what it becomes at the next sweep +* boundary if no more faults arrive, whichever is larger. +* See sched_cache_footprint_decay(). +*/ + hist =READ_ONCE (grp->footprint); + cur =atomic_long_read (&grp->footprint_cur); + footprint =max (hist, hist /2 + cur);/* * Scale the LLC size by 256*llc_aggr_tolerance @@ -1621,6 +1628,7 @@ int mm_init_sched(struct mm_struct *mm, grp->next_scan = jiffies; grp->nr_running_avg =0 ; grp->footprint =0 ; +atomic_long_set (&grp->footprint_cur,0 ); grp->last_decay_seq =0 ;refcount_set (&grp->refcnt,1 );/* @@ -3817,42 +3825,58 @@ static int preferred_group_nid(struct task_struct *p, int nid)#if defined(CONFIG_SCHED_CACHE ) && defined(CONFIG_NUMA_BALANCING )/* -* Fix 2 (Chen Yu sketch, test build): accumulate the pages reported by -* task_numa_fault() into the group footprint as they arrive within the -* current sweep, instead of waiting for task_numa_placement() at the sweep -* boundary. Batched per task to limit writes to the shared counter. +* Accumulate the pages reported by task_numa_fault() into the footprint of +* the current sweep as they arrive, instead of waiting for +* task_numa_placement() at the sweep boundary. A sweep of a large address +* space can take longer than the workload runs. +* +* The pages are batched per task before they are added to the shared +* counter. One THP hint fault reports HPAGE_PMD_NR pages, so the batch is +* one THP, or 512 base pages. task_numa_placement() flushes the batch +* once per sweep, so pages below the threshold are missing from the +* window for at most the sweep in progress. */ -#define SCHED_CACHE_FP_THRESHOLD 10 -static void sched_cache_footprint_accum (struct task_struct *p,int pages) +#define SCHED_CACHE_FP_THRESHOLD 512 +static void sched_cache_footprint_flush (struct task_struct *p) {struct sched_cache_group *grp; - p->total_footprint += pages; - -if (p->total_footprint <SCHED_CACHE_FP_THRESHOLD ) +if (!p->total_footprint)return ;guard (rcu)(); grp =rcu_dereference (p->sched_cache_grp); -if (!grp) -return ; - -/* drain the per-task footprint into the group */ -WRITE_ONCE (grp->footprint,READ_ONCE (grp->footprint) + p->total_footprint); +if (grp) +atomic_long_add (p->total_footprint, &grp->footprint_cur); p->total_footprint =0 ; } +static void sched_cache_footprint_accum (struct task_struct *p,int pages) +{ + p->total_footprint += pages; + +if (p->total_footprint >=SCHED_CACHE_FP_THRESHOLD ) +sched_cache_footprint_flush (p); +} +/* -* Decay once per group per sweep: the first task whose placement() observes -* a new scan sequence halves the accumulated window. (Decaying per task, as -* in the original sketch, would halve the group footprint once per thread -* per sweep.) +* Close the window at the sweep boundary, once per group per sweep: the +* first task whose task_numa_placement() observes a new scan sequence +* folds the current window into the history. +* +* Only the history is decayed. The window that just closed is added in +* full, like the per node update of the NUMA fault statistics: +* +* mem = mem / 2 + membuf +* +* With B pages touched per sweep the history settles at 2B, the value +* the fault statistics report. */ static void sched_cache_footprint_decay (struct task_struct *p) {struct sched_cache_group *grp;unsigned long seq = p->numa_scan_seq; -unsigned long old; +unsigned long old, cur;guard (rcu)(); grp =rcu_dereference (p->sched_cache_grp);
kernel/sched/fair.c static void sched_cache_footprint_decay(struct task_struct *p) · line 3890
Quoted 7 lines
kernel/sched/fair.c +2
-2@@ -3862,12 +3886,16 @@ static void sched_cache_footprint_decay(struct task_struct *p) old =READ_ONCE (grp->last_decay_seq);if (old == seq)return ; -if (cmpxchg (&grp->last_decay_seq, old, seq) == old) -WRITE_ONCE (grp->footprint,READ_ONCE (grp->footprint) /2 ); +if (cmpxchg (&grp->last_decay_seq, old, seq) != old) +return ;
I'm not sure if we should introduce this per-group last_decay_seq. The grp->last_decay_seq is assigned the current p->numa_scan_seq, which is derived from p->mm->numa_scan_seq. In the current implementation, cache-aware scheduling is per-mm, so this is OK. But soon, after we introduce cross-process/mm cache-aware scheduling via prctl, assigning different mm->numa_scan_seq values to the shared grp->last_decay_seq might cause last_decay_seq to bounce between different mms' numa_scan_seq, which could decay the grp->footprint very fast.
That is to say, since we need a "global" sequence across different mm, can we use jiffies in task_cache_work() to decay the footprint periodically, rather than decay it in task_numa_placement()? Besides, task_numa_placement() might only be invoked after a full scan, and only if there are NUMA page faults. If we put the decay in task_cache_work(), only 1 task of the group is allowed to decay the footprint, and it might be more reliable to invoked? I wonder if the following method would work, similar to what your patch does for RSS gating(just compiled)?
include/linux/sched.h +2 -0
@@ -2394,6 +2394,8 @@ struct sched_cache_group {u64 nr_running_avg;unsigned long next_scan;unsigned long footprint; +atomic_long_t footprint_cur; +unsigned long footprint_timeout;int cpu;refcount_t refcnt;struct rcu_head rcu;
kernel/sched/fair.c +24 -47
131 lines not on this page · raw message
Signature · 1 line
2.43.0
Quoted 186 lines
kernel/sched/fair.c +10
-0+ + cur =atomic_long_xchg (&grp->footprint_cur,0 ); + WRITE_ONCE(grp->footprint, READ_ONCE(grp->footprint) / 2 + cur); }#else static inline void sched_cache_footprint_accum (struct task_struct *p,int pages) { } +static inline void sched_cache_footprint_flush (struct task_struct *p) { }static inline void sched_cache_footprint_decay (struct task_struct *p) { }#endif @@ -3985,6 +4013,12 @@ static void task_numa_placement(struct task_struct *p) }update_task_scan_period (p, fault_types[0 ], fault_types[1 ]); + +/* +* Once per sweep: add this task's pending pages to the window +* before the window may be closed below. +*/ +sched_cache_footprint_flush (p);sched_cache_footprint_decay (p); }Signature · 20 lines
From: Tim Chen <[email protected]> Date: Mon, 16 Nov 2026 14:05:45 -0800 Subject: [PATCH 2/2] sched/cache: Use the RSS as an upper bound while there is no footprint The footprint check of exceed_llc_capacity() needs NUMA balancing hint faults. Until the first scan sweep of the address space completes there is no estimate, and without NUMA balancing there never is one. In both cases the check passes and a process of any size can be aggregated. Use the RSS of the mm as the footprint while there is no estimate. The RSS is a poor estimate of the working set, but it is an upper bound: if the RSS fits in the LLC, so does the working set. If it does not fit, we cannot tell, and refuse to aggregate. Not-yet-signed-off-by: Tim Chen <[email protected]> --- include/linux/sched.h | 6 +++ kernel/sched/fair.c | 95 ++++++++++++++++++++++++++++--------------- 2 files changed, 68 insertions(+), 33 deletions(-)include/linux/sched.h +6
-0@@ -2402,6 +2402,12 @@ struct sched_cache_group {unsigned long footprint;atomic_long_t footprint_cur;unsigned long last_decay_seq; +/* +* RSS of the mm of the last task that scanned for the group, in +* pages. An upper bound of the working set, used while there is no +* footprint estimate yet. See exceed_llc_capacity(). +*/ +unsigned long rss_bound;int cpu;refcount_t refcnt;struct rcu_head rcu;kernel/sched/fair.c +54
-33@@ -1423,8 +1423,7 @@ static inline int get_sched_cache_scale(int mul)static bool exceed_llc_capacity (struct sched_cache_group *grp,int cpu) { -#ifdef CONFIG_NUMA_BALANCING -unsigned long llc, footprint, hist, cur; +unsigned long llc, footprint =0 ;struct sched_domain *sd;int scale;@@ -1434,46 +1433,67 @@ static bool exceed_llc_capacity(struct sched_cache_group *grp, int cpu)if (!sd)return true; +/* +* Scale the LLC size by 256*llc_aggr_tolerance +* and compare it to the task's footprint. +* +* Suppose the L3 size is 32MB. If the +* llc_aggr_tolerance is 1: +* When the footprint is larger than 32MB, the +* process is regarded as exceeding the LLC +* capacity. If the llc_aggr_tolerance is 99: +* When the footprint is larger than 784GB, the +* process is regarded as exceeding the LLC +* capacity: +* 784GB = (1 + (99 - 1) * 256) * 32MB +* If the llc_aggr_tolerance is 100: +* ignore the footprint and do the aggregation +* anyway. +*/ + scale =get_sched_cache_scale (256 ); +if (scale ==INT_MAX ) +return false; + +/* +* TBD: RDT exclusive LLC ways reserved should be +* excluded. +*/ + llc = sd->llc_bytes; + +#ifdef CONFIG_NUMA_BALANCING if (static_branch_likely (&sched_numa_balancing)) { -/* -* TBD: RDT exclusive LLC ways reserved should be -* excluded. -*/ - llc = sd->llc_bytes; +unsigned long hist, cur; +/* * The history, or what it becomes at the next sweep * boundary if no more faults arrive, whichever is larger. * See sched_cache_footprint_decay(). +* +* The history is 0 until the first scan sweep of the +* address space completes. Until then the window alone +* is not an estimate of the working set, only a lower +* bound of it, so fall back to the RSS bound below. */ hist =READ_ONCE (grp->footprint); - cur =atomic_long_read (&grp->footprint_cur); - footprint =max (hist, hist /2 + cur); - -/* -* Scale the LLC size by 256*llc_aggr_tolerance -* and compare it to the task's footprint. -* -* Suppose the L3 size is 32MB. If the -* llc_aggr_tolerance is 1: -* When the footprint is larger than 32MB, the -* process is regarded as exceeding the LLC -* capacity. If the llc_aggr_tolerance is 99: -* When the footprint is larger than 784GB, the -* process is regarded as exceeding the LLC -* capacity: -* 784GB = (1 + (99 - 1) * 256) * 32MB -* If the llc_aggr_tolerance is 100: -* ignore the footprint and do the aggregation -* anyway. -*/ - scale =get_sched_cache_scale (256 ); -if (scale ==INT_MAX ) -return false; - -return ((llc * (u64 )scale) < (footprint *PAGE_SIZE )); +if (hist) { + cur =atomic_long_read (&grp->footprint_cur); + footprint =max (hist, hist /2 + cur); + } }#endif -return false; +/* +* No footprint estimate: the first sweep has not completed, or +* NUMA balancing is off. Fall back to the RSS of the mm. It is a +* poor estimate of the working set but an upper bound of it: if +* the RSS fits in the LLC, so does the working set. If it does +* not fit, we cannot tell, and refuse to aggregate. A missed +* aggregation forfeits a gain. A wrong one on a memory bandwidth +* bound process costs far more. +*/ +if (!footprint) + footprint =READ_ONCE (grp->rss_bound); + +return ((llc * (u64 )scale) < (footprint *PAGE_SIZE )); } static bool invalid_llc_nr(struct sched_cache_group *grp, struct task_struct *p,@@ -1630,6 +1650,7 @@ int mm_init_sched(struct mm_struct *mm, grp->footprint =0 ;atomic_long_set (&grp->footprint_cur,0 ); grp->last_decay_seq =0 ; + grp->rss_bound =0 ;refcount_set (&grp->refcnt,1 );/* * The update to grp->pcpu_sched should not be reordered
kernel/sched/fair.c static void task_cache_work(struct callback_head *work) · line 2043
Quoted 10 lines
kernel/sched/fair.c +7
-0@@ -2013,6 +2034,14 @@ static void task_cache_work(struct callback_head *work) READ_ONCE(llc_epoch_period), 1)))return ; +/* +* Sample the RSS of our own mm once per epoch, for the check +* below and for the tick and load balancer paths, which must +* not touch the mm of a task that is not current. +*/ +if (p->mm) +WRITE_ONCE (grp->rss_bound,get_mm_rss (p->mm));
MM_FILEPAGES includes some shared library, which was excluded by NUMA balancing, so we might also want to exclude it from the RSS. Maybe with above footprint timeout decay applied, we can decay the rss_bound as well, or use update_avg() to smooth it, otherwise it never shrink if we use max():
@@ -2014,9 +2019,18 @@ static void task_cache_work(struct callback_head *work)
cur = atomic_long_xchg(&grp->footprint_cur, 0);
hist = READ_ONCE(grp->footprint) / 2 + cur;
WRITE_ONCE(grp->footprint, hist);
+ WRITE_ONCE(grp->rss_bound, READ_ONCE(grp->rss_bound) / 2);
grp->footprint_timeout = now + SCHED_CACHE_FP_TIMEOUT_PERIOD;
}+ if (p->mm) {
+ unsigned long rss;
+
+ rss = get_mm_counter(p->mm, MM_ANONPAGES) +
+ get_mm_counter(p->mm, MM_SHMEMPAGES);
+ WRITE_ONCE(grp->rss_bound, max(READ_ONCE(grp->rss_bound), rss));
+ }
+
After a second thought, if we apply RSS based Fix2, do we still need Fix1?
thanks,
Chenyu
Quoted 10 lines
kernel/sched/fair.c +1
-0+ curr_cpu =task_cpu (p);if (invalid_llc_nr (grp, p, curr_cpu) ||exceed_llc_capacity (grp, curr_cpu)) {Signature · 1 line
2.53.0
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Quoted 5 lines · Chen Yu
kernel/sched/fair.c +0
-0if (!ng) {@@ -4210,6 +4178,15 @@ void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) p->numa_faults[task_faults_idx (NUMA_MEMBUF , mem_node, priv)] += pages; p->numa_faults[task_faults_idx (NUMA_CPUBUF , cpu_node, priv)] += pages;
kernel/sched/fair.c void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) · line 4189
Quoted 10 lines
kernel/sched/fair.c +9
-0p->numa_faults_locality[local] += pages; + +#ifdef CONFIG_SCHED_CACHE +scoped_guard (rcu) { +struct sched_cache_group *grp =rcu_dereference (p->sched_cache_grp); + +if (grp) +atomic_long_add (pages, &grp->footprint_cur); + } +#endif
I forgot the code from Tim that firstly add the footprint into per task buffer total_footprint, we should add back the following:
+static void sched_cache_footprint_accum(struct task_struct *p, int pages) +{
+ p->total_footprint += pages;
+
+ if (p->total_footprint >= SCHED_CACHE_FP_THRESHOLD)
+ sched_cache_footprint_flush(p);
+}
...
thanks,
Chenyu
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Hi Tim, Chen Yu,
Thank you both for the patches and the detailed design discussion. Two updates: the trace Tim asked for, and test results for the two patches.
PART 1: is NUMA balancing preventing the re-spread?
Quoted 3 lines
Wonder if NUMA balancing is preventing the re-spread?
If your traces havenuma_preferred_nidandtask_numa_migrateactivity after the trip, that would confirm or rule out out.
I traced it on the Fix-2 test kernel (mg.D 1x64 CAS-on, two runs that aggregated on different nodes, same structure in both): per-thread numa_preferred_nid sampled at every context switch, sched_setnuma() and migrate_task_to() in the task's own context, every sched_migrate_task with origin and destination, and wakeup target CPUs, alongside the group state per epoch.
The short answer: yes, but only late, and it is not the main obstacle. The run decomposes into three phases:
1. 0 - 4.9 s: consolidation. About 30 cross-node migrations toward the aggregated node; the footprint crosses the threshold at 4.2 - 4.9 s and grp->cpu is cleared.
2. Trip to sweep completion (4.9 - 35.8 s in the traced run): the re-spread runs at about 0.5 net cross-node migrations per second (thread placement 2/63 across the two nodes at t=4 s, 18/47 at t=28 s), and numa_preferred_nid is -1 for every thread during this whole window: sched_setnuma() first fires only when the sweep completes and placement runs, at t=35.8 s. So the NUMA preference cannot be what holds the re-spread back here. What the trace shows
instead: the wakeup placement keeps directing threads to the aggregated node at roughly 2:1 to 3:1 throughout the window (1264 vs 87 wakeups per 2 s at t=8 s, still 639 vs 380 at t=32 s; these are OMP barrier wakeups landing near their wakers), while the periodic balancer moves tasks out at only about 2 per 4 s. The net drift is the difference.
3. Sweep completion to end (35.8 - 42 s): placement sets numa_preferred_nid to the aggregated node for 53 of 66 threads (the pages have migrated there by then, so the fault statistics point there, exactly your reinforcing loop). From this moment the pull-back engages: migrate_task_to() toward the preferred node appears, and the cross-node churn in the last 6 s is 8 moves out vs 10 moves back, i.e. the spread stalls.
So NUMA balancing does prevent the re-spread, but only in the last 15 percent of the run. For the first 85 percent the preferred node is simply not set, and what holds it back is wake placement plus the conservative pace of cross-node load balancing. Resetting NUMA preferences at withdrawal would therefore not help this workload:
the sweep outlives the run, so there is nothing to reset during the window that matters. And the wake-placement observation suggests the re-spread would stay slow even with preferences reset; an active re-spread may need to move the tasks and let the wake placement follow.
PART 2: test results for the two patches
I built a kernel from the same 7.4.0-0.rc2.19.eln159 source, with Chen Yu's sketch (as tested before) and both patches applied. Both applied cleanly. Same test battery as the earlier rounds, n=5 medians for the NAS runs:
workload stock OFF stock ON patched OFF patched ON
NAS MG D, 1x64thr 26.45 s 41.78 s 26.38 s 26.47 s (+0.3%)
(+58%)
NAS MG C, 1x4thr 9.34 s 11.99 s 9.38 s 9.36 s (-0.2%)
(+28%)Both reported regressions are gone. The mechanism trace shows why:grp->cpu = -1 in all 42,566 task_cache_work() samples over one CAS-on MG run. The aggregation never settles, not even during the
warm-up: the RSS bound refuses within ~0.1 s of the allocation phase, before first-touch can skew anything. The hysteresis from PART 1 never develops because there is nothing to unwind.
The VM reproducer [3], the workload that benefits from packing, shows one cost of the patches and one way around it:
VM runtime: stock off 22.12 s, stock on 17.66 s (-20%)
patched off 21.81 s
patched on, tol=1: 22.47 s (+3.0%, win lost)
patched on, tol=4: 17.70 s (-18.9%, win back) cache-locality: tol=1: -4.6%, tol=4: +24.6%
mem-bandwidth: tol=1: +2.5%, tol=4: +30.6%
The win is lost at the default tolerance: qemu's RSS (guest memory, all anon) far exceeds the 108 MiB LLC, and the first sweep of its ~25 GB address space takes ~100 s while a reproducer pass runs ~20 s, so the bound governs throughout and aggregation is refused. At aggr_tolerance=4 the bound is (1 + 3*256) x 108 MiB = 83 GiB, qemu fits, and the win returns. The tolerance knob thus doubles as the opt-in for large-RSS workloads that benefit from aggregation. Splitting the two, so the tolerance scales only the estimate and not the bound, may be worth considering; either way the coupling deserves a line in the documentation.
On Chen Yu's question, whether Fix 1 is still needed if Fix 2 accumulates the RSS bound: the data says yes for the regression class. The bound is what refuses aggregation for MG D and MG C, because their fault-based estimate never exists within a run (the sweep is too slow), and Fix 2 alone recovered only one sixth of the regression in the earlier test.
Fix 2 correcting the initial placement does happen for a long-running VM, and I traced it. I ran the VM reproducer with the in-VM workloads scaled 10x (about 100 s per phase, 4 minutes per pass). The group state over the CAS-on pass at the default tolerance:
t=0 VM boots; rss_bound is 0 for the first epoch, CAS
aggregates for ~0.1 s until the first RSS sample lands (435k pages), then refuses.
t=16 s the first scan sweep folds: the history becomes 27,298
pages, the VM's actual hot set, within 1.3 percent of the 27,648-page LLC. The estimate takes over from the RSS bound, the check passes, and the aggregation is
granted: grp->cpu is set for the first time since boot.
t=19 s the bandwidth phase grows the current window to 23,576
pages; max(history, history/2 + window) crosses the threshold and the aggregation is withdrawn.
rest stably refused; the estimate stays above the threshold.
So the mechanism works exactly as designed end to end: the bound guards the window before the first sweep, the estimate corrects the decision afterward, and the flat combination catches the growth within the sweep. This VM is a boundary case by accident rather than design: its workload data is tiny, but the guest kernel and initramfs dominate the hot set, which was never sized against the LLC. Either way it is precisely the flip territory your max() smoothing addresses.
The aggregate numbers reflect how little of the run the granted window covers: the long pass ends at -2.9% runtime, +2.4% cache-locality, +6.0% bandwidth, against -20% for the stock kernel and +3.0% for the same patched kernel with the short (~20 s) workload. A persistent VM partially recovers the benefit.
One race worth noting: rss_bound is sampled at the first task_cache_work() epoch after group creation, so for about 0.1 s the bound is 0 and CAS can aggregate. In the traced run that blip was enough to set the initial vCPU placement (the threads clustered and never moved afterward; the box is idle and nothing pulls 8 threads back). Sampling rss_bound at group creation in mm_init_sched(), or withholding aggregation until the first sample, would close it.
Putting the three rounds of testing together, my recommendation:
I vote for keeping both fixes. They do different jobs: the RSS bound is the only thing that protects the window before the first sweep, which is where the memory-bound workloads take their damage, and the within-sweep accumulation is what makes the decision correct afterward and recovers the beneficial cases. The cost asymmetry settles the default: a wrongly granted aggregation cost us 58 percent, a wrongly refused one forfeits a 20 percent gain.
Two refinements seem worth considering on top:
- Hysteresis on the grant/withdraw decision. The VM trace showed a boundary case as it sits close to the threshold, so the aggregation flips as the window grows and the history decays. Withdrawing above the threshold and re-granting below half of it, the pattern imb_pct and overaggr_pct already use, would stabilize it.
- The tolerance splitting. aggr_tolerance was designed to scale the footprint threshold, and it now scales the RSS bound too, so tolerance 2 jumps the bound from 108 MiB to 27.5 GiB. That works as an opt-in but is a blunt one; the per-group control from the prctl RFC seems the better tool for "this large-RSS workload wants aggregation", with the tolerance kept for the estimate.
Happy to share the probe scripts or re-run anything.
Thanks,
Jirka
[3] The VM test boots a small VM directly off the host's own kernel and initramfs, with no guest OS install: 1 VM, 8 vCPUs, 25 GB of guest memory. Two workloads run inside it, in this order: a cache-locality test (process pairs exchanging data through FIFO pipes, reported as ops/s) and a memory-bandwidth test (cp over a 216 MB buffer, twice this host's LLC, reported as MB/s). The test records which physical CPUs the vCPU threads land on, which is how the packing effect is measured. The long variant scales the in-VM iterations 10x, to about 100 s per workload phase.
On Mon, Nov 17, 2026 at 12:39 AM Tim Chen <[email protected]> wrote:
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Hi,
Quoted 72 lines · On Wed, Nov 18, 2026 at 04:06:55AM +0100 Jirka Hladky wrote:
Hi Tim, Chen Yu,
Thank you both for the patches and the detailed design discussion. Two updates: the trace Tim asked for, and test results for the two patches.
PART 1: is NUMA balancing preventing the re-spread?
Quoted 3 lines
Wonder if NUMA balancing is preventing the re-spread?
If your traces havenuma_preferred_nidandtask_numa_migrateactivity after the trip, that would confirm or rule out out.I traced it on the Fix-2 test kernel (mg.D 1x64 CAS-on, two runs that aggregated on different nodes, same structure in both): per-thread
numa_preferred_nidsampled at every context switch,sched_setnuma()andmigrate_task_to()in the task's own context, everysched_migrate_taskwith origin and destination, and wakeup target CPUs, alongside the group state per epoch.The short answer: yes, but only late, and it is not the main obstacle. The run decomposes into three phases:
1. 0 - 4.9 s: consolidation. About 30 cross-node migrations toward the aggregated node; the footprint crosses the threshold at 4.2 - 4.9 s and
grp->cpuis cleared.2. Trip to sweep completion (4.9 - 35.8 s in the traced run): the re-spread runs at about 0.5 net cross-node migrations per second (thread placement 2/63 across the two nodes at t=4 s, 18/47 at t=28 s), and
numa_preferred_nidis -1 for every thread during this whole window:sched_setnuma()first fires only when the sweep completes and placement runs, at t=35.8 s. So the NUMA preference cannot be what holds the re-spread back here. What the trace shows
instead: the wakeup placement keeps directing threads to the aggregated node at roughly 2:1 to 3:1 throughout the window (1264 vs 87 wakeups per 2 s at t=8 s, still 639 vs 380 at t=32 s; these are OMP barrier wakeups landing near their wakers), while the periodic balancer moves tasks out at only about 2 per 4 s. The net drift is the difference.3. Sweep completion to end (35.8 - 42 s): placement sets
numa_preferred_nidto the aggregated node for 53 of 66 threads (the pages have migrated there by then, so the fault statistics point there, exactly your reinforcing loop). From this moment the pull-back engages:migrate_task_to()toward the preferred node appears, and the cross-node churn in the last 6 s is 8 moves out vs 10 moves back, i.e. the spread stalls.So NUMA balancing does prevent the re-spread, but only in the last 15 percent of the run. For the first 85 percent the preferred node is simply not set, and what holds it back is wake placement plus the conservative pace of cross-node load balancing. Resetting NUMA preferences at withdrawal would therefore not help this workload:
the sweep outlives the run, so there is nothing to reset during the window that matters. And the wake-placement observation suggests the re-spread would stay slow even with preferences reset; an active re-spread may need to move the tasks and let the wake placement follow.PART 2: test results for the two patches
I built a kernel from the same 7.4.0-0.rc2.19.eln159 source, with Chen Yu's sketch (as tested before) and both patches applied. Both applied cleanly. Same test battery as the earlier rounds, n=5 medians for the NAS runs:
workload stock OFF stock ON patched OFF patched ON NAS MG D, 1x64thr 26.45 s 41.78 s 26.38 s 26.47 s (+0.3%) (+58%) NAS MG C, 1x4thr 9.34 s 11.99 s 9.38 s 9.36 s (-0.2%) (+28%)
Quoted 6 lines
Both reported regressions are gone. The mechanism trace shows why:
grp->cpu= -1 in all 42,566task_cache_work()samples over one CAS-on MG run. The aggregation never settles, not even during the
warm-up: the RSS bound refuses within ~0.1 s of the allocation phase, before first-touch can skew anything. The hysteresis from PART 1 never develops because there is nothing to unwind.
That is an excellent thing to see. Thanks for all the testing Jirka!
And thank you Tim and Chen Yu for being so responsive to our issue.
...
Quoted 9 lines
I vote for keeping both fixes. They do different jobs: the RSS bound is the only thing that protects the window before the first sweep, which is where the memory-bound workloads take their damage, and the within-sweep accumulation is what makes the decision correct afterward and recovers the beneficial cases. The cost asymmetry settles the default: a wrongly granted aggregation cost us 58 percent, a wrongly refused one forfeits a 20 percent gain.
I agree both fixes seem worth having.
Quoted 8 lines
Two refinements seem worth considering on top:
- Hysteresis on the grant/withdraw decision. The VM trace showed a boundary case as it sits close to the threshold, so the aggregation flips as the window grows and the history decays. Withdrawing above the threshold and re-granting below half of it, the pattern
imb_pctandoveraggr_pctalready use, would stabilize it.
Quoted 7 lines
- The tolerance splitting.
aggr_tolerancewas designed to scale the footprint threshold, and it now scales the RSS bound too, so tolerance 2 jumps the bound from 108 MiB to 27.5 GiB. That works as an opt-in but is a blunt one; the per-group control from the prctl RFC seems the better tool for "this large-RSS workload wants aggregation", with the tolerance kept for the estimate.
These also look like reasonable refinements.
I may have missed it (or cut too much :), but how did this changed kernel behave on all the other tests? That is, did it regress else where? I'm thinking it should be pretty safe since it targets this use case and should not play a role in the cases that did not hit this.
Cheers,
Phil
Quoted 17 lines
Happy to share the probe scripts or re-run anything.
Thanks,
Jirka[3] The VM test boots a small VM directly off the host's own kernel and initramfs, with no guest OS install: 1 VM, 8 vCPUs, 25 GB of guest memory. Two workloads run inside it, in this order: a cache-locality test (process pairs exchanging data through FIFO pipes, reported as ops/s) and a memory-bandwidth test (cp over a 216 MB buffer, twice this host's LLC, reported as MB/s). The test records which physical CPUs the vCPU threads land on, which is how the packing effect is measured. The long variant scales the in-VM iterations 10x, to about 100 s per workload phase.
On Mon, Nov 17, 2026 at 12:39 AM Tim Chen <[email protected]> wrote:
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
In reply to Jirka HladkyHi Jirka,
Quoted 48 lines · Jirka Hladky
Hi Tim, Chen Yu,
Thank you both for the patches and the detailed design discussion. Two updates: the trace Tim asked for, and test results for the two patches.
PART 1: is NUMA balancing preventing the re-spread?
Quoted 3 lines
Wonder if NUMA balancing is preventing the re-spread?
If your traces havenuma_preferred_nidandtask_numa_migrateactivity after the trip, that would confirm or rule out out.I traced it on the Fix-2 test kernel (mg.D 1x64 CAS-on, two runs that aggregated on different nodes, same structure in both): per-thread
numa_preferred_nidsampled at every context switch,sched_setnuma()andmigrate_task_to()in the task's own context, everysched_migrate_taskwith origin and destination, and wakeup target CPUs, alongside the group state per epoch.The short answer: yes, but only late, and it is not the main obstacle. The run decomposes into three phases:
1. 0 - 4.9 s: consolidation. About 30 cross-node migrations toward the aggregated node; the footprint crosses the threshold at 4.2 - 4.9 s and
grp->cpuis cleared.2. Trip to sweep completion (4.9 - 35.8 s in the traced run): the re-spread runs at about 0.5 net cross-node migrations per second (thread placement 2/63 across the two nodes at t=4 s, 18/47 at t=28 s), and
numa_preferred_nidis -1 for every thread during this whole window:sched_setnuma()first fires only when the sweep completes and placement runs, at t=35.8 s. So the NUMA preference cannot be what holds the re-spread back here. What the trace shows
instead: the wakeup placement keeps directing threads to the aggregated node at roughly 2:1 to 3:1 throughout the window (1264 vs 87 wakeups per 2 s at t=8 s, still 639 vs 380 at t=32 s; these are OMP barrier wakeups landing near their wakers), while the periodic balancer moves tasks out at only about 2 per 4 s. The net drift is the difference.3. Sweep completion to end (35.8 - 42 s): placement sets
numa_preferred_nidto the aggregated node for 53 of 66 threads (the pages have migrated there by then, so the fault statistics point there, exactly your reinforcing loop). From this moment the pull-back engages:migrate_task_to()toward the preferred node appears, and the cross-node churn in the last 6 s is 8 moves out vs 10 moves back, i.e. the spread stalls.
Quoted 4 lines
So NUMA balancing does prevent the re-spread, but only in the last 15 percent of the run. For the first 85 percent the preferred node is simply not set, and what holds it back is wake placement plus the conservative pace of cross-node load balancing.
I created a test case that can reproduce this issue on a SRF. Actually, it is not the wakeup that aggregates the wakee on the local LLC in wake_affine(), that is the expected behavior for fast wakeup. Rather, because the tasks are first aggregated onto the same LLC by cache-aware scheduling, the wakeup then tries to wake the wakee on its previous/target CPU on the same LLC. The problem is that load balancing spreads the task too slowly: because there is only one running task on each CPU, active load balancing has to be triggered to spread the task to a different LLC. Active load balancing has to exceed an upper limit of 5
failures: cache_nice_tries + 2 = 4, with a min_interval of 192 ms because sd_weight = 2 NUMA nodes = 192 on my SRF, so roughly every 5 * 192 = 960 ms it will pull a task out. In your case, there are 288 CPUs for 2 nodes, so in theory it should take 288 * 5 = 1.4 seconds to pull one task out.
The test code is a single process with several threads just doing a while(1) loop, without waking up each other. First, bind all threads to LLC0 (socket0), then release their CPU affinity, and watch how they are spread to LLC1.
So to avoid this from happening, we should avoid aggregating the tasks at the first place.
Quoted 49 lines
Resetting NUMA preferences at withdrawal would therefore not help this workload:
the sweep outlives the run, so there is nothing to reset during the window that matters. And the wake-placement observation suggests the re-spread would stay slow even with preferences reset; an active re-spread may need to move the tasks and let the wake placement follow.PART 2: test results for the two patches
I built a kernel from the same 7.4.0-0.rc2.19.eln159 source, with Chen Yu's sketch (as tested before) and both patches applied. Both applied cleanly. Same test battery as the earlier rounds, n=5 medians for the NAS runs:
workload stock OFF stock ON patched OFF patched ON NAS MG D, 1x64thr 26.45 s 41.78 s 26.38 s 26.47 s (+0.3%) (+58%) NAS MG C, 1x4thr 9.34 s 11.99 s 9.38 s 9.36 s (-0.2%) (+28%)Both reported regressions are gone. The mechanism trace shows why:
grp->cpu= -1 in all 42,566task_cache_work()samples over one CAS-on MG run. The aggregation never settles, not even during the
warm-up: the RSS bound refuses within ~0.1 s of the allocation phase, before first-touch can skew anything. The hysteresis from PART 1 never develops because there is nothing to unwind.The VM reproducer [3], the workload that benefits from packing, shows one cost of the patches and one way around it:
VM runtime: stock off 22.12 s, stock on 17.66 s (-20%)
patched off 21.81 s patched on, tol=1: 22.47 s (+3.0%, win lost) patched on, tol=4: 17.70 s (-18.9%, win back)cache-locality: tol=1: -4.6%, tol=4: +24.6%
mem-bandwidth: tol=1: +2.5%, tol=4: +30.6%The win is lost at the default tolerance: qemu's RSS (guest memory, all anon) far exceeds the 108 MiB LLC, and the first sweep of its ~25 GB address space takes ~100 s while a reproducer pass runs ~20 s, so the bound governs throughout and aggregation is refused. At aggr_tolerance=4 the bound is (1 + 3*256) x 108 MiB = 83 GiB, qemu fits, and the win returns. The tolerance knob thus doubles as the opt-in for large-RSS workloads that benefit from aggregation. Splitting the two, so the tolerance scales only the estimate and not the bound, may be worth considering; either way the coupling deserves a line in the documentation.
Quoted 7 lines
On Chen Yu's question, whether Fix 1 is still needed if Fix 2 accumulates the RSS bound: the data says yes for the regression class. The bound is what refuses aggregation for MG D and MG C, because their fault-based estimate never exists within a run (the sweep is too slow), and Fix 2 alone recovered only one sixth of the regression in the earlier test.
Actually what I mean was if the RSS(not footprint accumulation during numa page fault) is used as the last resort if the footprint is 0, will this change fix the issue anyway? I guess the answer is yes, because you mentioned that the major fix is from the RSS gating.
Quoted 53 lines
Fix 2 correcting the initial placement does happen for a long-running VM, and I traced it. I ran the VM reproducer with the in-VM workloads scaled 10x (about 100 s per phase, 4 minutes per pass). The group state over the CAS-on pass at the default tolerance:
t=0 VM boots;
rss_boundis 0 for the first epoch, CAS
aggregates for ~0.1 s until the first RSS sample lands (435k pages), then refuses.
t=16 s the first scan sweep folds: the history becomes 27,298
pages, the VM's actual hot set, within 1.3 percent of the 27,648-page LLC. The estimate takes over from the RSS bound, the check passes, and the aggregation is
granted:grp->cpuis set for the first time since boot.
t=19 s the bandwidth phase grows the current window to 23,576
pages;max(history, history/2 + window)crosses the threshold and the aggregation is withdrawn.
rest stably refused; the estimate stays above the threshold.So the mechanism works exactly as designed end to end: the bound guards the window before the first sweep, the estimate corrects the decision afterward, and the flat combination catches the growth within the sweep. This VM is a boundary case by accident rather than design: its workload data is tiny, but the guest kernel and initramfs dominate the hot set, which was never sized against the LLC. Either way it is precisely the flip territory your
max()smoothing addresses.The aggregate numbers reflect how little of the run the granted window covers: the long pass ends at -2.9% runtime, +2.4% cache-locality, +6.0% bandwidth, against -20% for the stock kernel and +3.0% for the same patched kernel with the short (~20 s) workload. A persistent VM partially recovers the benefit.
One race worth noting:
rss_boundis sampled at the firsttask_cache_work()epoch after group creation, so for about 0.1 s the bound is 0 and CAS can aggregate. In the traced run that blip was enough to set the initial vCPU placement (the threads clustered and never moved afterward; the box is idle and nothing pulls 8 threads back). Samplingrss_boundat group creation inmm_init_sched(), or withholding aggregation until the first sample, would close it.Putting the three rounds of testing together, my recommendation:
I vote for keeping both fixes. They do different jobs: the RSS bound is the only thing that protects the window before the first sweep, which is where the memory-bound workloads take their damage, and the within-sweep accumulation is what makes the decision correct afterward and recovers the beneficial cases. The cost asymmetry settles the default: a wrongly granted aggregation cost us 58 percent, a wrongly refused one forfeits a 20 percent gain.
Quoted 8 lines
Two refinements seem worth considering on top:
- Hysteresis on the grant/withdraw decision. The VM trace showed a boundary case as it sits close to the threshold, so the aggregation flips as the window grows and the history decays. Withdrawing above the threshold and re-granting below half of it, the pattern
imb_pctandoveraggr_pctalready use, would stabilize it.
Agree, this is a good point that we should also apply hysteresis for footprint/RSS.
Quoted 7 lines
- The tolerance splitting.
aggr_tolerancewas designed to scale the footprint threshold, and it now scales the RSS bound too, so tolerance 2 jumps the bound from 108 MiB to 27.5 GiB. That works as an opt-in but is a blunt one; the per-group control from the prctl RFC seems the better tool for "this large-RSS workload wants aggregation", with the tolerance kept for the estimate.
Agree, BTW, if the workload has large-RSS but does not share data between each threads, this is an indicator that cache-aware-scheduling should not take care of. This information can be given either by the userspace via prctl, or maybe by leveraging numa_group in the NUMA balancing mechanism.
thanks,
Chenyu
Quoted 17 lines
Happy to share the probe scripts or re-run anything.
Thanks,
Jirka[3] The VM test boots a small VM directly off the host's own kernel and initramfs, with no guest OS install: 1 VM, 8 vCPUs, 25 GB of guest memory. Two workloads run inside it, in this order: a cache-locality test (process pairs exchanging data through FIFO pipes, reported as ops/s) and a memory-bandwidth test (cp over a 216 MB buffer, twice this host's LLC, reported as MB/s). The test records which physical CPUs the vCPU threads land on, which is how the packing effect is measured. The long variant scales the in-VM iterations 10x, to about 100 s per workload phase.
On Mon, Nov 17, 2026 at 12:39 AM Tim Chen <[email protected]> wrote:
Re: [Patch v4 17/22] sched/cache: Avoid cache-aware scheduling for memory-heavy processes
Hi Phil, Chen Yu,
Phil, on your question: the VM results were in my mail, but they may have been cut in the quoting. The short version: the patched kernel at the default tolerance loses the VM's 20 percent packing win (22.47 s vs 21.81 s with CAS off), and gets it back at aggr_tolerance=4 (17.70 s). That is the one regression the patches introduce, and it was the known cost of the RSS bound. The refusal is also not permanent: the RSS check only governs until the first address-space sweep completes (~16 s for this VM), after which the fault-based estimate takes over and grouping can start again, which I traced on a long-running variant of the VM test. So the worst case for a workload that genuinely should aggregate is a bounded startup delay, not a permanent behavior change.
On safety elsewhere: with CAS off, the patched kernel matches stock on everything we ran (NAS MG D 26.38 vs 26.45 s, MG C 9.38 vs 9.34 s, VM 21.81 vs 22.12 s, all n=5 medians and within noise), so the patches are inert when the feature is off. With CAS on, the behavioral change is confined to processes whose RSS exceeds the LLC (they no longer aggregate) and to the estimate dynamics near the threshold; processes with a small RSS aggregate exactly as before.
Chen Yu, on your questions:
Quoted 5 lines
Actually what I mean was if the RSS (not footprint accumulation during numa page fault) is used as the last resort if the footprint is 0, will this change fix the issue anyway? I guess the answer is yes, because you mentioned that the major fix is from the RSS gating.
Yes, confirmed with numbers. That is exactly the configuration I tested (Tim's second patch falls back to the RSS when the history is 0). NAS runtimes, n=5 medians:
workload stock OFF stock ON patched OFF patched ON
NAS MG D 1x64 26.45 s 41.78 s 26.38 s 26.47 s
NAS MG C 1x4 9.34 s 11.99 s 9.38 s 9.36 s
The gate refuses within ~0.1 s of the allocation phase, so the CAS-on runtime matches the CAS-off runtime on the patched kernel. The RSS fallback alone eliminates the reported regressions; your sketch's accumulation is what makes the decision correct afterward, not what stops the damage.
Quoted 4 lines
The test code is a single process with several threads just doing a while(1) loop, without waking up each other. First, bind all threads to LLC0 (socket0), then release their CPU affinity, and watch how they are spread to LLC1.
I replicated your test on our 288-CPU box (64 spinning threads, bound to LLC0, affinity released, placement sampled at 10 Hz). With CAS off, the mean interval between threads reaching LLC1 is 1.59 s, against your model's 1.44 s for this CPU count: within 10 percent, so the model holds. It also matches the re-spread rate I measured on the MG workload (~2 s per thread in the main window), which supports your reading of my trace: the wake placement is expected wake_affine behavior, and the load balancer's pace is the rate limiter. My "wake placement plus conservative balancing" should really read "conservative balancing, with wake placement doing what it always does".
For completeness, I also ran it with CAS on: only 5 of 64 threads reached LLC1 in 240 s. The spinning threads form a cache group with a zero footprint (they never fault), so the group holds them on LLC0.
On the numa_group idea: one caution from our two workloads. Both qemu (which benefits from packing) and NAS MG (which loses 58%) are single processes whose threads share one mm, so group or mm membership alone does not separate them; what separates them is the hot-set-to-LLC ratio. So I agree the sharing signal is the right thing to look for, but it likely has to come from userspace via prctl, or from a signal that tracks the actual sharing fraction, rather than from grouping alone.
Thanks,
Jirka
On Tue, Nov 18, 2026 at 9:31 PM Chen Yu <[email protected]> wrote: