scx_lavd/
main.rs

1// SPDX-License-Identifier: GPL-2.0
2//
3// Copyright (c) 2024 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
9mod bpf_skel;
10pub use bpf_skel::*;
11pub mod bpf_intf;
12pub use bpf_intf::*;
13
14mod cpu_order;
15use scx_utils::init_libbpf_logging;
16mod stats;
17use std::ffi::c_int;
18use std::ffi::CStr;
19use std::mem;
20use std::mem::MaybeUninit;
21use std::str;
22use std::sync::atomic::AtomicBool;
23use std::sync::atomic::Ordering;
24use std::sync::Arc;
25use std::thread::ThreadId;
26use std::time::Duration;
27
28use anyhow::Context;
29use anyhow::Result;
30use clap::Parser;
31use clap_num::number_range;
32use cpu_order::CpuOrder;
33use cpu_order::PerfCpuOrder;
34use crossbeam::channel;
35use crossbeam::channel::Receiver;
36use crossbeam::channel::RecvTimeoutError;
37use crossbeam::channel::Sender;
38use crossbeam::channel::TrySendError;
39use libbpf_rs::skel::Skel;
40use libbpf_rs::OpenObject;
41use libbpf_rs::PrintLevel;
42use libbpf_rs::ProgramInput;
43use libc::c_char;
44use plain::Plain;
45use scx_arena::ArenaLib;
46use scx_stats::prelude::*;
47use scx_utils::autopower::{fetch_power_profile, PowerProfile};
48use scx_utils::build_id;
49use scx_utils::compat;
50use scx_utils::ksym_exists;
51use scx_utils::libbpf_clap_opts::LibbpfOpts;
52use scx_utils::scx_ops_attach;
53use scx_utils::scx_ops_load;
54use scx_utils::scx_ops_open;
55use scx_utils::try_set_rlimit_infinity;
56use scx_utils::uei_exited;
57use scx_utils::uei_report;
58use scx_utils::EnergyModel;
59use scx_utils::TopologyArgs;
60use scx_utils::UserExitInfo;
61use scx_utils::NR_CPU_IDS;
62use stats::SchedSample;
63use stats::SchedSamples;
64use stats::StatsReq;
65use stats::StatsRes;
66use stats::SysStats;
67use tracing::{debug, info, warn};
68use tracing_subscriber::filter::EnvFilter;
69
70const SCHEDULER_NAME: &str = "scx_lavd";
71/// scx_lavd: Latency-criticality Aware Virtual Deadline (LAVD) scheduler
72///
73/// The rust part is minimal. It processes command line options and logs out
74/// scheduling statistics. The BPF part makes all the scheduling decisions.
75/// See the more detailed overview of the LAVD design at main.bpf.c.
76#[derive(Debug, Parser)]
77struct Opts {
78    /// Depricated, noop, use RUST_LOG or --log-level instead.
79    #[clap(short = 'v', long, action = clap::ArgAction::Count)]
80    verbose: u8,
81
82    /// Automatically decide the scheduler's power mode (performance vs.
83    /// powersave vs. balanced), CPU preference order, etc, based on system
84    /// load. The options affecting the power mode and the use of core compaction
85    /// (--autopower, --performance, --powersave, --balanced,
86    /// --no-core-compaction) cannot be used with this option. When no option
87    /// is specified, this is a default mode.
88    #[clap(long = "autopilot", action = clap::ArgAction::SetTrue)]
89    autopilot: bool,
90
91    /// Automatically decide the scheduler's power mode (performance vs.
92    /// powersave vs. balanced) based on the system's active power profile.
93    /// The scheduler's power mode decides the CPU preference order and the use
94    /// of core compaction, so the options affecting these (--autopilot,
95    /// --performance, --powersave, --balanced, --no-core-compaction) cannot
96    /// be used with this option.
97    #[clap(long = "autopower", action = clap::ArgAction::SetTrue)]
98    autopower: bool,
99
100    /// Run the scheduler in performance mode to get maximum performance.
101    /// This option cannot be used with other conflicting options (--autopilot,
102    /// --autopower, --balanced, --powersave, --no-core-compaction)
103    /// affecting the use of core compaction.
104    #[clap(long = "performance", action = clap::ArgAction::SetTrue)]
105    performance: bool,
106
107    /// Run the scheduler in powersave mode to minimize powr consumption.
108    /// This option cannot be used with other conflicting options (--autopilot,
109    /// --autopower, --performance, --balanced, --no-core-compaction)
110    /// affecting the use of core compaction.
111    #[clap(long = "powersave", action = clap::ArgAction::SetTrue)]
112    powersave: bool,
113
114    /// Run the scheduler in balanced mode aiming for sweetspot between power
115    /// and performance. This option cannot be used with other conflicting
116    /// options (--autopilot, --autopower, --performance, --powersave,
117    /// --no-core-compaction) affecting the use of core compaction.
118    #[clap(long = "balanced", action = clap::ArgAction::SetTrue)]
119    balanced: bool,
120
121    /// Maximum scheduling slice duration in microseconds.
122    #[clap(long = "slice-max-us", default_value = "5000")]
123    slice_max_us: u64,
124
125    /// Minimum scheduling slice duration in microseconds.
126    #[clap(long = "slice-min-us", default_value = "500")]
127    slice_min_us: u64,
128
129    /// Migration delta threshold percentage (0-100). When set to a non-zero value,
130    /// uses average utilization for threshold calculation instead of current
131    /// utilization, and the threshold is calculated as: avg_load * (mig-delta-pct / 100).
132    /// Additionally, disables force task stealing in the consume path, relying only
133    /// on the is_stealer/is_stealee thresholds for more predictable load balancing.
134    /// Default is 0 (disabled, uses dynamic threshold based on load with both
135    /// probabilistic and force task stealing enabled). This is an experimental feature.
136    #[clap(long = "mig-delta-pct", default_value = "0", value_parser=Opts::mig_delta_pct_range)]
137    mig_delta_pct: u8,
138
139    /// Slice duration in microseconds to use for all tasks when pinned tasks
140    /// are running on a CPU. Must be between slice-min-us and slice-max-us.
141    /// When this option is enabled, pinned tasks are always enqueued to per-CPU DSQs
142    /// and the dispatch logic compares vtimes across all DSQs to select the lowest
143    /// vtime task. This helps improve responsiveness for pinned tasks. By default,
144    /// this option is on with a default value of 5000 (5 msec). To turn off the option,
145    /// explicitly set the value to 0.
146    #[clap(long = "pinned-slice-us", default_value = "5000")]
147    pinned_slice_us: Option<u64>,
148
149    /// Limit the ratio of preemption to the roughly top P% of latency-critical
150    /// tasks. When N is given as an argument, P is 0.5^N * 100. The default
151    /// value is 6, which limits the preemption for the top 1.56% of
152    /// latency-critical tasks.
153    #[clap(long = "preempt-shift", default_value = "6", value_parser=Opts::preempt_shift_range)]
154    preempt_shift: u8,
155
156    /// List of CPUs in preferred order (e.g., "0-3,7,6,5,4"). The scheduler
157    /// uses the CPU preference mode only when the core compaction is enabled
158    /// (i.e., balanced or powersave mode is specified as an option or chosen
159    /// in the autopilot or autopower mode). When "--cpu-pref-order" is given,
160    /// it implies "--no-use-em".
161    #[clap(long = "cpu-pref-order", default_value = "")]
162    cpu_pref_order: String,
163
164    /// Do not use the energy model in making CPU preference order decisions.
165    #[clap(long = "no-use-em", action = clap::ArgAction::SetTrue)]
166    no_use_em: bool,
167
168    /// Do not boost futex holders.
169    #[clap(long = "no-futex-boost", action = clap::ArgAction::SetTrue)]
170    no_futex_boost: bool,
171
172    /// Disable preemption.
173    #[clap(long = "no-preemption", action = clap::ArgAction::SetTrue)]
174    no_preemption: bool,
175
176    /// Disable an optimization for synchronous wake-up.
177    #[clap(long = "no-wake-sync", action = clap::ArgAction::SetTrue)]
178    no_wake_sync: bool,
179
180    /// Disable dynamic slice boost for long-running tasks.
181    #[clap(long = "no-slice-boost", action = clap::ArgAction::SetTrue)]
182    no_slice_boost: bool,
183
184    /// Enables DSQs per CPU, this enables task queuing and dispatching
185    /// from CPU specific DSQs. This generally increases L1/L2 cache
186    /// locality for tasks and lowers lock contention compared to shared DSQs,
187    /// but at the cost of higher load balancing complexity. This is a
188    /// highly experimental feature.
189    #[clap(long = "per-cpu-dsq", action = clap::ArgAction::SetTrue)]
190    per_cpu_dsq: bool,
191
192    /// Enable CPU bandwidth control using cpu.max in cgroup v2.
193    /// This is a highly experimental feature.
194    #[clap(long = "enable-cpu-bw", action = clap::ArgAction::SetTrue)]
195    enable_cpu_bw: bool,
196
197    ///
198    /// Disable core compaction so the scheduler uses all the online CPUs.
199    /// The core compaction attempts to minimize the number of actively used
200    /// CPUs for unaffinitized tasks, respecting the CPU preference order.
201    /// Normally, the core compaction is enabled by the power mode (i.e.,
202    /// balanced or powersave mode is specified as an option or chosen in
203    /// the autopilot or autopower mode). This option cannot be used with the
204    /// other options that control the core compaction (--autopilot,
205    /// --autopower, --performance, --balanced, --powersave).
206    #[clap(long = "no-core-compaction", action = clap::ArgAction::SetTrue)]
207    no_core_compaction: bool,
208
209    /// Disable controlling the CPU frequency.
210    #[clap(long = "no-freq-scaling", action = clap::ArgAction::SetTrue)]
211    no_freq_scaling: bool,
212
213    /// Enable stats monitoring with the specified interval.
214    #[clap(long)]
215    stats: Option<f64>,
216
217    /// Run in stats monitoring mode with the specified interval. Scheduler is not launched.
218    #[clap(long)]
219    monitor: Option<f64>,
220
221    /// Run in monitoring mode. Show the specified number of scheduling
222    /// samples every second.
223    #[clap(long)]
224    monitor_sched_samples: Option<u64>,
225
226    /// Specify the logging level. Accepts rust's envfilter syntax for modular
227    /// logging: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#example-syntax. Examples: ["info", "warn,tokio=info"]
228    #[clap(long, default_value = "info")]
229    log_level: String,
230
231    /// Print scheduler version and exit.
232    #[clap(short = 'V', long, action = clap::ArgAction::SetTrue)]
233    version: bool,
234
235    /// Optional run ID for tracking scheduler instances.
236    #[clap(long)]
237    run_id: Option<u64>,
238
239    /// Show descriptions for statistics.
240    #[clap(long)]
241    help_stats: bool,
242
243    #[clap(flatten, next_help_heading = "Libbpf Options")]
244    pub libbpf: LibbpfOpts,
245
246    /// Topology configuration options
247    #[clap(flatten)]
248    topology: Option<TopologyArgs>,
249}
250
251impl Opts {
252    fn can_autopilot(&self) -> bool {
253        self.autopower == false
254            && self.performance == false
255            && self.powersave == false
256            && self.balanced == false
257            && self.no_core_compaction == false
258    }
259
260    fn can_autopower(&self) -> bool {
261        self.autopilot == false
262            && self.performance == false
263            && self.powersave == false
264            && self.balanced == false
265            && self.no_core_compaction == false
266    }
267
268    fn can_performance(&self) -> bool {
269        self.autopilot == false
270            && self.autopower == false
271            && self.powersave == false
272            && self.balanced == false
273    }
274
275    fn can_balanced(&self) -> bool {
276        self.autopilot == false
277            && self.autopower == false
278            && self.performance == false
279            && self.powersave == false
280            && self.no_core_compaction == false
281    }
282
283    fn can_powersave(&self) -> bool {
284        self.autopilot == false
285            && self.autopower == false
286            && self.performance == false
287            && self.balanced == false
288            && self.no_core_compaction == false
289    }
290
291    fn proc(&mut self) -> Option<&mut Self> {
292        if !self.autopilot {
293            self.autopilot = self.can_autopilot();
294        }
295
296        if self.autopilot {
297            if !self.can_autopilot() {
298                info!("Autopilot mode cannot be used with conflicting options.");
299                return None;
300            }
301            info!("Autopilot mode is enabled.");
302        }
303
304        if self.autopower {
305            if !self.can_autopower() {
306                info!("Autopower mode cannot be used with conflicting options.");
307                return None;
308            }
309            info!("Autopower mode is enabled.");
310        }
311
312        if self.performance {
313            if !self.can_performance() {
314                info!("Performance mode cannot be used with conflicting options.");
315                return None;
316            }
317            info!("Performance mode is enabled.");
318            self.no_core_compaction = true;
319        }
320
321        if self.powersave {
322            if !self.can_powersave() {
323                info!("Powersave mode cannot be used with conflicting options.");
324                return None;
325            }
326            info!("Powersave mode is enabled.");
327            self.no_core_compaction = false;
328        }
329
330        if self.balanced {
331            if !self.can_balanced() {
332                info!("Balanced mode cannot be used with conflicting options.");
333                return None;
334            }
335            info!("Balanced mode is enabled.");
336            self.no_core_compaction = false;
337        }
338
339        if !EnergyModel::has_energy_model() || !self.cpu_pref_order.is_empty() {
340            self.no_use_em = true;
341            info!("Energy model won't be used for CPU preference order.");
342        }
343
344        if let Some(pinned_slice) = self.pinned_slice_us {
345            if pinned_slice == 0 {
346                info!("Pinned task slice mode is disabled. Pinned tasks will use per-domain DSQs.");
347            } else if pinned_slice < self.slice_min_us || pinned_slice > self.slice_max_us {
348                info!(
349                    "pinned-slice-us ({}) must be between slice-min-us ({}) and slice-max-us ({})",
350                    pinned_slice, self.slice_min_us, self.slice_max_us
351                );
352                return None;
353            } else {
354                info!(
355                "Pinned task slice mode is enabled ({} us). Pinned tasks will use per-CPU DSQs.",
356                pinned_slice
357            );
358            }
359        }
360
361        Some(self)
362    }
363
364    fn preempt_shift_range(s: &str) -> Result<u8, String> {
365        number_range(s, 0, 10)
366    }
367
368    fn mig_delta_pct_range(s: &str) -> Result<u8, String> {
369        number_range(s, 0, 100)
370    }
371}
372
373unsafe impl Plain for msg_task_ctx {}
374
375impl msg_task_ctx {
376    fn from_bytes(buf: &[u8]) -> &msg_task_ctx {
377        plain::from_bytes(buf).expect("The buffer is either too short or not aligned!")
378    }
379}
380
381impl introspec {
382    fn new() -> Self {
383        let intrspc = unsafe { mem::MaybeUninit::<introspec>::zeroed().assume_init() };
384        intrspc
385    }
386}
387
388struct Scheduler<'a> {
389    skel: BpfSkel<'a>,
390    struct_ops: Option<libbpf_rs::Link>,
391    rb_mgr: libbpf_rs::RingBuffer<'static>,
392    intrspc: introspec,
393    intrspc_rx: Receiver<SchedSample>,
394    monitor_tid: Option<ThreadId>,
395    stats_server: StatsServer<StatsReq, StatsRes>,
396    mseq_id: u64,
397}
398
399impl<'a> Scheduler<'a> {
400    fn init(opts: &'a Opts, open_object: &'a mut MaybeUninit<OpenObject>) -> Result<Self> {
401        if *NR_CPU_IDS > LAVD_CPU_ID_MAX as usize {
402            panic!(
403                "Num possible CPU IDs ({}) exceeds maximum of ({})",
404                *NR_CPU_IDS, LAVD_CPU_ID_MAX
405            );
406        }
407
408        try_set_rlimit_infinity();
409
410        // Open the BPF prog first for verification.
411        let debug_level = if opts.log_level.contains("trace") {
412            2
413        } else if opts.log_level.contains("debug") {
414            1
415        } else {
416            0
417        };
418        let mut skel_builder = BpfSkelBuilder::default();
419        skel_builder.obj_builder.debug(debug_level > 1);
420        init_libbpf_logging(Some(PrintLevel::Debug));
421
422        let open_opts = opts.libbpf.clone().into_bpf_open_opts();
423        let mut skel = scx_ops_open!(skel_builder, open_object, lavd_ops, open_opts)?;
424
425        // Enable futex tracing using ftrace if available. If the ftrace is not
426        // available, use tracepoint, which is known to be slower than ftrace.
427        if !opts.no_futex_boost {
428            if Self::attach_futex_ftraces(&mut skel)? == false {
429                info!("Fail to attach futex ftraces. Try with tracepoints.");
430                if Self::attach_futex_tracepoints(&mut skel)? == false {
431                    info!("Fail to attach futex tracepoints.");
432                }
433            }
434        }
435
436        // Initialize CPU topology with CLI arguments
437        let order = CpuOrder::new(opts.topology.as_ref()).unwrap();
438        Self::init_cpus(&mut skel, &order);
439        Self::init_cpdoms(&mut skel, &order);
440
441        // Initialize skel according to @opts.
442        Self::init_globals(&mut skel, &opts, &order, debug_level);
443
444        // Initialize arena
445        let mut skel = scx_ops_load!(skel, lavd_ops, uei)?;
446        let task_size = std::mem::size_of::<types::task_ctx>();
447        let arenalib = ArenaLib::init(skel.object_mut(), task_size, *NR_CPU_IDS)?;
448        arenalib.setup()?;
449
450        // Attach.
451        let struct_ops = Some(scx_ops_attach!(skel, lavd_ops)?);
452        let stats_server = StatsServer::new(stats::server_data(*NR_CPU_IDS as u64)).launch()?;
453
454        // Build a ring buffer for instrumentation
455        let (intrspc_tx, intrspc_rx) = channel::bounded(65536);
456        let rb_map = &mut skel.maps.introspec_msg;
457        let mut builder = libbpf_rs::RingBufferBuilder::new();
458        builder
459            .add(rb_map, move |data| {
460                Scheduler::relay_introspec(data, &intrspc_tx)
461            })
462            .unwrap();
463        let rb_mgr = builder.build().unwrap();
464
465        Ok(Self {
466            skel,
467            struct_ops,
468            rb_mgr,
469            intrspc: introspec::new(),
470            intrspc_rx,
471            monitor_tid: None,
472            stats_server,
473            mseq_id: 0,
474        })
475    }
476
477    fn attach_futex_ftraces(skel: &mut OpenBpfSkel) -> Result<bool> {
478        let ftraces = vec![
479            ("__futex_wait", &skel.progs.fexit___futex_wait),
480            ("futex_wait_multiple", &skel.progs.fexit_futex_wait_multiple),
481            (
482                "futex_wait_requeue_pi",
483                &skel.progs.fexit_futex_wait_requeue_pi,
484            ),
485            ("futex_wake", &skel.progs.fexit_futex_wake),
486            ("futex_wake_op", &skel.progs.fexit_futex_wake_op),
487            ("futex_lock_pi", &skel.progs.fexit_futex_lock_pi),
488            ("futex_unlock_pi", &skel.progs.fexit_futex_unlock_pi),
489        ];
490
491        if compat::tracer_available("function")? == false {
492            info!("Ftrace is not enabled in the kernel.");
493            return Ok(false);
494        }
495
496        compat::cond_kprobes_enable(ftraces)
497    }
498
499    fn attach_futex_tracepoints(skel: &mut OpenBpfSkel) -> Result<bool> {
500        let tracepoints = vec![
501            ("syscalls:sys_enter_futex", &skel.progs.rtp_sys_enter_futex),
502            ("syscalls:sys_exit_futex", &skel.progs.rtp_sys_exit_futex),
503            (
504                "syscalls:sys_exit_futex_wait",
505                &skel.progs.rtp_sys_exit_futex_wait,
506            ),
507            (
508                "syscalls:sys_exit_futex_waitv",
509                &skel.progs.rtp_sys_exit_futex_waitv,
510            ),
511            (
512                "syscalls:sys_exit_futex_wake",
513                &skel.progs.rtp_sys_exit_futex_wake,
514            ),
515        ];
516
517        compat::cond_tracepoints_enable(tracepoints)
518    }
519
520    fn init_cpus(skel: &mut OpenBpfSkel, order: &CpuOrder) {
521        debug!("{:#?}", order);
522
523        // Initialize CPU capacity and sibling
524        for cpu in order.cpuids.iter() {
525            skel.maps.rodata_data.as_mut().unwrap().cpu_capacity[cpu.cpu_adx] = cpu.cpu_cap as u16;
526            skel.maps.rodata_data.as_mut().unwrap().cpu_big[cpu.cpu_adx] = cpu.big_core as u8;
527            skel.maps.rodata_data.as_mut().unwrap().cpu_turbo[cpu.cpu_adx] = cpu.turbo_core as u8;
528            skel.maps.rodata_data.as_mut().unwrap().cpu_sibling[cpu.cpu_adx] =
529                cpu.cpu_sibling as u32;
530        }
531
532        // Initialize performance vs. CPU order table.
533        let nr_pco_states: u8 = order.perf_cpu_order.len() as u8;
534        if nr_pco_states > LAVD_PCO_STATE_MAX as u8 {
535            panic!("Generated performance vs. CPU order stats are too complex ({nr_pco_states}) to handle");
536        }
537
538        skel.maps.rodata_data.as_mut().unwrap().nr_pco_states = nr_pco_states;
539        for (i, (_, pco)) in order.perf_cpu_order.iter().enumerate() {
540            Self::init_pco_tuple(skel, i, &pco);
541            info!("{:#}", pco);
542        }
543
544        let (_, last_pco) = order.perf_cpu_order.last_key_value().unwrap();
545        for i in nr_pco_states..LAVD_PCO_STATE_MAX as u8 {
546            Self::init_pco_tuple(skel, i as usize, &last_pco);
547        }
548    }
549
550    fn init_pco_tuple(skel: &mut OpenBpfSkel, i: usize, pco: &PerfCpuOrder) {
551        let cpus_perf = pco.cpus_perf.borrow();
552        let cpus_ovflw = pco.cpus_ovflw.borrow();
553        let pco_nr_primary = cpus_perf.len();
554
555        skel.maps.rodata_data.as_mut().unwrap().pco_bounds[i] = pco.perf_cap as u32;
556        skel.maps.rodata_data.as_mut().unwrap().pco_nr_primary[i] = pco_nr_primary as u16;
557
558        for (j, &cpu_adx) in cpus_perf.iter().enumerate() {
559            skel.maps.rodata_data.as_mut().unwrap().pco_table[i][j] = cpu_adx as u16;
560        }
561
562        for (j, &cpu_adx) in cpus_ovflw.iter().enumerate() {
563            let k = j + pco_nr_primary;
564            skel.maps.rodata_data.as_mut().unwrap().pco_table[i][k] = cpu_adx as u16;
565        }
566    }
567
568    fn init_cpdoms(skel: &mut OpenBpfSkel, order: &CpuOrder) {
569        // Initialize compute domain contexts
570        for (k, v) in order.cpdom_map.iter() {
571            skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].id = v.cpdom_id as u64;
572            skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].alt_id =
573                v.cpdom_alt_id.get() as u64;
574            skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].numa_id = k.numa_adx as u8;
575            skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].llc_id = k.llc_adx as u8;
576            skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].is_big = k.is_big as u8;
577            skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].is_valid = 1;
578            for cpu_id in v.cpu_ids.iter() {
579                let i = cpu_id / 64;
580                let j = cpu_id % 64;
581                skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].__cpumask[i] |=
582                    0x01 << j;
583            }
584
585            if v.neighbor_map.borrow().iter().len() > LAVD_CPDOM_MAX_DIST as usize {
586                panic!("The processor topology is too complex to handle in BPF.");
587            }
588
589            for (k, (_d, neighbors)) in v.neighbor_map.borrow().iter().enumerate() {
590                let nr_neighbors = neighbors.borrow().len() as u8;
591                if nr_neighbors > LAVD_CPDOM_MAX_NR as u8 {
592                    panic!("The processor topology is too complex to handle in BPF.");
593                }
594                skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].nr_neighbors[k] =
595                    nr_neighbors;
596                for (i, &id) in neighbors.borrow().iter().enumerate() {
597                    let idx = (k * LAVD_CPDOM_MAX_NR as usize) + i;
598                    skel.maps.bss_data.as_mut().unwrap().cpdom_ctxs[v.cpdom_id].neighbor_ids[idx] =
599                        id as u8;
600                }
601            }
602        }
603    }
604
605    fn init_globals(skel: &mut OpenBpfSkel, opts: &Opts, order: &CpuOrder, debug_level: u8) {
606        let bss_data = skel.maps.bss_data.as_mut().unwrap();
607        bss_data.no_preemption = opts.no_preemption;
608        bss_data.no_core_compaction = opts.no_core_compaction;
609        bss_data.no_freq_scaling = opts.no_freq_scaling;
610        bss_data.is_powersave_mode = opts.powersave;
611        let rodata = skel.maps.rodata_data.as_mut().unwrap();
612        rodata.nr_llcs = order.nr_llcs as u64;
613        rodata.nr_cpu_ids = *NR_CPU_IDS as u32;
614        rodata.is_smt_active = order.smt_enabled;
615        rodata.is_autopilot_on = opts.autopilot;
616        rodata.verbose = debug_level;
617        rodata.slice_max_ns = opts.slice_max_us * 1000;
618        rodata.slice_min_ns = opts.slice_min_us * 1000;
619        rodata.pinned_slice_ns = opts.pinned_slice_us.map(|v| v * 1000).unwrap_or(0);
620        rodata.preempt_shift = opts.preempt_shift;
621        rodata.mig_delta_pct = opts.mig_delta_pct;
622        rodata.no_use_em = opts.no_use_em as u8;
623        rodata.no_wake_sync = opts.no_wake_sync;
624        rodata.no_slice_boost = opts.no_slice_boost;
625        rodata.per_cpu_dsq = opts.per_cpu_dsq;
626        rodata.enable_cpu_bw = opts.enable_cpu_bw;
627
628        if !ksym_exists("scx_group_set_bandwidth").unwrap() {
629            skel.struct_ops.lavd_ops_mut().cgroup_set_bandwidth = std::ptr::null_mut();
630            warn!("Kernel does not support ops.cgroup_set_bandwidth(), so disable it.");
631        }
632
633        skel.struct_ops.lavd_ops_mut().flags = *compat::SCX_OPS_ENQ_EXITING
634            | *compat::SCX_OPS_ENQ_LAST
635            | *compat::SCX_OPS_ENQ_MIGRATION_DISABLED
636            | *compat::SCX_OPS_KEEP_BUILTIN_IDLE;
637    }
638
639    fn get_msg_seq_id() -> u64 {
640        static mut MSEQ: u64 = 0;
641        unsafe {
642            MSEQ += 1;
643            MSEQ
644        }
645    }
646
647    fn relay_introspec(data: &[u8], intrspc_tx: &Sender<SchedSample>) -> i32 {
648        let mt = msg_task_ctx::from_bytes(data);
649        let tx = mt.taskc_x;
650
651        // No idea how to print other types than LAVD_MSG_TASKC
652        if mt.hdr.kind != LAVD_MSG_TASKC {
653            return 0;
654        }
655
656        let mseq = Scheduler::get_msg_seq_id();
657
658        let c_tx_cm: *const c_char = (&tx.comm as *const [c_char; 17]) as *const c_char;
659        let c_tx_cm_str: &CStr = unsafe { CStr::from_ptr(c_tx_cm) };
660        let tx_comm: &str = c_tx_cm_str.to_str().unwrap();
661
662        let c_waker_cm: *const c_char = (&tx.waker_comm as *const [c_char; 17]) as *const c_char;
663        let c_waker_cm_str: &CStr = unsafe { CStr::from_ptr(c_waker_cm) };
664        let waker_comm: &str = c_waker_cm_str.to_str().unwrap();
665
666        let c_tx_st: *const c_char = (&tx.stat as *const [c_char; 5]) as *const c_char;
667        let c_tx_st_str: &CStr = unsafe { CStr::from_ptr(c_tx_st) };
668        let tx_stat: &str = c_tx_st_str.to_str().unwrap();
669
670        match intrspc_tx.try_send(SchedSample {
671            mseq,
672            pid: tx.pid,
673            comm: tx_comm.into(),
674            stat: tx_stat.into(),
675            cpu_id: tx.cpu_id,
676            prev_cpu_id: tx.prev_cpu_id,
677            suggested_cpu_id: tx.suggested_cpu_id,
678            waker_pid: tx.waker_pid,
679            waker_comm: waker_comm.into(),
680            slice: tx.slice,
681            lat_cri: tx.lat_cri,
682            avg_lat_cri: tx.avg_lat_cri,
683            static_prio: tx.static_prio,
684            rerunnable_interval: tx.rerunnable_interval,
685            resched_interval: tx.resched_interval,
686            run_freq: tx.run_freq,
687            avg_runtime: tx.avg_runtime,
688            wait_freq: tx.wait_freq,
689            wake_freq: tx.wake_freq,
690            perf_cri: tx.perf_cri,
691            thr_perf_cri: tx.thr_perf_cri,
692            cpuperf_cur: tx.cpuperf_cur,
693            cpu_util: tx.cpu_util,
694            cpu_sutil: tx.cpu_sutil,
695            nr_active: tx.nr_active,
696            dsq_id: tx.dsq_id,
697            dsq_consume_lat: tx.dsq_consume_lat,
698            slice_used: tx.last_slice_used,
699        }) {
700            Ok(()) | Err(TrySendError::Full(_)) => 0,
701            Err(e) => panic!("failed to send on intrspc_tx ({})", e),
702        }
703    }
704
705    fn prep_introspec(&mut self) {
706        if !self.skel.maps.bss_data.as_ref().unwrap().is_monitored {
707            self.skel.maps.bss_data.as_mut().unwrap().is_monitored = true;
708        }
709        self.skel.maps.bss_data.as_mut().unwrap().intrspc.cmd = self.intrspc.cmd;
710        self.skel.maps.bss_data.as_mut().unwrap().intrspc.arg = self.intrspc.arg;
711    }
712
713    fn cleanup_introspec(&mut self) {
714        self.skel.maps.bss_data.as_mut().unwrap().intrspc.cmd = LAVD_CMD_NOP;
715    }
716
717    fn get_pc(x: u64, y: u64) -> f64 {
718        return 100. * x as f64 / y as f64;
719    }
720
721    fn get_power_mode(power_mode: i32) -> &'static str {
722        match power_mode as u32 {
723            LAVD_PM_PERFORMANCE => "performance",
724            LAVD_PM_BALANCED => "balanced",
725            LAVD_PM_POWERSAVE => "powersave",
726            _ => "unknown",
727        }
728    }
729
730    fn stats_req_to_res(&mut self, req: &StatsReq) -> Result<StatsRes> {
731        Ok(match req {
732            StatsReq::NewSampler(tid) => {
733                self.rb_mgr.consume().unwrap();
734                self.monitor_tid = Some(*tid);
735                StatsRes::Ack
736            }
737            StatsReq::SysStatsReq { tid } => {
738                if Some(*tid) != self.monitor_tid {
739                    return Ok(StatsRes::Bye);
740                }
741                self.mseq_id += 1;
742
743                let bss_data = self.skel.maps.bss_data.as_ref().unwrap();
744                let st = bss_data.sys_stat;
745
746                let mseq = self.mseq_id;
747                let nr_queued_task = st.nr_queued_task;
748                let nr_active = st.nr_active;
749                let nr_sched = st.nr_sched;
750                let nr_preempt = st.nr_preempt;
751                let pc_pc = Self::get_pc(st.nr_perf_cri, nr_sched);
752                let pc_lc = Self::get_pc(st.nr_lat_cri, nr_sched);
753                let pc_x_migration = Self::get_pc(st.nr_x_migration, nr_sched);
754                let nr_stealee = st.nr_stealee;
755                let nr_big = st.nr_big;
756                let pc_big = Self::get_pc(nr_big, nr_sched);
757                let pc_pc_on_big = Self::get_pc(st.nr_pc_on_big, nr_big);
758                let pc_lc_on_big = Self::get_pc(st.nr_lc_on_big, nr_big);
759                let power_mode = Self::get_power_mode(bss_data.power_mode);
760                let total_time = bss_data.performance_mode_ns
761                    + bss_data.balanced_mode_ns
762                    + bss_data.powersave_mode_ns;
763                let pc_performance = Self::get_pc(bss_data.performance_mode_ns, total_time);
764                let pc_balanced = Self::get_pc(bss_data.balanced_mode_ns, total_time);
765                let pc_powersave = Self::get_pc(bss_data.powersave_mode_ns, total_time);
766
767                StatsRes::SysStats(SysStats {
768                    mseq,
769                    nr_queued_task,
770                    nr_active,
771                    nr_sched,
772                    nr_preempt,
773                    pc_pc,
774                    pc_lc,
775                    pc_x_migration,
776                    nr_stealee,
777                    pc_big,
778                    pc_pc_on_big,
779                    pc_lc_on_big,
780                    power_mode: power_mode.to_string(),
781                    pc_performance,
782                    pc_balanced,
783                    pc_powersave,
784                })
785            }
786            StatsReq::SchedSamplesNr {
787                tid,
788                nr_samples,
789                interval_ms,
790            } => {
791                if Some(*tid) != self.monitor_tid {
792                    return Ok(StatsRes::Bye);
793                }
794
795                self.intrspc.cmd = LAVD_CMD_SCHED_N;
796                self.intrspc.arg = *nr_samples;
797                self.prep_introspec();
798                std::thread::sleep(Duration::from_millis(*interval_ms));
799                self.rb_mgr.poll(Duration::from_millis(100)).unwrap();
800
801                let mut samples = vec![];
802                while let Ok(ts) = self.intrspc_rx.try_recv() {
803                    samples.push(ts);
804                }
805
806                self.cleanup_introspec();
807
808                StatsRes::SchedSamples(SchedSamples { samples })
809            }
810        })
811    }
812
813    fn stop_monitoring(&mut self) {
814        if self.skel.maps.bss_data.as_ref().unwrap().is_monitored {
815            self.skel.maps.bss_data.as_mut().unwrap().is_monitored = false;
816        }
817    }
818
819    pub fn exited(&mut self) -> bool {
820        uei_exited!(&self.skel, uei)
821    }
822
823    fn set_power_profile(&mut self, mode: u32) -> Result<(), u32> {
824        let prog = &mut self.skel.progs.set_power_profile;
825        let mut args = power_arg {
826            power_mode: mode as c_int,
827        };
828        let input = ProgramInput {
829            context_in: Some(unsafe {
830                std::slice::from_raw_parts_mut(
831                    &mut args as *mut _ as *mut u8,
832                    std::mem::size_of_val(&args),
833                )
834            }),
835            ..Default::default()
836        };
837        let out = prog.test_run(input).unwrap();
838        if out.return_value != 0 {
839            return Err(out.return_value);
840        }
841
842        Ok(())
843    }
844
845    fn update_power_profile(&mut self, prev_profile: PowerProfile) -> (bool, PowerProfile) {
846        let profile = fetch_power_profile(false);
847        if profile == prev_profile {
848            // If the profile is the same, skip updaring the profile for BPF.
849            return (true, profile);
850        }
851
852        let _ = match profile {
853            PowerProfile::Performance => self.set_power_profile(LAVD_PM_PERFORMANCE),
854            PowerProfile::Balanced { .. } => self.set_power_profile(LAVD_PM_BALANCED),
855            PowerProfile::Powersave => self.set_power_profile(LAVD_PM_POWERSAVE),
856            PowerProfile::Unknown => {
857                // We don't know how to handle an unknown energy profile,
858                // so we just give up updating the profile from now on.
859                return (false, profile);
860            }
861        };
862
863        info!("Set the scheduler's power profile to {profile} mode.");
864        (true, profile)
865    }
866
867    fn run(&mut self, opts: &Opts, shutdown: Arc<AtomicBool>) -> Result<UserExitInfo> {
868        let (res_ch, req_ch) = self.stats_server.channels();
869        let mut autopower = opts.autopower;
870        let mut profile = PowerProfile::Unknown;
871
872        if opts.performance {
873            let _ = self.set_power_profile(LAVD_PM_PERFORMANCE);
874        } else if opts.powersave {
875            let _ = self.set_power_profile(LAVD_PM_POWERSAVE);
876        } else {
877            let _ = self.set_power_profile(LAVD_PM_BALANCED);
878        }
879
880        while !shutdown.load(Ordering::Relaxed) && !self.exited() {
881            if autopower {
882                (autopower, profile) = self.update_power_profile(profile);
883            }
884
885            match req_ch.recv_timeout(Duration::from_secs(1)) {
886                Ok(req) => {
887                    let res = self.stats_req_to_res(&req)?;
888                    res_ch.send(res)?;
889                }
890                Err(RecvTimeoutError::Timeout) => {
891                    self.stop_monitoring();
892                }
893                Err(e) => {
894                    self.stop_monitoring();
895                    Err(e)?
896                }
897            }
898            self.cleanup_introspec();
899        }
900        self.rb_mgr.consume().unwrap();
901
902        let _ = self.struct_ops.take();
903        uei_report!(&self.skel, uei)
904    }
905}
906
907impl Drop for Scheduler<'_> {
908    fn drop(&mut self) {
909        info!("Unregister {SCHEDULER_NAME} scheduler");
910
911        if let Some(struct_ops) = self.struct_ops.take() {
912            drop(struct_ops);
913        }
914    }
915}
916
917fn init_log(opts: &Opts) {
918    let env_filter = EnvFilter::try_from_default_env()
919        .or_else(|_| match EnvFilter::try_new(&opts.log_level) {
920            Ok(filter) => Ok(filter),
921            Err(e) => {
922                eprintln!(
923                    "invalid log envvar: {}, using info, err is: {}",
924                    opts.log_level, e
925                );
926                EnvFilter::try_new("info")
927            }
928        })
929        .unwrap_or_else(|_| EnvFilter::new("info"));
930
931    match tracing_subscriber::fmt()
932        .with_env_filter(env_filter)
933        .with_target(true)
934        .with_thread_ids(true)
935        .with_file(true)
936        .with_line_number(true)
937        .try_init()
938    {
939        Ok(()) => {}
940        Err(e) => eprintln!("failed to init logger: {}", e),
941    }
942}
943
944#[clap_main::clap_main]
945fn main(mut opts: Opts) -> Result<()> {
946    if opts.version {
947        println!(
948            "scx_lavd {}",
949            build_id::full_version(env!("CARGO_PKG_VERSION"))
950        );
951        return Ok(());
952    }
953
954    if opts.help_stats {
955        let sys_stats_meta_name = SysStats::meta().name;
956        let sched_sample_meta_name = SchedSample::meta().name;
957        let stats_meta_names: &[&str] = &[
958            sys_stats_meta_name.as_str(),
959            sched_sample_meta_name.as_str(),
960        ];
961        stats::server_data(0).describe_meta(&mut std::io::stdout(), Some(&stats_meta_names))?;
962        return Ok(());
963    }
964
965    init_log(&opts);
966
967    if opts.verbose > 0 {
968        warn!("Setting verbose via -v is depricated and will be an error in future releases.");
969    }
970
971    if let Some(run_id) = opts.run_id {
972        info!("scx_lavd run_id: {}", run_id);
973    }
974
975    if opts.monitor.is_none() && opts.monitor_sched_samples.is_none() {
976        opts.proc().unwrap();
977        info!("{:#?}", opts);
978    }
979
980    let shutdown = Arc::new(AtomicBool::new(false));
981    let shutdown_clone = shutdown.clone();
982    ctrlc::set_handler(move || {
983        shutdown_clone.store(true, Ordering::Relaxed);
984    })
985    .context("Error setting Ctrl-C handler")?;
986
987    if let Some(nr_samples) = opts.monitor_sched_samples {
988        let shutdown_copy = shutdown.clone();
989        let jh = std::thread::spawn(move || {
990            stats::monitor_sched_samples(nr_samples, shutdown_copy).unwrap()
991        });
992        let _ = jh.join();
993        return Ok(());
994    }
995
996    if let Some(intv) = opts.monitor.or(opts.stats) {
997        let shutdown_copy = shutdown.clone();
998        let jh = std::thread::spawn(move || {
999            stats::monitor(Duration::from_secs_f64(intv), shutdown_copy).unwrap()
1000        });
1001        if opts.monitor.is_some() {
1002            let _ = jh.join();
1003            return Ok(());
1004        }
1005    }
1006
1007    let mut open_object = MaybeUninit::uninit();
1008    loop {
1009        let mut sched = Scheduler::init(&opts, &mut open_object)?;
1010        info!(
1011            "scx_lavd scheduler is initialized (build ID: {})",
1012            build_id::full_version(env!("CARGO_PKG_VERSION"))
1013        );
1014        info!("scx_lavd scheduler starts running.");
1015        if !sched.run(&opts, shutdown.clone())?.should_restart() {
1016            break;
1017        }
1018    }
1019
1020    Ok(())
1021}