scx_rusty/
load_balance.rs

1// Copyright (c) Meta Platforms, Inc. and affiliates.
2
3// This software may be used and distributed according to the terms of the
4// GNU General Public License version 2.
5
6//! # Rusty load balancer
7//!
8//! The module that includes logic for performing load balancing in the
9//! scx_rusty scheduler.
10//!
11//! Load Balancing
12//! --------------
13//!
14//! scx_rusty performs load balancing using the following general workflow:
15//!
16//! 1. Determine domain load averages from the duty cycle buckets in the
17//!    dom_ctx_map_elem map, aggregate the load using
18//!    scx_utils::LoadCalculator, and then determine load distribution
19//!    (accounting for infeasible weights) the scx_utils::LoadLedger object.
20//!
21//! 2. Create a hierarchy representing load using NumaNode and Domain objects
22//!    as follows:
23//!
24//!                                 o--------------------------------o
25//!                                 |             LB Root            |
26//!                                 |                                |
27//!                                 | PushNodes: <Load, NumaNode>    |
28//!                                 | PullNodes: <Load, NumaNode>    |
29//!                                 | BalancedNodes: <Load, NumaNode>|
30//!                                 o----------------o---------------o
31//!                                                  |
32//!                              o-------------------o-------------------o
33//!                              |                   |                   |
34//!                              |                   |                   |
35//!                o-------------o--------------o   ...   o--------------o-------------o
36//!                |          NumaNode          |         |           NumaNode         |
37//!                | ID    0                    |         | ID    1                    |
38//!                | PushDomains <Load, Domain> |         | PushDomains <Load, Domain> |
39//!                | PullDomains <Load, Domain> |         | PullDomains <Load, Domain> |
40//!                | BalancedDomains <Domain>   |         | BalancedDomains <Domain>   |
41//!                | LoadSum f64                |         | LoadSum f64                |
42//!                | LoadAvg f64                |         | LoadAvg f64                |
43//!                | LoadImbal f64              |         | LoadImbal f64              |
44//!                | BalanceCost f64            |         | BalanceCost f64            |
45//!                | ...                        |         | ...                        |
46//!                o-------------o--------------o         o----------------------------o
47//!                              |
48//!                              |
49//!  o----------------------o   ...   o---------------------o
50//!  |        Domain        |         |        Domain       |
51//!  | ID    0              |         | ID    1             |
52//!  | Tasks   <Load, Task> |         | Tasks  <Load, Task> |
53//!  | LoadSum f64          |         | LoadSum f64         |
54//!  | LoadAvg f64          |         | LoadAvg f64         |
55//!  | LoadImbal f64        |         | LoadImbal f64       |
56//!  | BalanceCost f64      |         | BalanceCost f64     |
57//!  | ...                  |         | ...                 |
58//!  o----------------------o         o----------o----------o
59//!                                              |
60//!                                              |
61//!                        o----------------o   ...   o----------------o
62//!                        |      Task      |         |      Task      |
63//!                        | PID   0        |         | PID   1        |
64//!                        | Load  f64      |         | Load  f64      |
65//!                        | Migrated bool  |         | Migrated bool  |
66//!                        | IsKworker bool |         | IsKworker bool |
67//!                        o----------------o         o----------------o
68//!
69//! As mentioned above, the hierarchy is created by querying BPF for each
70//! domain's duty cycle, and using the infeasible.rs crate to determine load
71//! averages and load sums for each domain.
72//!
73//! 3. From the LB Root, we begin by iterating over all NUMA nodes, and
74//!    migrating load from any nodes with an excess of load (push nodes) to
75//!    nodes with a lack of load (pull domains). The cost of migrations here are
76//!    higher than when migrating load between domains within a node.
77//!    Ultimately, migrations are performed by moving tasks between domains. The
78//!    difference in this step is that imbalances are first addressed by moving
79//!    tasks between NUMA nodes, and that such migrations only take place when
80//!    imbalances are sufficiently high to warrant it.
81//!
82//! 4. Once load has been migrated between NUMA nodes, we iterate over each NUMA
83//!    node and migrate load between the domains inside of each. The cost of
84//!    migrations here are lower than between NUMA nodes. Like with load
85//!    balancing between NUMA nodes, migrations here are just moving tasks
86//!    between domains.
87//!
88//! The load hierarchy is always created when load_balance() is called on a
89//! LoadBalancer object, but actual load balancing is only performed if the
90//! balance_load option is specified.
91//!
92//! Statistics
93//! ----------
94//!
95//! After load balancing has occurred, statistics may be queried by invoking
96//! the get_stats() function on the LoadBalancer object:
97//!
98//! ```
99//! let lb = LoadBalancer::new(...)?;
100//! lb.load_balance()?;
101//!
102//! let stats = lb.get_stats();
103//! ...
104//! ```
105//!
106//! Statistics are exported as a vector of NumaStat objects, which each
107//! contains load balancing statistics for that NUMA node, as well as
108//! statistics for any Domains contained therein as DomainStats objects.
109//!
110//! Future Improvements
111//! -------------------
112//!
113//! There are a few ways that we could further improve the implementation here:
114//!
115//! - The logic for load balancing between NUMA nodes, and load balancing within
116//!   a specific NUMA node (i.e. between domains in that NUMA node), could
117//!   probably be improved to avoid code duplication using traits and/or
118//!   generics.
119//!
120//! - When deciding whether to migrate a task, we're only looking at its impact
121//!   on addressing load imbalances. In reality, this is a very complex,
122//!   multivariate cost function. For example, a domain with sufficiently low
123//!   load to warrant having an imbalance / requiring more load maybe should not
124//!   pull load if it's running tasks that are much better suited to isolation.
125//!   Or, a domain may not want to push a task to another domain if the task is
126//!   co-located with other tasks that benefit from shared L3 cache locality.
127//!
128//!   Coming up with an extensible and clean way to model and implement this is
129//!   likely itself a large project.
130//!
131//! - We're not accounting for cgroups when performing load balancing.
132
133use core::cmp::Ordering;
134use std::cell::Cell;
135use std::collections::BTreeMap;
136use std::collections::VecDeque;
137use std::fmt;
138use std::sync::Arc;
139
140use anyhow::Result;
141use anyhow::bail;
142use log::debug;
143use log::trace;
144use ordered_float::OrderedFloat;
145use scx_utils::LoadAggregator;
146use scx_utils::LoadLedger;
147use scx_utils::ravg::ravg_read;
148use sorted_vec::SortedVec;
149
150use crate::DomainGroup;
151use crate::bpf_intf;
152use crate::bpf_skel::*;
153use crate::stats::DomainStats;
154use crate::stats::NodeStats;
155
156const DEFAULT_WEIGHT: f64 = bpf_intf::consts_LB_DEFAULT_WEIGHT as f64;
157const RAVG_FRAC_BITS: u32 = bpf_intf::ravg_consts_RAVG_FRAC_BITS;
158
159fn now_monotonic() -> u64 {
160    let mut time = libc::timespec {
161        tv_sec: 0,
162        tv_nsec: 0,
163    };
164    let ret = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut time) };
165    assert!(ret == 0);
166    time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64
167}
168
169#[derive(Clone, Copy, Debug, PartialEq)]
170enum BalanceState {
171    Balanced,
172    NeedsPush,
173    NeedsPull,
174}
175
176impl fmt::Display for BalanceState {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            BalanceState::Balanced => write!(f, "BALANCED"),
180            BalanceState::NeedsPush => write!(f, "OVER-LOADED"),
181            BalanceState::NeedsPull => write!(f, "UNDER-LOADED"),
182        }
183    }
184}
185
186macro_rules! impl_ord_for_type {
187    ($($t:ty),*) => {
188        $(
189            impl PartialEq for $t {
190                fn eq(&self, other: &Self) -> bool {
191                    <dyn LoadOrdered>::eq(self, other)
192                }
193            }
194
195            impl Eq for $t {}
196
197            impl PartialOrd for $t {
198                fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
199                    <dyn LoadOrdered>::partial_cmp(self, other)
200                }
201            }
202
203            impl Ord for $t {
204                fn cmp(&self, other: &Self) -> Ordering {
205                    <dyn LoadOrdered>::cmp(self, other)
206                }
207            }
208        )*
209    };
210}
211
212trait LoadOrdered {
213    fn get_load(&self) -> OrderedFloat<f64>;
214}
215
216impl dyn LoadOrdered {
217    #[inline]
218    fn eq(&self, other: &Self) -> bool {
219        self.get_load().eq(&other.get_load())
220    }
221
222    #[inline]
223    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
224        self.get_load().partial_cmp(&other.get_load())
225    }
226
227    #[inline]
228    fn cmp(&self, other: &Self) -> Ordering {
229        self.get_load().cmp(&other.get_load())
230    }
231}
232
233#[derive(Debug, Clone)]
234pub struct LoadEntity {
235    cost_ratio: f64,
236    push_max_ratio: f64,
237    xfer_ratio: f64,
238    load_sum: OrderedFloat<f64>,
239    load_avg: f64,
240    load_delta: f64,
241    bal_state: BalanceState,
242}
243
244impl LoadEntity {
245    fn new(
246        cost_ratio: f64,
247        push_max_ratio: f64,
248        xfer_ratio: f64,
249        load_sum: f64,
250        load_avg: f64,
251    ) -> Self {
252        let mut entity = Self {
253            cost_ratio,
254            push_max_ratio,
255            xfer_ratio,
256            load_sum: OrderedFloat(load_sum),
257            load_avg,
258            load_delta: 0.0f64,
259            bal_state: BalanceState::Balanced,
260        };
261        entity.add_load(0.0f64);
262        entity
263    }
264
265    pub fn load_sum(&self) -> f64 {
266        *self.load_sum
267    }
268
269    pub fn load_avg(&self) -> f64 {
270        self.load_avg
271    }
272
273    pub fn imbal(&self) -> f64 {
274        self.load_sum() - self.load_avg
275    }
276
277    pub fn delta(&self) -> f64 {
278        self.load_delta
279    }
280
281    fn state(&self) -> BalanceState {
282        self.bal_state
283    }
284
285    fn rebalance(&mut self, new_load: f64) {
286        self.load_sum = OrderedFloat(new_load);
287
288        let imbal = self.imbal();
289        let needs_balance = imbal.abs() > self.load_avg * self.cost_ratio;
290
291        self.bal_state = if needs_balance {
292            if imbal > 0f64 {
293                BalanceState::NeedsPush
294            } else {
295                BalanceState::NeedsPull
296            }
297        } else {
298            BalanceState::Balanced
299        };
300    }
301
302    fn add_load(&mut self, delta: f64) {
303        self.rebalance(self.load_sum() + delta);
304        self.load_delta += delta;
305    }
306
307    fn push_cutoff(&self) -> f64 {
308        self.imbal().abs() * self.push_max_ratio
309    }
310
311    fn xfer_between(&self, other: &LoadEntity) -> f64 {
312        self.imbal().abs().min(other.imbal().abs()) * self.xfer_ratio
313    }
314}
315
316#[derive(Debug)]
317struct TaskInfo {
318    taskc_p: *mut types::task_ctx,
319    load: OrderedFloat<f64>,
320    dom_mask: u64,
321    preferred_dom_mask: u64,
322    migrated: Cell<bool>,
323    is_kworker: bool,
324}
325
326impl LoadOrdered for TaskInfo {
327    fn get_load(&self) -> OrderedFloat<f64> {
328        self.load
329    }
330}
331impl_ord_for_type!(TaskInfo);
332
333#[derive(Debug)]
334struct Domain {
335    id: usize,
336    queried_tasks: bool,
337    load: LoadEntity,
338    tasks: SortedVec<TaskInfo>,
339}
340
341impl Domain {
342    const LOAD_IMBAL_HIGH_RATIO: f64 = 0.05;
343    const LOAD_IMBAL_XFER_TARGET_RATIO: f64 = 0.50;
344    const LOAD_IMBAL_PUSH_MAX_RATIO: f64 = 0.50;
345
346    fn new(id: usize, load_sum: f64, load_avg: f64) -> Self {
347        Self {
348            id,
349            queried_tasks: false,
350            load: LoadEntity::new(
351                Domain::LOAD_IMBAL_HIGH_RATIO,
352                Domain::LOAD_IMBAL_PUSH_MAX_RATIO,
353                Domain::LOAD_IMBAL_XFER_TARGET_RATIO,
354                load_sum,
355                load_avg,
356            ),
357            tasks: SortedVec::new(),
358        }
359    }
360
361    fn transfer_load(&mut self, load: f64, taskc: &mut types::task_ctx, other: &mut Domain) {
362        trace!("XFER pid={} dom={}->{}", taskc.pid, self.id, other.id);
363
364        let dom_id: u32 = other.id.try_into().unwrap();
365        taskc.target_dom = dom_id;
366
367        self.load.add_load(-load);
368        other.load.add_load(load);
369    }
370
371    fn xfer_between(&self, other: &Domain) -> f64 {
372        self.load.xfer_between(&other.load)
373    }
374}
375
376impl LoadOrdered for Domain {
377    fn get_load(&self) -> OrderedFloat<f64> {
378        self.load.load_sum
379    }
380}
381impl_ord_for_type!(Domain);
382
383#[derive(Debug)]
384struct NumaNode {
385    id: usize,
386    load: LoadEntity,
387    domains: SortedVec<Domain>,
388}
389
390impl NumaNode {
391    const LOAD_IMBAL_HIGH_RATIO: f64 = 0.17;
392    const LOAD_IMBAL_XFER_TARGET_RATIO: f64 = 0.50;
393    const LOAD_IMBAL_PUSH_MAX_RATIO: f64 = 0.50;
394
395    fn new(id: usize, numa_load_avg: f64) -> Self {
396        Self {
397            id,
398            load: LoadEntity::new(
399                NumaNode::LOAD_IMBAL_HIGH_RATIO,
400                NumaNode::LOAD_IMBAL_PUSH_MAX_RATIO,
401                NumaNode::LOAD_IMBAL_XFER_TARGET_RATIO,
402                0.0f64,
403                numa_load_avg,
404            ),
405            domains: SortedVec::new(),
406        }
407    }
408
409    fn allocate_domain(&mut self, id: usize, load: f64, dom_load_avg: f64) {
410        let domain = Domain::new(id, load, dom_load_avg);
411
412        self.insert_domain(domain);
413        self.load.rebalance(self.load.load_sum() + load);
414    }
415
416    fn xfer_between(&self, other: &NumaNode) -> f64 {
417        self.load.xfer_between(&other.load)
418    }
419
420    fn insert_domain(&mut self, domain: Domain) {
421        self.domains.insert(domain);
422    }
423
424    fn update_load(&mut self, delta: f64) {
425        self.load.add_load(delta);
426    }
427
428    fn stats(&self) -> NodeStats {
429        let mut stats = NodeStats::new(
430            self.load.load_sum(),
431            self.load.imbal(),
432            self.load.delta(),
433            BTreeMap::new(),
434        );
435        for dom in self.domains.iter() {
436            stats.doms.insert(
437                dom.id,
438                DomainStats::new(dom.load.load_sum(), dom.load.imbal(), dom.load.delta()),
439            );
440        }
441        stats
442    }
443}
444
445impl LoadOrdered for NumaNode {
446    fn get_load(&self) -> OrderedFloat<f64> {
447        self.load.load_sum
448    }
449}
450impl_ord_for_type!(NumaNode);
451
452pub struct LoadBalancer<'a, 'b> {
453    skel: &'a mut BpfSkel<'b>,
454    dom_group: Arc<DomainGroup>,
455    skip_kworkers: bool,
456
457    infeas_threshold: f64,
458
459    nodes: SortedVec<NumaNode>,
460
461    lb_apply_weight: bool,
462    balance_load: bool,
463}
464
465// Verify that the number of buckets is a factor of the maximum weight to
466// ensure that the range of weight can be split evenly amongst every bucket.
467const_assert_eq!(
468    bpf_intf::consts_LB_MAX_WEIGHT % bpf_intf::consts_LB_LOAD_BUCKETS,
469    0
470);
471
472impl<'a, 'b> LoadBalancer<'a, 'b> {
473    pub fn new(
474        skel: &'a mut BpfSkel<'b>,
475        dom_group: Arc<DomainGroup>,
476        skip_kworkers: bool,
477        lb_apply_weight: bool,
478        balance_load: bool,
479    ) -> Self {
480        Self {
481            skel,
482            skip_kworkers,
483
484            infeas_threshold: bpf_intf::consts_LB_MAX_WEIGHT as f64,
485
486            nodes: SortedVec::new(),
487
488            lb_apply_weight,
489            balance_load,
490
491            dom_group,
492        }
493    }
494
495    /// Perform load balancing calculations. When load balancing is enabled,
496    /// also perform rebalances between NUMA nodes (when running on a
497    /// multi-socket host) and domains.
498    pub fn load_balance(&mut self) -> Result<()> {
499        self.create_domain_hierarchy()?;
500
501        if self.balance_load {
502            self.perform_balancing()?
503        }
504
505        Ok(())
506    }
507
508    pub fn get_stats(&self) -> BTreeMap<usize, NodeStats> {
509        let mut stats = BTreeMap::new();
510        for node in self.nodes.iter() {
511            stats.insert(node.id, node.stats());
512        }
513        stats
514    }
515
516    fn create_domain_hierarchy(&mut self) -> Result<()> {
517        let ledger = self.calculate_load_avgs()?;
518
519        let (dom_loads, total_load) = if !self.lb_apply_weight {
520            (
521                ledger
522                    .dom_dcycle_sums()
523                    .iter()
524                    .copied()
525                    .map(|d| DEFAULT_WEIGHT * d)
526                    .collect(),
527                DEFAULT_WEIGHT * ledger.global_dcycle_sum(),
528            )
529        } else {
530            self.infeas_threshold = ledger.effective_max_weight();
531            (ledger.dom_load_sums().to_vec(), ledger.global_load_sum())
532        };
533
534        let num_numa_nodes = self.dom_group.nr_nodes();
535        let numa_load_avg = total_load / num_numa_nodes as f64;
536
537        let mut nodes: Vec<NumaNode> = Vec::with_capacity(num_numa_nodes);
538        for id in 0..num_numa_nodes {
539            nodes.push(NumaNode::new(id, numa_load_avg));
540        }
541
542        let dom_load_avg = total_load / dom_loads.len() as f64;
543        for (dom_id, load) in dom_loads.iter().enumerate() {
544            let numa_id = self.dom_group.dom_numa_id(&dom_id).unwrap();
545
546            if numa_id >= num_numa_nodes {
547                bail!("NUMA ID {} exceeds maximum {}", numa_id, num_numa_nodes);
548            }
549
550            let node = &mut nodes[numa_id];
551            node.allocate_domain(dom_id, *load, dom_load_avg);
552        }
553
554        for _ in 0..num_numa_nodes {
555            self.nodes.insert(nodes.pop().unwrap());
556        }
557
558        Ok(())
559    }
560
561    fn calculate_load_avgs(&mut self) -> Result<LoadLedger> {
562        const NUM_BUCKETS: u64 = bpf_intf::consts_LB_LOAD_BUCKETS as u64;
563        let now_mono = now_monotonic();
564        let load_half_life = self.skel.maps.rodata_data.load_half_life;
565
566        let mut aggregator =
567            LoadAggregator::new(self.dom_group.weight(), !self.lb_apply_weight.clone());
568
569        for (dom_id, dom) in self.dom_group.doms() {
570            aggregator.init_domain(*dom_id);
571
572            let dom_ctx = dom.ctx().unwrap();
573
574            for bucket in 0..NUM_BUCKETS {
575                let bucket_ctx = &dom_ctx.buckets[bucket as usize];
576                let rd = &bucket_ctx.rd;
577                let duty_cycle = ravg_read(
578                    rd.val,
579                    rd.val_at,
580                    rd.old,
581                    rd.cur,
582                    now_mono,
583                    load_half_life,
584                    RAVG_FRAC_BITS,
585                );
586
587                if duty_cycle == 0.0f64 {
588                    continue;
589                }
590
591                let weight = self.bucket_weight(bucket);
592                aggregator.record_dom_load(*dom_id, weight, duty_cycle)?;
593            }
594        }
595
596        Ok(aggregator.calculate())
597    }
598
599    fn bucket_range(&self, bucket: u64) -> (f64, f64) {
600        const MAX_WEIGHT: u64 = bpf_intf::consts_LB_MAX_WEIGHT as u64;
601        const NUM_BUCKETS: u64 = bpf_intf::consts_LB_LOAD_BUCKETS as u64;
602        const WEIGHT_PER_BUCKET: u64 = MAX_WEIGHT / NUM_BUCKETS;
603
604        if bucket >= NUM_BUCKETS {
605            panic!("Invalid bucket {}, max {}", bucket, NUM_BUCKETS);
606        }
607
608        // w_x = [1 + (10000 * x) / N, 10000 * (x + 1) / N]
609        let min_w = 1 + (MAX_WEIGHT * bucket) / NUM_BUCKETS;
610        let max_w = min_w + WEIGHT_PER_BUCKET - 1;
611
612        (min_w as f64, max_w as f64)
613    }
614
615    fn bucket_weight(&self, bucket: u64) -> usize {
616        const WEIGHT_PER_BUCKET: f64 = bpf_intf::consts_LB_WEIGHT_PER_BUCKET as f64;
617        let (min_weight, _) = self.bucket_range(bucket);
618
619        // Use the mid-point of the bucket when determining weight
620        (min_weight + (WEIGHT_PER_BUCKET / 2.0f64)).ceil() as usize
621    }
622
623    /// @dom needs to push out tasks to balance loads. Make sure its
624    /// tasks_by_load is populated so that the victim tasks can be picked.
625    fn populate_tasks_by_load(&mut self, dom: &mut Domain) -> Result<()> {
626        if dom.queried_tasks {
627            return Ok(());
628        }
629        dom.queried_tasks = true;
630
631        // Read active_tasks and update read_idx and gen.
632        const MAX_TPTRS: u64 = bpf_intf::consts_MAX_DOM_ACTIVE_TPTRS as u64;
633        let dom_ctx = unsafe { &mut *self.skel.maps.bss_data.dom_ctxs[dom.id] };
634        let active_tasks = &mut dom_ctx.active_tasks;
635
636        let (mut ridx, widx) = (active_tasks.read_idx, active_tasks.write_idx);
637        active_tasks.read_idx = active_tasks.write_idx;
638        active_tasks.genn += 1;
639
640        if widx - ridx > MAX_TPTRS {
641            ridx = widx - MAX_TPTRS;
642        }
643
644        // Read task_ctx and load.
645        let load_half_life = self.skel.maps.rodata_data.load_half_life;
646        let now_mono = now_monotonic();
647
648        for idx in ridx..widx {
649            let taskc_p = active_tasks.tasks[(idx % MAX_TPTRS) as usize];
650            let taskc = unsafe { &mut *taskc_p };
651
652            if taskc.target_dom as usize != dom.id {
653                continue;
654            }
655
656            let rd = &taskc.dcyc_rd;
657            let mut load = ravg_read(
658                rd.val,
659                rd.val_at,
660                rd.old,
661                rd.cur,
662                now_mono,
663                load_half_life,
664                RAVG_FRAC_BITS,
665            );
666
667            let weight = if self.lb_apply_weight {
668                (taskc.weight as f64).min(self.infeas_threshold)
669            } else {
670                DEFAULT_WEIGHT
671            };
672            load *= weight;
673
674            dom.tasks.insert(TaskInfo {
675                taskc_p,
676                load: OrderedFloat(load),
677                dom_mask: taskc.dom_mask,
678                preferred_dom_mask: taskc.preferred_dom_mask,
679                migrated: Cell::new(false),
680                is_kworker: unsafe { taskc.is_kworker.assume_init() },
681            });
682        }
683
684        Ok(())
685    }
686
687    // Find the first candidate task which hasn't already been migrated and
688    // can run in @pull_dom.
689    fn find_first_candidate<'d, I>(tasks_by_load: I) -> Option<&'d TaskInfo>
690    where
691        I: IntoIterator<Item = &'d TaskInfo>,
692    {
693        match tasks_by_load.into_iter().next() {
694            Some(task) => Some(task),
695            None => None,
696        }
697    }
698
699    /// Try to find a task in @push_dom to be moved into @pull_dom. If a task is
700    /// found, move the task between the domains, and return the amount of load
701    /// transferred between the two.
702    fn try_find_move_task(
703        &mut self,
704        (push_dom, to_push): (&mut Domain, f64),
705        (pull_dom, to_pull): (&mut Domain, f64),
706        task_filter: impl Fn(&TaskInfo, u32) -> bool,
707        to_xfer: f64,
708    ) -> Result<Option<f64>> {
709        let to_pull = to_pull.abs();
710        let calc_new_imbal = |xfer: f64| (to_push - xfer).abs() + (to_pull - xfer).abs();
711
712        self.populate_tasks_by_load(push_dom)?;
713
714        // We want to pick a task to transfer from push_dom to pull_dom to
715        // reduce the load imbalance between the two closest to $to_xfer.
716        // IOW, pick a task which has the closest load value to $to_xfer
717        // that can be migrated. Find such task by locating the first
718        // migratable task while scanning left from $to_xfer and the
719        // counterpart while scanning right and picking the better of the
720        // two.
721        let pull_dom_id: u32 = pull_dom.id.try_into().unwrap();
722        let tasks: Vec<TaskInfo> = std::mem::take(&mut push_dom.tasks)
723            .into_vec()
724            .into_iter()
725            .filter(|task| {
726                task.dom_mask & (1 << pull_dom_id) != 0
727                    && !(self.skip_kworkers && task.is_kworker)
728                    && !task.migrated.get()
729            })
730            .collect();
731
732        let (task, new_imbal) = match (
733            Self::find_first_candidate(
734                tasks
735                    .as_slice()
736                    .iter()
737                    .filter(|x| x.load <= OrderedFloat(to_xfer) && task_filter(x, pull_dom_id))
738                    .rev(),
739            ),
740            Self::find_first_candidate(
741                tasks
742                    .as_slice()
743                    .iter()
744                    .filter(|x| x.load >= OrderedFloat(to_xfer) && task_filter(x, pull_dom_id)),
745            ),
746        ) {
747            (None, None) => {
748                std::mem::swap(&mut push_dom.tasks, &mut SortedVec::from_unsorted(tasks));
749                return Ok(None);
750            }
751            (Some(task), None) | (None, Some(task)) => (task, calc_new_imbal(*task.load)),
752            (Some(task0), Some(task1)) => {
753                let (new_imbal0, new_imbal1) =
754                    (calc_new_imbal(*task0.load), calc_new_imbal(*task1.load));
755                if new_imbal0 <= new_imbal1 {
756                    (task0, new_imbal0)
757                } else {
758                    (task1, new_imbal1)
759                }
760            }
761        };
762
763        // If the best candidate can't reduce the imbalance, there's nothing
764        // to do for this pair.
765        let old_imbal = to_push + to_pull;
766        if old_imbal < new_imbal {
767            std::mem::swap(&mut push_dom.tasks, &mut SortedVec::from_unsorted(tasks));
768            return Ok(None);
769        }
770
771        let load = *(task.load);
772        let taskc_p = task.taskc_p;
773        task.migrated.set(true);
774        std::mem::swap(&mut push_dom.tasks, &mut SortedVec::from_unsorted(tasks));
775
776        push_dom.transfer_load(load, unsafe { &mut *taskc_p }, pull_dom);
777        Ok(Some(load))
778    }
779
780    fn transfer_between_nodes(
781        &mut self,
782        push_node: &mut NumaNode,
783        pull_node: &mut NumaNode,
784    ) -> Result<f64> {
785        debug!("Inter node {} -> {} started", push_node.id, pull_node.id);
786
787        let push_imbal = push_node.load.imbal();
788        let pull_imbal = pull_node.load.imbal();
789        let xfer = push_node.xfer_between(pull_node);
790
791        if push_imbal <= 0.0f64 || pull_imbal >= 0.0f64 {
792            bail!(
793                "push node {}:{}, pull node {}:{}",
794                push_node.id,
795                push_imbal,
796                pull_node.id,
797                pull_imbal
798            );
799        }
800        let mut pushers = VecDeque::with_capacity(push_node.domains.len());
801        let mut pullers = Vec::with_capacity(pull_node.domains.len());
802        let mut pushed = 0f64;
803
804        while push_node.domains.len() > 0 {
805            // Push from the busiest node
806            let mut push_dom = push_node.domains.pop().unwrap();
807            if push_dom.load.state() != BalanceState::NeedsPush {
808                push_node.domains.insert(push_dom);
809                break;
810            }
811
812            while pull_node.domains.len() > 0 {
813                let mut pull_dom = pull_node.domains.remove_index(0);
814                if pull_dom.load.state() != BalanceState::NeedsPull {
815                    pull_node.domains.insert(pull_dom);
816                    break;
817                }
818                let mut transferred = self.try_find_move_task(
819                    (&mut push_dom, push_imbal),
820                    (&mut pull_dom, pull_imbal),
821                    |task: &TaskInfo, pull_dom: u32| -> bool {
822                        (task.preferred_dom_mask & (1 << pull_dom)) > 0
823                    },
824                    xfer,
825                )?;
826                if transferred.is_none() {
827                    transferred = self.try_find_move_task(
828                        (&mut push_dom, push_imbal),
829                        (&mut pull_dom, pull_imbal),
830                        |_task: &TaskInfo, _pull_dom: u32| -> bool { true },
831                        xfer,
832                    )?;
833                }
834
835                pullers.push(pull_dom);
836                if let Some(transferred) = transferred {
837                    pushed = transferred;
838                    push_node.update_load(-transferred);
839                    pull_node.update_load(transferred);
840                    break;
841                }
842            }
843            while let Some(puller) = pullers.pop() {
844                pull_node.domains.insert(puller);
845            }
846            pushers.push_back(push_dom);
847            if pushed > 0.0f64 {
848                break;
849            }
850        }
851        while let Some(pusher) = pushers.pop_front() {
852            push_node.domains.insert(pusher);
853        }
854
855        Ok(pushed)
856    }
857
858    fn balance_between_nodes(&mut self) -> Result<()> {
859        if self.nodes.len() < 2 {
860            return Ok(());
861        }
862
863        debug!("Node <-> Node LB started");
864
865        // Keep track of the nodes we're pushing load from, and pulling load to,
866        // respectively. We use separate vectors like this to allow us to
867        // mutably iterate over the same list, and pull nodes from the front and
868        // back in a nested fashion. The load algorithm looks roughly like this:
869        //
870        // In sorted order from most -> least loaded:
871        //
872        // For each "push node" (i.e. node with a positive load imbalance):
873        // restart_push:
874        //      For each "pull node" (i.e. node with a negative load imbalance):
875        //              For each "push domain" (i.e. each domain in "push node"
876        //              with a positive load imbalance):
877        //                      For each "pull domain" (i.e. each domain in
878        //                      "pull node" with a negative load imbalance):
879        //                              load = try_move_load(push_dom -> pull-dom)
880        //                              if load > 0
881        //                                      goto restart_pushext_pull
882        //
883        // There are four levels of nesting here, but in practice these are very
884        // shallow loops, as a system doesn't usually have many nodes or domains
885        // per node, only a subset of them will be imbalanced, and the
886        // imbalanced nodes and domains will only ever be in push imbalance, or
887        // pull imbalance at any given time.
888        //
889        // Because we're iterating mutably over these lists, we pop nodes and
890        // domains off of their lists, and then re-insert them after we're done
891        // doing migrations. The lists below are how we keep track of
892        // already-visited nodes while we're still iterating over the lists.
893        // Note that we immediately go back to iterating over every pull node
894        // any time we successfully transfer load, so that we ensure that we're
895        // always sending load to the least-loaded node.
896        //
897        // Note that we use a VecDeque for the pushers because we're iterating
898        // over self.nodes in descending-load order. Thus, when we're done
899        // iterating and we're adding the popped nodes back into self.nodes, we
900        // want to add them back in _ascending_ order so that we don't have to
901        // unnecessarily shift any already-re-added nodes to the right in the
902        // backing vector. In other words, this lets us do a true append in the
903        // SortedVec, rather than doing an insert(list.len() - 2, node). This
904        // applies both to iterating over push-imbalanced nodes, and iterating
905        // over push-imbalanced domains in the inner loops.
906        let mut pushers = VecDeque::with_capacity(self.nodes.len());
907        let mut pullers = Vec::with_capacity(self.nodes.len());
908
909        while self.nodes.len() >= 2 {
910            // Push from the busiest node
911            let mut push_node = self.nodes.pop().unwrap();
912            if push_node.load.state() != BalanceState::NeedsPush {
913                self.nodes.insert(push_node);
914                break;
915            }
916
917            let push_cutoff = push_node.load.push_cutoff();
918            let mut pushed = 0f64;
919            while self.nodes.len() > 0 && pushed < push_cutoff {
920                // To the least busy node
921                let mut pull_node = self.nodes.remove_index(0);
922                let pull_id = pull_node.id;
923                if pull_node.load.state() != BalanceState::NeedsPull {
924                    self.nodes.insert(pull_node);
925                    break;
926                }
927                let migrated = self.transfer_between_nodes(&mut push_node, &mut pull_node)?;
928                pullers.push(pull_node);
929                if migrated > 0.0f64 {
930                    // Break after a successful migration so that we can
931                    // rebalance the pulling domains before the next
932                    // transfer attempt, and ensure that we're trying to
933                    // pull from domains in descending-imbalance order.
934                    pushed += migrated;
935                    debug!(
936                        "NODE {} sending {:.06} --> NODE {}",
937                        push_node.id, migrated, pull_id
938                    );
939                }
940            }
941            while let Some(puller) = pullers.pop() {
942                self.nodes.insert(puller);
943            }
944
945            if pushed > 0.0f64 {
946                debug!("NODE {} pushed {:.06} total load", push_node.id, pushed);
947            }
948            pushers.push_back(push_node);
949        }
950
951        while let Some(pusher) = pushers.pop_front() {
952            self.nodes.insert(pusher);
953        }
954
955        Ok(())
956    }
957
958    fn balance_within_node(&mut self, node: &mut NumaNode) -> Result<()> {
959        if node.domains.len() < 2 {
960            return Ok(());
961        }
962
963        debug!("Intra node {} LB started", node.id);
964
965        // See the comment in balance_between_nodes() for the purpose of these
966        // lists. Everything is roughly the same here as in that comment block,
967        // with the notable exception that we're only iterating over domains
968        // inside of a single node.
969        let mut pushers = VecDeque::with_capacity(node.domains.len());
970        let mut pullers = Vec::new();
971
972        while node.domains.len() >= 2 {
973            let mut push_dom = node.domains.pop().unwrap();
974            if node.domains.len() == 0 || push_dom.load.state() != BalanceState::NeedsPush {
975                node.domains.insert(push_dom);
976                break;
977            }
978
979            let mut pushed = 0.0f64;
980            let push_cutoff = push_dom.load.push_cutoff();
981            let push_imbal = push_dom.load.imbal();
982            if push_imbal < 0.0f64 {
983                bail!(
984                    "Node {} push dom {} had imbal {}",
985                    node.id,
986                    push_dom.id,
987                    push_imbal
988                );
989            }
990
991            while node.domains.len() > 0 && pushed < push_cutoff {
992                let mut pull_dom = node.domains.remove_index(0);
993                if pull_dom.load.state() != BalanceState::NeedsPull {
994                    node.domains.push(pull_dom);
995                    break;
996                }
997                let pull_imbal = pull_dom.load.imbal();
998                if pull_imbal >= 0.0f64 {
999                    bail!(
1000                        "Node {} pull dom {} had imbal {}",
1001                        node.id,
1002                        pull_dom.id,
1003                        pull_imbal
1004                    );
1005                }
1006                let xfer = push_dom.xfer_between(&pull_dom);
1007                let mut transferred = self.try_find_move_task(
1008                    (&mut push_dom, push_imbal),
1009                    (&mut pull_dom, pull_imbal),
1010                    |task: &TaskInfo, pull_dom: u32| -> bool {
1011                        (task.preferred_dom_mask & (1 << pull_dom)) > 0
1012                    },
1013                    xfer,
1014                )?;
1015                if transferred.is_none() {
1016                    transferred = self.try_find_move_task(
1017                        (&mut push_dom, push_imbal),
1018                        (&mut pull_dom, pull_imbal),
1019                        |_task: &TaskInfo, _pull_dom: u32| -> bool { true },
1020                        xfer,
1021                    )?;
1022                }
1023
1024                if let Some(transferred) = transferred {
1025                    if transferred <= 0.0f64 {
1026                        bail!("Expected nonzero load transfer")
1027                    }
1028                    pushed += transferred;
1029                    // We've pushed load to pull_dom, and have already updated
1030                    // its load (in try_find_move_task()). Re-insert it into the
1031                    // sorted list (thus ensuring we're still iterating from
1032                    // least load -> most load in the loop above), and try to
1033                    // push more load.
1034                    node.domains.insert(pull_dom);
1035                    continue;
1036                }
1037
1038                // Couldn't push any load to this domain, try the next one.
1039                pullers.push(pull_dom);
1040            }
1041            while let Some(puller) = pullers.pop() {
1042                node.domains.insert(puller);
1043            }
1044
1045            if pushed > 0.0f64 {
1046                debug!("DOM {} pushed {:.06} total load", push_dom.id, pushed);
1047            }
1048            pushers.push_back(push_dom);
1049        }
1050        while let Some(pusher) = pushers.pop_front() {
1051            node.domains.insert(pusher);
1052        }
1053
1054        Ok(())
1055    }
1056
1057    fn perform_balancing(&mut self) -> Result<()> {
1058        // First balance load between the NUMA nodes. Balancing here has a
1059        // higher cost function than balancing between domains inside of NUMA
1060        // nodes, but the mechanics are the same. Adjustments made here are
1061        // reflected in intra-node balancing decisions made next.
1062        if self.dom_group.nr_nodes() > 1 {
1063            self.balance_between_nodes()?;
1064        }
1065
1066        // Now that the NUMA nodes have been balanced, do another balance round
1067        // amongst the domains in each node.
1068
1069        debug!("Intra node LBs started");
1070
1071        // Assume all nodes are now balanced.
1072
1073        let mut nodes = std::mem::take(&mut self.nodes).into_vec();
1074        for node in nodes.iter_mut() {
1075            self.balance_within_node(node)?;
1076        }
1077        std::mem::swap(&mut self.nodes, &mut SortedVec::from_unsorted(nodes));
1078
1079        Ok(())
1080    }
1081}