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