Skip to main content

scx_mavd/
cpu_order.rs

1// SPDX-License-Identifier: GPL-2.0
2//
3// Copyright (c) 2025 Valve Corporation.
4// Author: Changwoo Min <changwoo@igalia.com>
5
6// This software may be used and distributed according to the terms of the
7// GNU General Public License version 2.
8
9use anyhow::Result;
10use anyhow::anyhow;
11use itertools::Itertools;
12use itertools::iproduct;
13use scx_utils::CoreType;
14use scx_utils::Cpumask;
15use scx_utils::EnergyModel;
16use scx_utils::NR_CPU_IDS;
17use scx_utils::PerfDomain;
18use scx_utils::PerfState;
19use scx_utils::Topology;
20use std::cell::Cell;
21use std::cell::RefCell;
22use std::collections::BTreeMap;
23use std::collections::BTreeSet;
24use std::collections::HashSet;
25use std::fmt;
26use std::hash::{Hash, Hasher};
27use tracing::debug;
28use tracing::warn;
29
30#[derive(Debug, Clone)]
31pub struct CpuId {
32    // - *_adx: an absolute index within a system scope
33    // - *_rdx: a relative index under a parent
34    //
35    // - numa_adx: a NUMA domain within a system
36    // - pd_adx: a performance domain (CPU frequency domain) within a system
37    //   - llc_rdx: an LLC domain (CCX) under a NUMA domain
38    //   - llc_kernel_id: physical LLC domain ID provided by the kernel
39    //     - core_rdx: a core under a LLC domain
40    //       - cpu_rdx: a CPU under a core
41    pub numa_adx: usize,
42    pub pd_adx: usize,
43    pub llc_adx: usize,
44    pub llc_rdx: usize,
45    pub llc_kernel_id: usize,
46    pub core_rdx: usize,
47    pub cpu_rdx: usize,
48    pub cpu_adx: usize,
49    pub smt_level: usize,
50    pub cache_size: usize,
51    pub cpu_cap: usize,
52    pub big_core: bool,
53    pub turbo_core: bool,
54}
55
56#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
57pub struct ComputeDomainId {
58    pub numa_adx: usize,
59    pub llc_adx: usize,
60    pub llc_rdx: usize,
61    pub llc_kernel_id: usize,
62    pub is_big: bool,
63}
64
65#[derive(Debug, Clone)]
66pub struct ComputeDomain {
67    pub cpdom_id: usize,
68    pub cpdom_alt_id: Cell<usize>,
69    pub cpu_ids: Vec<usize>,
70    pub neighbor_map: RefCell<BTreeMap<usize, RefCell<Vec<usize>>>>,
71}
72
73#[derive(Debug, Clone)]
74#[allow(dead_code)]
75pub struct PerfCpuOrder {
76    pub perf_cap: usize,                 // performance in capacity
77    pub perf_util: f32,                  // performance in utilization, [0, 1]
78    pub cpus_perf: RefCell<Vec<usize>>,  // CPU adx order within the performance range by @perf_cap
79    pub cpus_ovflw: RefCell<Vec<usize>>, // CPU adx order beyond @perf_cap
80}
81
82#[derive(Debug)]
83#[allow(dead_code)]
84pub struct CpuOrder {
85    pub all_cpus_mask: Cpumask,
86    pub cpuids: Vec<CpuId>,
87    pub perf_cpu_order: BTreeMap<usize, PerfCpuOrder>,
88    pub cpdom_map: BTreeMap<ComputeDomainId, ComputeDomain>,
89    pub nr_cpus: usize,
90    pub nr_cores: usize,
91    pub nr_cpdoms: usize,
92    pub nr_llcs: usize,
93    pub nr_numa: usize,
94    pub smt_enabled: bool,
95    pub has_biglittle: bool,
96    pub has_energy_model: bool,
97}
98
99impl CpuOrder {
100    /// Build a cpu preference order with optional topology configuration.
101    /// When @no_use_em is set, ignore the energy model even if the kernel
102    /// provides one, so the CPU preference order is built as on a machine
103    /// without an energy model.
104    pub fn new(
105        topology_args: Option<&scx_utils::TopologyArgs>,
106        no_use_em: bool,
107    ) -> Result<CpuOrder> {
108        let ctx = CpuOrderCtx::new(topology_args, no_use_em)?;
109        let cpus_pf = ctx.build_topo_order(false).unwrap();
110        let cpus_ps = ctx.build_topo_order(true).unwrap();
111        let cpdom_map = CpuOrderCtx::build_cpdom(&cpus_pf).unwrap();
112        let perf_cpu_order = if ctx.em.is_ok() {
113            let em = ctx.em.unwrap();
114            EnergyModelOptimizer::get_perf_cpu_order_table(&em, &cpus_pf)
115        } else {
116            EnergyModelOptimizer::get_fake_perf_cpu_order_table(&cpus_pf, &cpus_ps)
117        };
118
119        let nr_cpdoms = cpdom_map.len();
120        Ok(CpuOrder {
121            all_cpus_mask: ctx.topo.span,
122            cpuids: cpus_pf,
123            perf_cpu_order,
124            cpdom_map,
125            nr_cpus: ctx.topo.all_cpus.len(),
126            nr_cores: ctx.topo.all_cores.len(),
127            nr_cpdoms,
128            nr_llcs: ctx.topo.all_llcs.len(),
129            nr_numa: ctx.topo.nodes.len(),
130            smt_enabled: ctx.smt_enabled,
131            has_biglittle: ctx.has_biglittle,
132            has_energy_model: ctx.has_energy_model,
133        })
134    }
135}
136
137/// CpuOrderCtx is a helper struct used to build a CpuOrder
138struct CpuOrderCtx {
139    topo: Topology,
140    em: Result<EnergyModel>,
141    smt_enabled: bool,
142    has_biglittle: bool,
143    has_energy_model: bool,
144}
145
146impl CpuOrderCtx {
147    fn new(topology_args: Option<&scx_utils::TopologyArgs>, no_use_em: bool) -> Result<Self> {
148        let topo = match topology_args {
149            Some(args) => Topology::with_args(args)?,
150            None => Topology::new()?,
151        };
152
153        let em = if no_use_em {
154            Err(anyhow!("energy model disabled (--no-use-em)"))
155        } else {
156            EnergyModel::new()
157        };
158        let smt_enabled = topo.smt_enabled;
159        let has_biglittle = topo.has_little_cores();
160        let has_energy_model = em.is_ok();
161
162        debug!("{:#?}", topo);
163        debug!("{:#?}", em);
164
165        Ok(CpuOrderCtx {
166            topo,
167            em,
168            smt_enabled,
169            has_biglittle,
170            has_energy_model,
171        })
172    }
173
174    /// Build a CPU preference order based on its optimization target
175    fn build_topo_order(&self, prefer_powersave: bool) -> Option<Vec<CpuId>> {
176        let mut cpu_ids = Vec::new();
177
178        // Build a vector of cpu ids.
179        for (&numa_adx, node) in self.topo.nodes.iter() {
180            for (llc_rdx, (&llc_adx, llc)) in node.llcs.iter().enumerate() {
181                for (core_rdx, (_core_adx, core)) in llc.cores.iter().enumerate() {
182                    for (cpu_rdx, (cpu_adx, cpu)) in core.cpus.iter().enumerate() {
183                        let cpu_adx = *cpu_adx;
184                        let pd_adx = Self::get_pd_id(&self.em, cpu_adx, llc_adx);
185                        let cpu_id = CpuId {
186                            numa_adx,
187                            pd_adx,
188                            llc_adx,
189                            llc_rdx,
190                            core_rdx,
191                            cpu_rdx,
192                            cpu_adx,
193                            smt_level: cpu.smt_level,
194                            cache_size: cpu.cache_size,
195                            cpu_cap: cpu.cpu_capacity,
196                            big_core: cpu.core_type != CoreType::Little,
197                            turbo_core: cpu.core_type == CoreType::Big { turbo: true },
198                            llc_kernel_id: llc.kernel_id,
199                        };
200                        cpu_ids.push(RefCell::new(cpu_id));
201                    }
202                }
203            }
204        }
205
206        // Convert a vector of RefCell to a vector of plain cpu_ids
207        let mut cpu_ids2 = Vec::new();
208        for cpu_id in cpu_ids.iter() {
209            cpu_ids2.push(cpu_id.borrow().clone());
210        }
211        let mut cpu_ids = cpu_ids2;
212
213        // Sort the cpu_ids
214        match (prefer_powersave, self.has_biglittle) {
215            // 1. powersave,      no  big/little
216            //     * within the same LLC domain
217            //         - numa_adx, llc_rdx,
218            //     * prefer more capable CPU with higher capacity
219            //       and larger cache
220            //         - ^cpu_cap (chip binning), ^cache_size,
221            //     * prefer the SMT core within the same performance domain
222            //         - pd_adx, core_rdx, ^smt_level, cpu_rdx
223            (true, false) => {
224                cpu_ids.sort_by(|a, b| {
225                    a.numa_adx
226                        .cmp(&b.numa_adx)
227                        .then_with(|| a.llc_rdx.cmp(&b.llc_rdx))
228                        .then_with(|| b.cpu_cap.cmp(&a.cpu_cap))
229                        .then_with(|| b.cache_size.cmp(&a.cache_size))
230                        .then_with(|| a.pd_adx.cmp(&b.pd_adx))
231                        .then_with(|| a.core_rdx.cmp(&b.core_rdx))
232                        .then_with(|| b.smt_level.cmp(&a.smt_level))
233                        .then_with(|| a.cpu_rdx.cmp(&b.cpu_rdx))
234                        .then_with(|| a.cpu_adx.cmp(&b.cpu_adx))
235                });
236            }
237            // 2. powersave,      yes big/little
238            //     * within the same LLC domain
239            //         - numa_adx, llc_rdx,
240            //     * prefer energy-efficient LITTLE CPU with a larger cache
241            //         - cpu_cap (big/little), ^cache_size,
242            //     * prefer the SMT core within the same performance domain
243            //         - pd_adx, core_rdx, ^smt_level, cpu_rdx
244            (true, true) => {
245                cpu_ids.sort_by(|a, b| {
246                    a.numa_adx
247                        .cmp(&b.numa_adx)
248                        .then_with(|| a.llc_rdx.cmp(&b.llc_rdx))
249                        .then_with(|| a.cpu_cap.cmp(&b.cpu_cap))
250                        .then_with(|| b.cache_size.cmp(&a.cache_size))
251                        .then_with(|| a.pd_adx.cmp(&b.pd_adx))
252                        .then_with(|| a.core_rdx.cmp(&b.core_rdx))
253                        .then_with(|| b.smt_level.cmp(&a.smt_level))
254                        .then_with(|| a.cpu_rdx.cmp(&b.cpu_rdx))
255                        .then_with(|| a.cpu_adx.cmp(&b.cpu_adx))
256                });
257            }
258            // 3. performance,    no  big/little
259            // 4. performance,    yes big/little
260            //     * prefer the non-SMT core
261            //         - cpu_rdx,
262            //     * fill the same LLC domain first
263            //         - numa_adx, llc_rdx,
264            //     * prefer more capable CPU with higher capacity
265            //       (chip binning or big/little) and larger cache
266            //         - ^cpu_cap, ^cache_size, smt_level
267            //     * within the same power domain
268            //         - pd_adx, core_rdx
269            _ => {
270                cpu_ids.sort_by(|a, b| {
271                    a.cpu_rdx
272                        .cmp(&b.cpu_rdx)
273                        .then_with(|| a.numa_adx.cmp(&b.numa_adx))
274                        .then_with(|| a.llc_rdx.cmp(&b.llc_rdx))
275                        .then_with(|| b.cpu_cap.cmp(&a.cpu_cap))
276                        .then_with(|| b.cache_size.cmp(&a.cache_size))
277                        .then_with(|| a.smt_level.cmp(&b.smt_level))
278                        .then_with(|| a.pd_adx.cmp(&b.pd_adx))
279                        .then_with(|| a.core_rdx.cmp(&b.core_rdx))
280                        .then_with(|| a.cpu_adx.cmp(&b.cpu_adx))
281                });
282            }
283        }
284
285        Some(cpu_ids)
286    }
287
288    /// Build a list of compute domains
289    fn build_cpdom(cpu_ids: &Vec<CpuId>) -> Option<BTreeMap<ComputeDomainId, ComputeDomain>> {
290        // Note that building compute domain is independent to CPU order
291        // so it is okay to use any cpus_*.
292
293        // Create a compute domain map, where a compute domain is a CPUs that
294        // are under the same node and LLC (virtual and physical) and have the same core type.
295        let mut cpdom_id = 0;
296        let mut cpdom_map: BTreeMap<ComputeDomainId, ComputeDomain> = BTreeMap::new();
297        let mut cpdom_types: BTreeMap<usize, bool> = BTreeMap::new();
298        for cpu_id in cpu_ids.iter() {
299            let key = ComputeDomainId {
300                numa_adx: cpu_id.numa_adx,
301                llc_adx: cpu_id.llc_adx,
302                llc_rdx: cpu_id.llc_rdx,
303                llc_kernel_id: cpu_id.llc_kernel_id,
304                is_big: cpu_id.big_core,
305            };
306            let value = cpdom_map.entry(key.clone()).or_insert_with(|| {
307                let val = ComputeDomain {
308                    cpdom_id,
309                    cpdom_alt_id: Cell::new(cpdom_id),
310                    cpu_ids: Vec::new(),
311                    neighbor_map: RefCell::new(BTreeMap::new()),
312                };
313                cpdom_types.insert(cpdom_id, key.is_big);
314
315                cpdom_id += 1;
316                val
317            });
318            value.cpu_ids.push(cpu_id.cpu_adx);
319        }
320
321        // Build a neighbor map for each compute domain, where neighbors are
322        // ordered by core type, node, and LLC.
323        for ((from_k, from_v), (to_k, to_v)) in iproduct!(cpdom_map.iter(), cpdom_map.iter()) {
324            if from_k == to_k {
325                continue;
326            }
327
328            let d = Self::dist(from_k, to_k);
329            let mut map = from_v.neighbor_map.borrow_mut();
330            match map.get(&d) {
331                Some(v) => {
332                    v.borrow_mut().push(to_v.cpdom_id);
333                }
334                None => {
335                    map.insert(d, RefCell::new(vec![to_v.cpdom_id]));
336                }
337            }
338        }
339
340        // Circular sort compute domains within the same distance to preserve
341        // proximity between domains.
342        //
343        // Suppose that domains 0, 1, 2, 3, 4, 5, 6, 7 are at the same distance.
344        //            0
345        //         7     1
346        //       6         2
347        //         5     3
348        //            4
349        //
350        // We want to traverse the domains from 0. The circular-sorted order
351        // starting from domain 0 is 0, 1, 7, 2, 6, 3, 5, 4. Similarly,
352        // the order starting from domain 1 is 1, 0, 2, 3, 7, 4, 6, 5.
353        // The one from 7 is 7, 0, 6, 1, 5, 2, 4, 3. As follows, circularly
354        // sorted orders in task stealing preserve proximity between domains
355        // (e.g., 0, 1, 7 in the example), so we can achieve less cacheline
356        // bouncing than with random-ordered task stealing.
357        for cpdom in cpdom_map.values() {
358            for neighbors in cpdom.neighbor_map.borrow_mut().values() {
359                let mut neighbors_csorted =
360                    Self::circular_sort(cpdom.cpdom_id, &neighbors.borrow_mut().to_vec());
361                neighbors.borrow_mut().clear();
362                neighbors.borrow_mut().append(&mut neighbors_csorted);
363            }
364        }
365
366        // Fill up cpdom_alt_id for each compute domain.
367        for (k, v) in cpdom_map.iter() {
368            let mut key = k.clone();
369            key.is_big = !k.is_big;
370
371            if let Some(alt_v) = cpdom_map.get(&key) {
372                // First, try to find an alternative domain
373                // under the same node/LLC.
374                v.cpdom_alt_id.set(alt_v.cpdom_id);
375            } else {
376                // If there is no alternative domain in the same node/LLC,
377                // choose the closest one.
378                //
379                // Note that currently, the idle CPU selection (pick_idle_cpu)
380                // is not optimized for this kind of architecture, where big
381                // and LITTLE cores are in different node/LLCs.
382                'outer: for ncpdoms in v.neighbor_map.borrow().values() {
383                    for ncpdom_id in ncpdoms.borrow().iter() {
384                        if let Some(is_big) = cpdom_types.get(ncpdom_id)
385                            && *is_big == key.is_big
386                        {
387                            v.cpdom_alt_id.set(*ncpdom_id);
388                            break 'outer;
389                        }
390                    }
391                }
392            }
393        }
394
395        Some(cpdom_map)
396    }
397
398    /// Circular sorting of a list from a starting point
399    fn circular_sort(start: usize, the_rest: &Vec<usize>) -> Vec<usize> {
400        // Create a full list including 'start'
401        let mut list = the_rest.clone();
402        list.push(start);
403        list.sort();
404
405        // Get the index of 'start'
406        let s = list
407            .binary_search(&start)
408            .expect("start must appear exactly once");
409
410        // Get the circularly sorted index list.
411        let n = list.len();
412        let dist = |x: usize| {
413            let d = (x + n - s) % n;
414            d.min(n - d)
415        };
416        let mut order: Vec<usize> = (0..n).collect();
417        order.sort_by_key(|&x| (dist(x), x));
418
419        // Rearrange the full list
420        // according to the circularly sorted index list.
421        let list_csorted: Vec<_> = order.iter().map(|&i| list[i]).collect();
422
423        // Drop 'start' from the rearranged full list.
424        list_csorted[1..].to_vec()
425    }
426
427    /// Get the performance domain (i.e., CPU frequency domain) ID for a CPU.
428    /// If the energy model is not available, use LLC ID instead.
429    fn get_pd_id(em: &Result<EnergyModel>, cpu_adx: usize, llc_adx: usize) -> usize {
430        match em {
431            Ok(em) => em.get_pd_by_cpu_id(cpu_adx).unwrap().id,
432            Err(_) => llc_adx,
433        }
434    }
435
436    /// Calculate distance from two compute domains
437    fn dist(from: &ComputeDomainId, to: &ComputeDomainId) -> usize {
438        let mut d = 0;
439        // core type > numa node > llc
440        if from.is_big != to.is_big {
441            d += 100;
442        }
443        if from.numa_adx != to.numa_adx {
444            d += 10;
445        } else {
446            if from.llc_rdx != to.llc_rdx {
447                d += 1;
448            }
449            if from.llc_kernel_id != to.llc_kernel_id {
450                d += 1;
451            }
452        }
453        d
454    }
455}
456
457#[derive(Debug)]
458struct EnergyModelOptimizer<'a> {
459    // The member performance domains of each equivalence performance domain of
460    // the energy model. Both the equivalence performance domains and their
461    // members are in CPU preference order, so taking N CPUs from an equivalence
462    // performance domain takes the N most preferred ones.
463    eq_pds: Vec<Vec<&'a PerfDomain>>,
464
465    // How many CPUs to take from each equivalence performance domain, for
466    // every combination worth considering. The i-th count belongs to
467    // @eq_pds[i]. It depends only on the CPU count of each equivalence
468    // performance domain, not on the CPU utilization, so it is enumerated once
469    // here.
470    //
471    // For example, when @em has two equivalence performance domains, one of
472    // 2 P-cores and one of 3 E-cores, the (2 + 1) * (3 + 1) - 1 = 11
473    // combinations are:
474    //
475    //     [0, 1] -- 1 E-core
476    //     [0, 2] -- 2 E-cores
477    //     [0, 3] -- 3 E-cores
478    //     [1, 0] -- 1 P-core
479    //     [1, 1] -- 1 P-core and 1 E-core
480    //     ...
481    //     [2, 2] -- 2 P-cores and 2 E-cores
482    //     [2, 3] -- 2 P-cores and 3 E-cores
483    nr_cpus_combinations: Vec<Vec<usize>>,
484
485    // CPU preference order in a performance mode purely based on topology
486    cpus_topological_order: Vec<usize>,
487
488    // CPU preference order within a performance domain
489    pd_cpu_order: BTreeMap<usize, RefCell<Vec<usize>>>,
490
491    // Total performance capacity of the system
492    tot_perf: usize,
493
494    // All possible combinations of performance domains & states
495    // indexed by performance.
496    pdss_infos: RefCell<BTreeMap<usize, RefCell<HashSet<PDSetInfo<'a>>>>>,
497
498    // Performance domains and states to achieve a certain performance level,
499    // which is derived from @pdss_infos.
500    perf_pdsi: RefCell<BTreeMap<usize, PDSetInfo<'a>>>,
501
502    // CPU orders indexed by performance
503    perf_cpu_order: RefCell<BTreeMap<usize, PerfCpuOrder>>,
504}
505
506#[allow(clippy::upper_case_acronyms)]
507#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
508struct PDS<'a> {
509    pd: &'a PerfDomain,
510    ps: &'a PerfState,
511}
512
513#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
514struct PDCpu<'a> {
515    pd: &'a PerfDomain, // performance domain
516    cpu_vid: usize,     // virtual ID of a CPU on the performance domain
517}
518
519#[derive(Debug, Clone, Eq)]
520struct PDSetInfo<'a> {
521    performance: usize,
522    power: usize,
523    pdcpu_set: BTreeSet<PDCpu<'a>>,
524    pd_id_set: BTreeSet<usize>, // pd:id:0, pd:id:1
525}
526
527const PD_UNIT: usize = 100_000_000;
528const CPU_UNIT: usize = 100_000;
529const LOOKAHEAD_CNT: usize = 10;
530
531/// Upper bound on the number of equivalence performance domain combinations to
532/// consider, to keep the number of combinations manageable. The performance
533/// domains of a processor may not collapse into a few equivalence performance
534/// domains -- per-core binning, for one, could give every core its own
535/// performance table. See <https://github.com/sched-ext/scx/issues/3340>.
536const MAX_EQPD_COMBINATIONS: u128 = 100_000;
537
538impl<'a> EnergyModelOptimizer<'a> {
539    fn new(em: &'a EnergyModel, cpus_pf: &'a Vec<CpuId>) -> EnergyModelOptimizer<'a> {
540        let tot_perf = em.perf_total();
541
542        let eq_pds = Self::sort_eq_pds(em, cpus_pf);
543        let max_nr_cpus: Vec<usize> = eq_pds
544            .iter()
545            .map(|perf_doms| perf_doms.iter().map(|pd| pd.span.weight()).sum())
546            .collect();
547        let nr_cpus_combinations = Self::gen_nr_cpus_combinations(&max_nr_cpus);
548
549        let pdss_infos: BTreeMap<usize, RefCell<HashSet<PDSetInfo<'a>>>> = BTreeMap::new();
550        let pdss_infos = pdss_infos.into();
551
552        let perf_pdsi: BTreeMap<usize, PDSetInfo<'a>> = BTreeMap::new();
553        let perf_pdsi = perf_pdsi.into();
554
555        let mut pd_cpu_order: BTreeMap<usize, RefCell<Vec<usize>>> = BTreeMap::new();
556        let mut cpus_topological_order: Vec<usize> = vec![];
557        for cpuid in cpus_pf.iter() {
558            match pd_cpu_order.get(&cpuid.pd_adx) {
559                Some(v) => {
560                    let mut v = v.borrow_mut();
561                    v.push(cpuid.cpu_adx);
562                }
563                None => {
564                    let v = vec![cpuid.cpu_adx];
565                    pd_cpu_order.insert(cpuid.pd_adx, v.into());
566                }
567            }
568            cpus_topological_order.push(cpuid.cpu_adx);
569        }
570
571        let perf_cpu_order: BTreeMap<usize, PerfCpuOrder> = BTreeMap::new();
572        let perf_cpu_order = perf_cpu_order.into();
573
574        debug!("# pd_cpu_order");
575        debug!("{:#?}", pd_cpu_order);
576
577        EnergyModelOptimizer {
578            eq_pds,
579            nr_cpus_combinations,
580            cpus_topological_order,
581            pd_cpu_order,
582            tot_perf,
583            pdss_infos,
584            perf_pdsi,
585            perf_cpu_order,
586        }
587    }
588
589    fn get_perf_cpu_order_table(
590        em: &'a EnergyModel,
591        cpus_pf: &'a Vec<CpuId>,
592    ) -> BTreeMap<usize, PerfCpuOrder> {
593        let emo = EnergyModelOptimizer::new(em, cpus_pf);
594        emo.gen_perf_cpu_order_table();
595
596        emo.perf_cpu_order.borrow().clone()
597    }
598
599    fn get_fake_perf_cpu_order_table(
600        cpus_pf: &'a Vec<CpuId>,
601        cpus_ps: &'a Vec<CpuId>,
602    ) -> BTreeMap<usize, PerfCpuOrder> {
603        let tot_perf: usize = cpus_pf.iter().map(|cpuid| cpuid.cpu_cap).sum();
604
605        let pco_pf = Self::fake_pco(tot_perf, cpus_pf, false);
606        let pco_ps = Self::fake_pco(tot_perf, cpus_ps, true);
607
608        let mut perf_cpu_order: BTreeMap<usize, PerfCpuOrder> = BTreeMap::new();
609        perf_cpu_order.insert(pco_pf.perf_cap, pco_pf);
610        perf_cpu_order.insert(pco_ps.perf_cap, pco_ps);
611
612        perf_cpu_order
613    }
614
615    fn fake_pco(tot_perf: usize, cpuids: &'a Vec<CpuId>, powersave: bool) -> PerfCpuOrder {
616        let perf_cap = if powersave {
617            cpuids[0].cpu_cap
618        } else {
619            tot_perf
620        };
621
622        let perf_util: f32 = (perf_cap as f32) / (tot_perf as f32);
623        let cpus: Vec<usize> = cpuids.iter().map(|cpuid| cpuid.cpu_adx).collect();
624        let cpus_perf: Vec<usize> = cpus[..1].to_vec();
625        let cpus_ovflw: Vec<usize> = cpus[1..].to_vec();
626        PerfCpuOrder {
627            perf_cap,
628            perf_util,
629            cpus_perf: cpus_perf.clone().into(),
630            cpus_ovflw: cpus_ovflw.clone().into(),
631        }
632    }
633
634    /// Generate the performance versus CPU preference order table based on
635    /// the system's CPU topology and energy model. The table consists of the
636    /// following information (PerfCpuOrder):
637    ///
638    ///   - PerfCpuOrder::perf_cap: The upper bound of the performance
639    ///     capacity covered by this tuple.
640    ///
641    ///   - PerfCpuOrder::cpus_perf: Primary CPUs to be used is ordered
642    ///     by preference.
643    ///
644    ///   - PerfCpuOrder::cpus_ovrflw: When the system load goes beyond
645    ///     @perf_cap, the list of CPUs to be used is ordered by preference.
646    fn gen_perf_cpu_order_table(&'a self) {
647        // First, generate all possible combinations of CPUs (e.g., two CPUs
648        // in performance domain 0 and three CPUs in performance domain 1) to
649        // achieve the possible performance capacities with minimal energy
650        // consumption. We assume a reasonable load balancer, so the
651        // utilization of the used CPUs is similar.
652        self.gen_all_pds_combinations();
653
654        // Then, from all the possible combinations of performance versus
655        // CPU sets, select a list of combinations that minimize the number of
656        // active performance domains and reduce the number of performance
657        // domain switches when changing performance levels.
658        self.gen_perf_pds_table();
659
660        // Finally, assign CPUs (@cpu_adx) to the virtual CPU ID (@cpu_vid) of
661        // a performance domain.
662        self.assign_cpu_vids();
663    }
664
665    /// Generate a CPU order table for each performance range.
666    fn assign_cpu_vids(&'a self) {
667        // Generate CPU order within the performance range (@cpus_perf).
668        for (&perf_cap, pdsi) in self.perf_pdsi.borrow().iter() {
669            let mut cpus_perf: Vec<usize> = vec![];
670
671            for pdcpu in pdsi.pdcpu_set.iter() {
672                let pd_id = pdcpu.pd.id;
673                let cpu_vid = pdcpu.cpu_vid;
674                let cpu_order = self.pd_cpu_order.get(&pd_id).unwrap().borrow();
675                let cpu_adx = cpu_order[cpu_vid];
676                cpus_perf.push(cpu_adx);
677            }
678
679            let perf_util: f32 = (perf_cap as f32) / (self.tot_perf as f32);
680            let cpus_perf = self.sort_cpus_by_topological_order(&cpus_perf);
681            let cpus_ovflw: Vec<usize> = vec![];
682
683            let mut perf_cpu_order = self.perf_cpu_order.borrow_mut();
684            perf_cpu_order.insert(
685                perf_cap,
686                PerfCpuOrder {
687                    perf_cap,
688                    perf_util,
689                    cpus_perf: cpus_perf.clone().into(),
690                    cpus_ovflw: cpus_ovflw.clone().into(),
691                },
692            );
693        }
694
695        // Generate CPU order beyond the performance range (@cpus_ovflw).
696        let perf_cpu_order = self.perf_cpu_order.borrow();
697        let perf_caps: Vec<_> = self.perf_pdsi.borrow().keys().cloned().collect();
698        for o in 1..perf_caps.len() {
699            // Gather all @cpus_perf from the upper performance ranges.
700            let ovrflw_perf_caps = &perf_caps[o..];
701            let mut ovrflw_cpus_all: Vec<usize> = vec![];
702            for perf_cap in ovrflw_perf_caps.iter() {
703                let cpu_order = perf_cpu_order.get(perf_cap).unwrap();
704                let cpus_perf = cpu_order.cpus_perf.borrow();
705                ovrflw_cpus_all.extend(cpus_perf.iter().cloned());
706            }
707
708            // Filter out already taken CPUs from the @ovrflw_cpus_all,
709            // and build @cpus_ovrflw.
710            let mut cpu_set = HashSet::<usize>::new();
711            let perf_cap = perf_caps[o - 1];
712            let cpu_order = perf_cpu_order.get(&perf_cap).unwrap();
713            let cpus_perf = cpu_order.cpus_perf.borrow();
714            for &cpu_adx in cpus_perf.iter() {
715                cpu_set.insert(cpu_adx);
716            }
717
718            let mut cpus_ovflw: Vec<usize> = vec![];
719            for &cpu_adx in ovrflw_cpus_all.iter() {
720                if cpu_set.get(&cpu_adx).is_none() {
721                    cpus_ovflw.push(cpu_adx);
722                    cpu_set.insert(cpu_adx);
723                }
724            }
725
726            // Inject the constructed @cpus_ovrflw to the table.
727            let mut v = cpu_order.cpus_ovflw.borrow_mut();
728            v.extend(cpus_ovflw.iter().cloned());
729        }
730
731        // Debug print of the generated table
732        debug!("## gen_perf_cpu_order_table");
733        debug!("{:#?}", perf_cpu_order);
734    }
735
736    /// Sort the CPU IDs by topological order (@self.cpus_topological_order).
737    fn sort_cpus_by_topological_order(&'a self, cpus: &Vec<usize>) -> Vec<usize> {
738        let mut sorted: Vec<usize> = vec![];
739        for &cpu_adx in self.cpus_topological_order.iter() {
740            if cpus.iter().find(|&&x| x == cpu_adx).is_some() {
741                sorted.push(cpu_adx);
742            }
743        }
744        sorted
745    }
746
747    /// Generate a table of performance vs. performance domain sets
748    /// (@self.perf_pdss) from all the possible performance domain & state
749    /// combinations (@self.pdss_infos).
750    ///
751    /// An example result is as follows:
752    ///     PERF: [_, 300]
753    ///             pd:id: 0 -- cpu_vid: 0
754    ///             pd:id: 0 -- cpu_vid: 1
755    ///     PERF: [_, 1138]
756    ///             pd:id: 0 -- cpu_vid: 0
757    ///             pd:id: 0 -- cpu_vid: 1
758    ///             pd:id: 1 -- cpu_vid: 0
759    ///             pd:id: 1 -- cpu_vid: 1
760    ///     PERF: [_, 3386]
761    ///             pd:id: 1 -- cpu_vid: 0
762    ///             pd:id: 1 -- cpu_vid: 1
763    ///             pd:id: 1 -- cpu_vid: 2
764    ///             pd:id: 2 -- cpu_vid: 0
765    ///             pd:id: 2 -- cpu_vid: 1
766    ///     PERF: [_, 3977]
767    ///             pd:id: 0 -- cpu_vid: 0
768    ///             pd:id: 1 -- cpu_vid: 0
769    ///             pd:id: 1 -- cpu_vid: 1
770    ///             pd:id: 1 -- cpu_vid: 2
771    ///             pd:id: 2 -- cpu_vid: 0
772    ///             pd:id: 2 -- cpu_vid: 1
773    ///     PERF: [_, 4508]
774    ///             pd:id: 0 -- cpu_vid: 0
775    ///             pd:id: 0 -- cpu_vid: 1
776    ///             pd:id: 1 -- cpu_vid: 0
777    ///             pd:id: 1 -- cpu_vid: 1
778    ///             pd:id: 1 -- cpu_vid: 2
779    ///             pd:id: 2 -- cpu_vid: 0
780    ///             pd:id: 2 -- cpu_vid: 1
781    ///     PERF: [_, 5627]
782    ///             pd:id: 0 -- cpu_vid: 0
783    ///             pd:id: 0 -- cpu_vid: 1
784    ///             pd:id: 1 -- cpu_vid: 0
785    ///             pd:id: 1 -- cpu_vid: 1
786    ///             pd:id: 1 -- cpu_vid: 2
787    ///             pd:id: 2 -- cpu_vid: 0
788    ///             pd:id: 2 -- cpu_vid: 1
789    ///             pd:id: 3 -- cpu_vid: 0
790    fn gen_perf_pds_table(&'a self) {
791        let utils = vec![0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];
792
793        // Find the best performance domains for each system utilization target.
794        for &util in utils.iter() {
795            let mut best_pdsi: Option<PDSetInfo<'a>>;
796            let mut del_pdsi: Option<PDSetInfo<'a>> = None;
797
798            match self.perf_pdsi.borrow().last_key_value() {
799                Some((_, base)) => {
800                    best_pdsi = self.find_perf_pds_for(util, Some(base));
801
802                    // If the next performance level (@best_pdsi) is subsumed
803                    // by the previous level (@base), extend the base to the
804                    // next level. To this end, insert the extended base (with
805                    // updated performance and power values) and delete the old
806                    // base.
807                    if let Some(ref best) = best_pdsi
808                        && best.pdcpu_set.is_subset(&base.pdcpu_set)
809                    {
810                        let ext_pdcpu = PDSetInfo {
811                            performance: best.performance,
812                            power: best.power,
813                            pdcpu_set: base.pdcpu_set.clone(),
814                            pd_id_set: base.pd_id_set.clone(),
815                        };
816                        best_pdsi = Some(ext_pdcpu);
817                        del_pdsi = Some(base.clone());
818                    }
819                }
820                None => {
821                    best_pdsi = self.find_perf_pds_for(util, None);
822                }
823            };
824
825            if let Some(best_pdsi) = best_pdsi {
826                self.perf_pdsi
827                    .borrow_mut()
828                    .insert(best_pdsi.performance, best_pdsi);
829            }
830
831            if let Some(del_pdsi) = del_pdsi {
832                self.perf_pdsi.borrow_mut().remove(&del_pdsi.performance);
833            }
834        }
835
836        // Debug print of the generated table
837        debug!("## gen_perf_pds_table");
838        for (perf, pdsi) in self.perf_pdsi.borrow().iter() {
839            debug!("PERF: [_, {}]", perf);
840            for pdcpu in pdsi.pdcpu_set.iter() {
841                debug!(
842                    "        pd:id: {:?} -- cpu_vid: {}",
843                    pdcpu.pd.id, pdcpu.cpu_vid
844                );
845            }
846        }
847    }
848
849    fn find_perf_pds_for(
850        &'a self,
851        util: f32,
852        base: Option<&PDSetInfo<'a>>,
853    ) -> Option<PDSetInfo<'a>> {
854        let target_perf = (util * self.tot_perf as f32) as usize;
855        let mut lookahead = 0;
856        let mut min_dist: usize = usize::MAX;
857        let mut best_pdsi: Option<PDSetInfo<'a>> = None;
858
859        let pdss_infos = self.pdss_infos.borrow();
860        for (&pdsi_perf, pdsi_set) in pdss_infos.iter() {
861            if pdsi_perf >= target_perf {
862                let pdsi_set_ref = pdsi_set.borrow();
863                for pdsi in pdsi_set_ref.iter() {
864                    let dist = pdsi.dist(base);
865                    if dist < min_dist {
866                        min_dist = dist;
867                        best_pdsi = Some(pdsi.clone());
868                    }
869                }
870                lookahead += 1;
871                if lookahead >= LOOKAHEAD_CNT {
872                    break;
873                }
874            }
875        }
876
877        best_pdsi
878    }
879
880    /// Generate all possible performance domain & state combinations,
881    /// @self.pdss_infos. Each combination represents a set of performance
882    /// domains (and their corresponding performance states) that achieve the
883    /// requested performance with minimal power consumption.
884    ///
885    /// We assume a 'reasonable load balancer,' so the CPU utilization of all
886    /// the involved CPUs is similar.
887    ///
888    /// An example result is as follows:
889    ///
890    ///     PERF: [_, 5135]
891    ///         perf: 5135 -- power: 5475348
892    ///             pd:id: 0 -- cpu_vid: 0
893    ///             pd:id: 1 -- cpu_vid: 0
894    ///             pd:id: 1 -- cpu_vid: 1
895    ///             pd:id: 1 -- cpu_vid: 2
896    ///             pd:id: 2 -- cpu_vid: 0
897    ///             pd:id: 2 -- cpu_vid: 1
898    ///             pd:id: 3 -- cpu_vid: 0
899    ///     PERF: [_, 5187]
900    ///         perf: 5187 -- power: 4844969
901    ///             pd:id: 0 -- cpu_vid: 0
902    ///             pd:id: 0 -- cpu_vid: 1
903    ///             pd:id: 1 -- cpu_vid: 0
904    ///             pd:id: 1 -- cpu_vid: 1
905    ///             pd:id: 1 -- cpu_vid: 2
906    ///             pd:id: 2 -- cpu_vid: 0
907    ///             pd:id: 2 -- cpu_vid: 1
908    ///             pd:id: 3 -- cpu_vid: 0
909    ///     PERF: [_, 5195]
910    ///         perf: 5195 -- power: 5924606
911    ///             pd:id: 1 -- cpu_vid: 0
912    ///             pd:id: 1 -- cpu_vid: 1
913    ///             pd:id: 1 -- cpu_vid: 2
914    ///             pd:id: 2 -- cpu_vid: 0
915    ///             pd:id: 2 -- cpu_vid: 1
916    ///             pd:id: 3 -- cpu_vid: 0
917    ///     PERF: [_, 5217]
918    ///         perf: 5217 -- power: 4894911
919    ///             pd:id: 0 -- cpu_vid: 0
920    ///             pd:id: 0 -- cpu_vid: 1
921    ///             pd:id: 1 -- cpu_vid: 0
922    ///             pd:id: 1 -- cpu_vid: 1
923    ///             pd:id: 1 -- cpu_vid: 2
924    ///             pd:id: 2 -- cpu_vid: 0
925    ///             pd:id: 2 -- cpu_vid: 1
926    ///             pd:id: 3 -- cpu_vid: 0
927    ///     PERF: [_, 5225]
928    ///         perf: 5225 -- power: 5665770
929    ///             pd:id: 0 -- cpu_vid: 0
930    ///             pd:id: 1 -- cpu_vid: 0
931    ///             pd:id: 1 -- cpu_vid: 1
932    ///             pd:id: 1 -- cpu_vid: 2
933    ///             pd:id: 2 -- cpu_vid: 0
934    ///             pd:id: 2 -- cpu_vid: 1
935    ///             pd:id: 3 -- cpu_vid: 0
936    ///     PERF: [_, 5316]
937    ///         perf: 5316 -- power: 5860568
938    ///             pd:id: 0 -- cpu_vid: 0
939    ///             pd:id: 1 -- cpu_vid: 0
940    ///             pd:id: 1 -- cpu_vid: 1
941    ///             pd:id: 1 -- cpu_vid: 2
942    ///             pd:id: 2 -- cpu_vid: 0
943    ///             pd:id: 2 -- cpu_vid: 1
944    ///             pd:id: 3 -- cpu_vid: 0
945    fn gen_all_pds_combinations(&'a self) {
946        // Start from the min (0%) and max (100%) CPU utilizations
947        let pdsi_vec = self.gen_pds_combinations(0.0);
948        self.insert_pds_combinations(&pdsi_vec);
949
950        let pdsi_vec = self.gen_pds_combinations(100.0);
951        self.insert_pds_combinations(&pdsi_vec);
952
953        // Then dive into the range between the min and max.
954        self.gen_perf_cpuset_table_range(0, 100);
955
956        // Debug print performance table
957        debug!("## gen_all_pds_combinations");
958        for (perf, pdss_info) in self.pdss_infos.borrow().iter() {
959            debug!("PERF: [_, {}]", perf);
960            for pdsi in pdss_info.borrow().iter() {
961                debug!("    perf: {} -- power: {}", pdsi.performance, pdsi.power);
962                for pdcpu in pdsi.pdcpu_set.iter() {
963                    debug!(
964                        "        pd:id: {:?} -- cpu_vid: {}",
965                        pdcpu.pd.id, pdcpu.cpu_vid
966                    );
967                }
968            }
969        }
970    }
971
972    fn gen_perf_cpuset_table_range(&'a self, low: isize, high: isize) {
973        if low > high {
974            return;
975        }
976
977        // If there is a new performance point in the middle,
978        // let's further explore. Otherwise, stop it here.
979        let mid: isize = low + (high - low) / 2;
980        let pdsi_vec = self.gen_pds_combinations(mid as f32);
981        let found_new = self.insert_pds_combinations(&pdsi_vec);
982        if found_new {
983            self.gen_perf_cpuset_table_range(mid + 1, high);
984            self.gen_perf_cpuset_table_range(low, mid - 1);
985        }
986    }
987
988    /// Rank the performance domains by CPU preference: a performance domain is
989    /// as preferred as its most preferred CPU, which is the first one appearing
990    /// in @cpus_pf. A performance domain with no CPU in @cpus_pf is unranked and
991    /// comes last.
992    fn rank_perf_doms(cpus_pf: &[CpuId]) -> BTreeMap<usize, usize> {
993        let mut ranks = BTreeMap::new();
994
995        for (rank, cpuid) in cpus_pf.iter().enumerate() {
996            ranks.entry(cpuid.pd_adx).or_insert(rank);
997        }
998
999        ranks
1000    }
1001
1002    /// Collect the member performance domains of each equivalence performance
1003    /// domain of @em, ordering both the members and the equivalence performance
1004    /// domains by CPU preference. See @EnergyModelOptimizer::eq_pds.
1005    fn sort_eq_pds(em: &'a EnergyModel, cpus_pf: &'a [CpuId]) -> Vec<Vec<&'a PerfDomain>> {
1006        let ranks = Self::rank_perf_doms(cpus_pf);
1007        let rank_of = |pd: &PerfDomain| ranks.get(&pd.id).copied().unwrap_or(usize::MAX);
1008
1009        let mut eq_pds: Vec<Vec<&'a PerfDomain>> = em
1010            .eq_perf_doms
1011            .values()
1012            .map(|eq_pd| {
1013                let mut perf_doms: Vec<&'a PerfDomain> =
1014                    eq_pd.perf_doms.iter().map(|pd| pd.as_ref()).collect();
1015                perf_doms.sort_by_key(|pd| rank_of(pd));
1016                perf_doms
1017            })
1018            .collect();
1019
1020        // An equivalence performance domain is as preferred as its most
1021        // preferred member performance domain.
1022        eq_pds.sort_by_key(|perf_doms| perf_doms.iter().map(|pd| rank_of(pd)).min());
1023
1024        eq_pds
1025    }
1026
1027    /// Enumerate how many CPUs to take from each equivalence performance
1028    /// domain, taking at most @max_nr_cpus[i] CPUs from the i-th one. See
1029    /// @EnergyModelOptimizer::nr_cpus_combinations.
1030    fn gen_nr_cpus_combinations(max_nr_cpus: &[usize]) -> Vec<Vec<usize>> {
1031        // The number of all the possible combinations. An equivalence
1032        // performance domain can contribute none, some, or all of its CPUs, so
1033        // it has max_nr_cpus + 1 choices, and the choices of all the
1034        // equivalence performance domains multiply. Subtract one for the
1035        // combination taking no CPU at all. The product saturates instead of
1036        // overflowing when there are hundreds of equivalence performance
1037        // domains.
1038        let nr_combinations = max_nr_cpus
1039            .iter()
1040            .fold(1u128, |nr, &max| nr.saturating_mul(max as u128 + 1))
1041            - 1;
1042        if nr_combinations <= MAX_EQPD_COMBINATIONS {
1043            return Self::gen_all_nr_cpus(max_nr_cpus);
1044        }
1045
1046        let combinations = Self::gen_run_nr_cpus(max_nr_cpus);
1047        warn!(
1048            "{} equivalence performance domains yield {nr_combinations} combinations, \
1049             exceeding the limit of {MAX_EQPD_COMBINATIONS}, so consider only {} of them",
1050            max_nr_cpus.len(),
1051            combinations.len(),
1052        );
1053
1054        combinations
1055    }
1056
1057    /// Enumerate how many CPUs to take from each equivalence performance domain
1058    /// in every possible way. An equivalence performance domain independently
1059    /// takes 0, 1, ... up to all of its CPUs, so a combination picks one count
1060    /// from the range `0..=max_nr_cpus[i]` of every equivalence performance
1061    /// domain. Picking one element from each of several ranges, in all the
1062    /// possible ways, is the cartesian product of those ranges, which
1063    /// `multi_cartesian_product` enumerates one combination at a time. See
1064    /// @EnergyModelOptimizer::nr_cpus_combinations for an example.
1065    fn gen_all_nr_cpus(max_nr_cpus: &[usize]) -> Vec<Vec<usize>> {
1066        max_nr_cpus
1067            .iter()
1068            .map(|&max| 0..=max)
1069            .multi_cartesian_product()
1070            // Drop the one combination taking no CPU at all.
1071            .filter(|nr_cpus| nr_cpus.iter().any(|&nr| nr > 0))
1072            .collect()
1073    }
1074
1075    /// Enumerate how many CPUs to take from each equivalence performance domain
1076    /// when there are too many combinations to consider them all
1077    /// (@MAX_EQPD_COMBINATIONS). Only the runs of equivalence performance
1078    /// domains are considered, where a run takes all the CPUs of consecutive
1079    /// equivalence performance domains and some of the CPUs of the last one:
1080    ///
1081    ///   - A forward run grows from the first equivalence performance domain,
1082    ///     adding one more equivalence performance domain at a time.
1083    ///   - A backward run grows from the last equivalence performance domain
1084    ///     in the opposite direction.
1085    ///   - A single run takes CPUs from one equivalence performance domain and
1086    ///     none from the others.
1087    ///
1088    /// For example, with three equivalence performance domains of 1, 2, and 1
1089    /// CPUs, the runs are:
1090    ///
1091    ///     forward:  [1, 0, 0]
1092    ///               [1, 1, 0], [1, 2, 0]
1093    ///               [1, 2, 1]
1094    ///     backward: [0, 0, 1]
1095    ///               [0, 1, 1], [0, 2, 1]
1096    ///               [1, 2, 1]
1097    ///     single:   [1, 0, 0]
1098    ///               [0, 1, 0], [0, 2, 0]
1099    ///               [0, 0, 1]
1100    ///
1101    /// which is 3 * nr_cpus = 12 combinations, or 9 once the duplicates are
1102    /// removed. Since there are at most 3 * nr_cpus of them, the runs always
1103    /// fit in @MAX_EQPD_COMBINATIONS.
1104    fn gen_run_nr_cpus(max_nr_cpus: &[usize]) -> Vec<Vec<usize>> {
1105        let nr_eq_pds = max_nr_cpus.len();
1106        let mut combinations = vec![];
1107
1108        // Take 1 to all the CPUs of the @i-th equivalence performance domain,
1109        // which is the last one of a forward run, the last one of a backward
1110        // run, and the only one of a single run.
1111        for i in 0..nr_eq_pds {
1112            let mut forward = vec![0; nr_eq_pds];
1113            forward[..i].copy_from_slice(&max_nr_cpus[..i]);
1114
1115            let mut backward = vec![0; nr_eq_pds];
1116            backward[i + 1..].copy_from_slice(&max_nr_cpus[i + 1..]);
1117
1118            let mut single = vec![0; nr_eq_pds];
1119
1120            for nr in 1..=max_nr_cpus[i] {
1121                forward[i] = nr;
1122                backward[i] = nr;
1123                single[i] = nr;
1124
1125                combinations.push(forward.clone());
1126                combinations.push(backward.clone());
1127                combinations.push(single.clone());
1128            }
1129        }
1130
1131        combinations.sort();
1132        combinations.dedup();
1133
1134        combinations
1135    }
1136
1137    /// Generate the combinations of performance domains and states to consider
1138    /// for a given CPU utilization (@util), one for each combination of
1139    /// per-equivalence performance domain CPU counts.
1140    fn gen_pds_combinations(&'a self, util: f32) -> Vec<PDSetInfo<'a>> {
1141        self.nr_cpus_combinations
1142            .iter()
1143            .map(|nr_cpus| self.gen_pdsi(nr_cpus, util))
1144            .collect()
1145    }
1146
1147    /// Build the performance domains and states taking @nr_cpus[i] CPUs from
1148    /// the i-th equivalence performance domain at the performance state for
1149    /// @util. The CPUs are taken from the member performance domains in order,
1150    /// so the CPUs for a count of N are always a subset of the ones for N + 1.
1151    fn gen_pdsi(&'a self, nr_cpus: &[usize], util: f32) -> PDSetInfo<'a> {
1152        let mut pds_set = vec![];
1153
1154        for (perf_doms, &nr) in self.eq_pds.iter().zip(nr_cpus.iter()) {
1155            // All the member performance domains share one performance table,
1156            // so they are all at the same performance state.
1157            let ps = perf_doms[0].select_perf_state(util).unwrap();
1158            let mut remaining = nr;
1159
1160            for pd in perf_doms.iter() {
1161                if remaining == 0 {
1162                    break;
1163                }
1164
1165                // A performance domain contributes at most its own CPUs.
1166                let take = remaining.min(pd.span.weight());
1167                for _ in 0..take {
1168                    pds_set.push(PDS::new(pd, ps));
1169                }
1170                remaining -= take;
1171            }
1172        }
1173
1174        PDSetInfo::new(pds_set)
1175    }
1176
1177    fn insert_pds_combinations(&self, new_pdsi_vec: &Vec<PDSetInfo<'a>>) -> bool {
1178        // For the same performance, keep the PDS combinations with the lowest
1179        // power consumption. If there are more than one lowest, keep them all
1180        // to choose one later when assigning CPUs from the selected
1181        // performance domains.
1182        let mut found_new = false;
1183
1184        for new_pdsi in new_pdsi_vec.iter() {
1185            let mut pdss_infos = self.pdss_infos.borrow_mut();
1186            let v = pdss_infos.get(&new_pdsi.performance);
1187            match v {
1188                // There are already PDSetInfo in the list.
1189                Some(v) => {
1190                    let mut v = v.borrow_mut();
1191                    let pdsi = &v.iter().next().unwrap();
1192                    if pdsi.power == new_pdsi.power {
1193                        // If the power consumptions are the same, keep both.
1194                        if v.insert(new_pdsi.clone()) {
1195                            found_new = true;
1196                        }
1197                    } else if pdsi.power > new_pdsi.power {
1198                        // If the new one takes less power, keep the new one.
1199                        v.clear();
1200                        v.insert(new_pdsi.clone());
1201                        found_new = true;
1202                    }
1203                }
1204                // This is the first for the performance target.
1205                None => {
1206                    // Let's add it and move on.
1207                    let mut v: HashSet<PDSetInfo<'a>> = HashSet::new();
1208                    v.insert(new_pdsi.clone());
1209                    pdss_infos.insert(new_pdsi.performance, v.into());
1210                    found_new = true;
1211                }
1212            }
1213        }
1214        found_new
1215    }
1216}
1217
1218impl<'a> PDS<'_> {
1219    fn new(pd: &'a PerfDomain, ps: &'a PerfState) -> PDS<'a> {
1220        PDS { pd, ps }
1221    }
1222}
1223
1224impl<'a> PDCpu<'_> {
1225    fn new(pd: &'a PerfDomain, cpu_vid: usize) -> PDCpu<'a> {
1226        PDCpu { pd, cpu_vid }
1227    }
1228}
1229
1230impl fmt::Display for PDS<'_> {
1231    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232        write!(
1233            f,
1234            "pd:id:{}/pd:weight:{}/ps:cap:{}/ps:power:{}",
1235            self.pd.id,
1236            self.pd.span.weight(),
1237            self.ps.performance,
1238            self.ps.power,
1239        )?;
1240        Ok(())
1241    }
1242}
1243
1244impl<'a> PDSetInfo<'_> {
1245    fn new(pds_set: Vec<PDS<'a>>) -> PDSetInfo<'a> {
1246        // Create a pd_id_set and calculate performance and power.
1247        let mut performance = 0;
1248        let mut power = 0;
1249        let mut pd_id_set: BTreeSet<usize> = BTreeSet::new();
1250
1251        for pds in pds_set.iter() {
1252            performance += pds.ps.performance;
1253            power += pds.ps.power;
1254            pd_id_set.insert(pds.pd.id);
1255        }
1256
1257        // Create a pdcpu_set, so first gather the same PDS entries.
1258        let mut pds_map: BTreeMap<PDS<'a>, RefCell<Vec<PDS<'a>>>> = BTreeMap::new();
1259
1260        for pds in pds_set.iter() {
1261            let v = pds_map.get(pds);
1262            match v {
1263                Some(v) => {
1264                    let mut v = v.borrow_mut();
1265                    v.push(pds.clone());
1266                }
1267                None => {
1268                    let mut v: Vec<PDS<'a>> = Vec::new();
1269                    v.push(pds.clone());
1270                    pds_map.insert(pds.clone(), v.into());
1271                }
1272            }
1273        }
1274        // Then assign cpu virtual ids to pdcpu_set.
1275        let mut pdcpu_set: BTreeSet<PDCpu<'a>> = BTreeSet::new();
1276        let pds_map = pds_map;
1277
1278        for v in pds_map.values() {
1279            for (cpu_vid, pds) in v.borrow().iter().enumerate() {
1280                let pdcpu = PDCpu::new(pds.pd, cpu_vid);
1281                pdcpu_set.insert(pdcpu);
1282            }
1283        }
1284
1285        PDSetInfo {
1286            performance,
1287            power,
1288            pdcpu_set,
1289            pd_id_set,
1290        }
1291    }
1292
1293    /// Calculate the distance from @base to @self. We minimize the number of
1294    /// performance domains involved to reduce the leakage power consumption.
1295    /// We then maximize the overlap between the previous (i.e., base)
1296    /// performance domains and the new one for a smooth transition to the new
1297    /// cpuset with higher cache locality. Finally, we minimize the number of
1298    /// CPUs involved, thereby reducing the chance of contention for shared
1299    /// hardware resources (e.g., shared cache).
1300    fn dist(&self, base: Option<&PDSetInfo<'a>>) -> usize {
1301        let nr_pds = self.pd_id_set.len();
1302        let nr_pds_overlap = match base {
1303            Some(base) => self.pd_id_set.intersection(&base.pd_id_set).count(),
1304            None => 0,
1305        };
1306        let nr_cpus = self.pdcpu_set.len();
1307
1308        ((nr_pds - nr_pds_overlap) * PD_UNIT) +         // # non-overlapping PDs
1309        ((*NR_CPU_IDS - nr_cpus) * CPU_UNIT) +          // # of CPUs
1310        (*NR_CPU_IDS - self.pd_id_set.first().unwrap()) // PD ID as a tiebreaker
1311    }
1312}
1313
1314impl PartialEq for PDSetInfo<'_> {
1315    fn eq(&self, other: &Self) -> bool {
1316        self.performance == other.performance
1317            && self.power == other.power
1318            && self.pdcpu_set == other.pdcpu_set
1319    }
1320}
1321
1322impl Hash for PDSetInfo<'_> {
1323    fn hash<H: Hasher>(&self, state: &mut H) {
1324        // We don't need to hash performance, power, and pd_id_set
1325        // since they are a kind of cache for pds_set.
1326        self.pdcpu_set.hash(state);
1327    }
1328}
1329
1330impl PartialEq for PerfCpuOrder {
1331    fn eq(&self, other: &Self) -> bool {
1332        self.perf_cap == other.perf_cap
1333    }
1334}
1335
1336impl fmt::Display for PerfCpuOrder {
1337    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1338        writeln!(
1339            f,
1340            "capacity bound:  {} ({}%)",
1341            self.perf_cap,
1342            self.perf_util * 100.0
1343        )?;
1344        writeln!(f, "  primary CPUs:  {:?}", self.cpus_perf.borrow())?;
1345        write!(f, "  overflow CPUs: {:?}", self.cpus_ovflw.borrow())?;
1346        Ok(())
1347    }
1348}
1349
1350/// Tests for enumerating the combinations of equivalence performance domains,
1351/// which used to be enumerated over the individual performance domains and
1352/// blow up on a hybrid processor, where there is one performance domain per
1353/// CPU. See <https://github.com/sched-ext/scx/issues/3340>.
1354#[cfg(test)]
1355mod tests {
1356    use super::*;
1357    use scx_utils::EqPerfDomain;
1358    use std::sync::Arc;
1359
1360    /// Build an energy model whose i-th equivalence performance domain has
1361    /// @eq_pd_nr_cpus[i] CPUs, each CPU in a performance domain of its own as
1362    /// on an Intel hybrid processor.
1363    fn energy_model(eq_pd_nr_cpus: &[usize]) -> EnergyModel {
1364        let mut perf_doms = BTreeMap::new();
1365        let mut eq_perf_doms = BTreeMap::new();
1366        let mut pd_id = 0;
1367
1368        for (eq_pd_id, &nr_cpus) in eq_pd_nr_cpus.iter().enumerate() {
1369            // Give every equivalence performance domain a performance table of
1370            // its own so that they stay distinct.
1371            let performance = 100 * (eq_pd_id + 1);
1372            let ps = PerfState {
1373                cost: performance,
1374                frequency: performance,
1375                inefficient: 0,
1376                performance,
1377                power: performance,
1378            };
1379            let perf_table: BTreeMap<usize, Arc<PerfState>> =
1380                [(performance, ps.into())].into_iter().collect();
1381
1382            let mut members = vec![];
1383            let mut span_bits = 0u64;
1384            for _ in 0..nr_cpus {
1385                let pd: Arc<PerfDomain> = PerfDomain {
1386                    id: pd_id,
1387                    span: Cpumask::from_vec(vec![1u64 << pd_id]),
1388                    perf_table: perf_table.clone(),
1389                }
1390                .into();
1391                span_bits |= 1u64 << pd_id;
1392                perf_doms.insert(pd_id, pd.clone());
1393                members.push(pd);
1394                pd_id += 1;
1395            }
1396
1397            let eq_pd = EqPerfDomain {
1398                id: eq_pd_id,
1399                perf_doms: members,
1400                span: Cpumask::from_vec(vec![span_bits]),
1401                perf_table,
1402            };
1403            eq_perf_doms.insert(eq_pd_id, eq_pd.into());
1404        }
1405
1406        EnergyModel {
1407            perf_doms,
1408            eq_perf_doms,
1409        }
1410    }
1411
1412    /// Build a CPU preference order taking one CPU from each performance domain
1413    /// of @pd_adxs, so the performance domain listed first is the most
1414    /// preferred one.
1415    fn cpu_pref_order(pd_adxs: &[usize]) -> Vec<CpuId> {
1416        pd_adxs
1417            .iter()
1418            .enumerate()
1419            .map(|(core_rdx, &pd_adx)| CpuId {
1420                numa_adx: 0,
1421                pd_adx,
1422                llc_adx: 0,
1423                llc_rdx: 0,
1424                llc_kernel_id: 0,
1425                core_rdx,
1426                cpu_rdx: 0,
1427                cpu_adx: pd_adx,
1428                smt_level: 1,
1429                cache_size: 0,
1430                cpu_cap: 1024,
1431                big_core: true,
1432                turbo_core: false,
1433            })
1434            .collect()
1435    }
1436
1437    /// The CPUs of an equivalence performance domain are taken from its most
1438    /// preferred member performance domain first, not from the one with the
1439    /// lowest id.
1440    #[test]
1441    fn test_members_in_cpu_preference_order() {
1442        // One equivalence performance domain of 4 CPUs, each in a performance
1443        // domain of its own, preferred in the reverse order of their ids.
1444        let em = energy_model(&[4]);
1445        let cpus_pf = cpu_pref_order(&[3, 2, 1, 0]);
1446        let emo = EnergyModelOptimizer::new(&em, &cpus_pf);
1447
1448        let pd_ids: Vec<usize> = emo.eq_pds[0].iter().map(|pd| pd.id).collect();
1449        assert_eq!(pd_ids, vec![3, 2, 1, 0]);
1450
1451        // Taking 2 CPUs takes them from the 2 most preferred performance
1452        // domains.
1453        let expected: BTreeSet<usize> = [2, 3].into_iter().collect();
1454        assert_eq!(emo.gen_pdsi(&[2], 100.0).pd_id_set, expected);
1455    }
1456
1457    /// The equivalence performance domains themselves are ordered by CPU
1458    /// preference, so a count belongs to the equivalence performance domain of
1459    /// the same preference.
1460    #[test]
1461    fn test_eq_pds_in_cpu_preference_order() {
1462        // Two equivalence performance domains of 2 CPUs each, preferring the
1463        // CPUs of the second one.
1464        let em = energy_model(&[2, 2]);
1465        let cpus_pf = cpu_pref_order(&[2, 3, 0, 1]);
1466        let emo = EnergyModelOptimizer::new(&em, &cpus_pf);
1467
1468        let pd_ids: Vec<Vec<usize>> = emo
1469            .eq_pds
1470            .iter()
1471            .map(|perf_doms| perf_doms.iter().map(|pd| pd.id).collect())
1472            .collect();
1473        assert_eq!(pd_ids, vec![vec![2, 3], vec![0, 1]]);
1474
1475        // The first count belongs to the first equivalence performance domain,
1476        // which is the preferred one.
1477        let expected: BTreeSet<usize> = [2].into_iter().collect();
1478        assert_eq!(emo.gen_pdsi(&[1, 0], 100.0).pd_id_set, expected);
1479    }
1480
1481    /// A 28-thread hybrid processor (8 P-cores, 16 E-cores, and 4 LP-E-cores)
1482    /// collapsing into three equivalence performance domains. Enumerating over
1483    /// its 28 performance domains, one per CPU, would take 2^28 - 1
1484    /// combinations.
1485    #[test]
1486    fn test_hybrid_combinations() {
1487        let em = energy_model(&[8, 16, 4]);
1488        let cpus_pf = vec![];
1489        let emo = EnergyModelOptimizer::new(&em, &cpus_pf);
1490
1491        // (8 + 1) * (16 + 1) * (4 + 1) - 1
1492        assert_eq!(emo.nr_cpus_combinations.len(), 764);
1493        assert!(emo.nr_cpus_combinations.contains(&vec![8, 16, 4]));
1494        assert_eq!(emo.gen_pds_combinations(100.0).len(), 764);
1495    }
1496
1497    /// A processor whose performance domains do not collapse at all, as
1498    /// per-core binning could produce. Enumerating all the combinations would
1499    /// take 2^24 - 1 of them, exceeding @MAX_EQPD_COMBINATIONS, so only the
1500    /// runs of equivalence performance domains are considered.
1501    #[test]
1502    fn test_uncollapsed_combinations_fall_back_to_runs() {
1503        let em = energy_model(&[1; 24]);
1504        let cpus_pf = vec![];
1505        let emo = EnergyModelOptimizer::new(&em, &cpus_pf);
1506
1507        // 24 forward runs, 24 backward runs, and 24 single runs, of which the
1508        // all-CPU run and the two end single runs are duplicates.
1509        assert_eq!(emo.nr_cpus_combinations.len(), 69);
1510        assert!(emo.nr_cpus_combinations.contains(&vec![1; 24]));
1511
1512        // Every run takes CPUs from consecutive equivalence performance
1513        // domains.
1514        for nr_cpus in emo.nr_cpus_combinations.iter() {
1515            let first = nr_cpus.iter().position(|&nr| nr > 0).unwrap();
1516            let last = nr_cpus.iter().rposition(|&nr| nr > 0).unwrap();
1517            assert!(nr_cpus[first..=last].iter().all(|&nr| nr > 0));
1518        }
1519    }
1520
1521    /// A single equivalence performance domain, so a combination is just how
1522    /// many of its CPUs to take.
1523    #[test]
1524    fn test_uniform_combinations() {
1525        let em = energy_model(&[8]);
1526        let cpus_pf = vec![];
1527        let emo = EnergyModelOptimizer::new(&em, &cpus_pf);
1528
1529        assert_eq!(emo.nr_cpus_combinations.len(), 8);
1530        assert_eq!(emo.gen_pds_combinations(100.0).len(), 8);
1531    }
1532}