Skip to main content

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