scx_bpfland/
main.rs

1// SPDX-License-Identifier: GPL-2.0
2//
3// Copyright (c) 2024 Andrea Righi <andrea.righi@linux.dev>
4
5// This software may be used and distributed according to the terms of the
6// GNU General Public License version 2.
7
8mod bpf_skel;
9pub use bpf_skel::*;
10pub mod bpf_intf;
11pub use bpf_intf::*;
12
13mod stats;
14use std::collections::BTreeMap;
15use std::ffi::c_int;
16use std::fmt::Write;
17use std::mem::MaybeUninit;
18use std::sync::atomic::AtomicBool;
19use std::sync::atomic::Ordering;
20use std::sync::Arc;
21use std::time::Duration;
22
23use anyhow::Context;
24use anyhow::Result;
25use clap::Parser;
26use crossbeam::channel::RecvTimeoutError;
27use libbpf_rs::OpenObject;
28use libbpf_rs::ProgramInput;
29use log::warn;
30use log::{debug, info};
31use scx_stats::prelude::*;
32use scx_utils::autopower::{fetch_power_profile, PowerProfile};
33use scx_utils::build_id;
34use scx_utils::compat;
35use scx_utils::pm::{cpu_idle_resume_latency_supported, update_cpu_idle_resume_latency};
36use scx_utils::scx_ops_attach;
37use scx_utils::scx_ops_load;
38use scx_utils::scx_ops_open;
39use scx_utils::set_rlimit_infinity;
40use scx_utils::uei_exited;
41use scx_utils::uei_report;
42use scx_utils::CoreType;
43use scx_utils::Cpumask;
44use scx_utils::Topology;
45use scx_utils::UserExitInfo;
46use scx_utils::NR_CPU_IDS;
47use stats::Metrics;
48
49const SCHEDULER_NAME: &str = "scx_bpfland";
50
51#[derive(PartialEq)]
52enum Powermode {
53    Performance,
54    Powersave,
55    Any,
56}
57
58fn get_primary_cpus(mode: Powermode) -> std::io::Result<Vec<usize>> {
59    let topo = Topology::new().unwrap();
60
61    let cpus: Vec<usize> = topo
62        .all_cores
63        .values()
64        .flat_map(|core| &core.cpus)
65        .filter_map(|(cpu_id, cpu)| match (&mode, &cpu.core_type) {
66            // Performance mode: add all the Big CPUs (either Turbo or non-Turbo)
67            (Powermode::Performance, CoreType::Big { .. }) |
68            // Powersave mode: add all the Little CPUs
69            (Powermode::Powersave, CoreType::Little) => Some(*cpu_id),
70            (Powermode::Any, ..) => Some(*cpu_id),
71            _ => None,
72        })
73        .collect();
74
75    Ok(cpus)
76}
77
78// Convert an array of CPUs to the corresponding cpumask of any arbitrary size.
79fn cpus_to_cpumask(cpus: &Vec<usize>) -> String {
80    if cpus.is_empty() {
81        return String::from("none");
82    }
83
84    // Determine the maximum CPU ID to create a sufficiently large byte vector.
85    let max_cpu_id = *cpus.iter().max().unwrap();
86
87    // Create a byte vector with enough bytes to cover all CPU IDs.
88    let mut bitmask = vec![0u8; (max_cpu_id + 1 + 7) / 8];
89
90    // Set the appropriate bits for each CPU ID.
91    for cpu_id in cpus {
92        let byte_index = cpu_id / 8;
93        let bit_index = cpu_id % 8;
94        bitmask[byte_index] |= 1 << bit_index;
95    }
96
97    // Convert the byte vector to a hexadecimal string.
98    let hex_str: String = bitmask.iter().rev().fold(String::new(), |mut f, byte| {
99        let _ = write!(&mut f, "{:02x}", byte);
100        f
101    });
102
103    format!("0x{}", hex_str)
104}
105
106/// scx_bpfland: a vruntime-based sched_ext scheduler that prioritizes interactive workloads.
107///
108/// This scheduler is derived from scx_rustland, but it is fully implemented in BPF. It has a minimal
109/// user-space part written in Rust to process command line options, collect metrics and log out
110/// scheduling statistics.
111///
112/// The BPF part makes all the scheduling decisions (see src/bpf/main.bpf.c).
113#[derive(Debug, Parser)]
114struct Opts {
115    /// Exit debug dump buffer length. 0 indicates default.
116    #[clap(long, default_value = "0")]
117    exit_dump_len: u32,
118
119    /// Maximum scheduling slice duration in microseconds.
120    #[clap(short = 's', long, default_value = "20000")]
121    slice_us: u64,
122
123    /// Minimum scheduling slice duration in microseconds.
124    #[clap(short = 'S', long, default_value = "1000")]
125    slice_us_min: u64,
126
127    /// Maximum time slice lag in microseconds.
128    ///
129    /// A positive value can help to enhance the responsiveness of interactive tasks, but it can
130    /// also make performance more "spikey".
131    ///
132    /// A negative value can make performance more consistent, but it can also reduce the
133    /// responsiveness of interactive tasks (by smoothing the effect of the vruntime scheduling and
134    /// making the task ordering closer to a FIFO).
135    #[clap(short = 'l', long, allow_hyphen_values = true, default_value = "20000")]
136    slice_us_lag: i64,
137
138    /// Throttle the running CPUs by periodically injecting idle cycles.
139    ///
140    /// This option can help extend battery life on portable devices, reduce heating, fan noise
141    /// and overall energy consumption (0 = disable).
142    #[clap(short = 't', long, default_value = "0")]
143    throttle_us: u64,
144
145    /// Set CPU idle QoS resume latency in microseconds (-1 = disabled).
146    ///
147    /// Setting a lower latency value makes CPUs less likely to enter deeper idle states, enhancing
148    /// performance at the cost of higher power consumption. Alternatively, increasing the latency
149    /// value may reduce performance, but also improve power efficiency.
150    #[clap(short = 'I', long, allow_hyphen_values = true, default_value = "-1")]
151    idle_resume_us: i64,
152
153    /// Disable preemption.
154    ///
155    /// Never allow tasks to be directly dispatched. This can help to increase fairness
156    /// over responsiveness.
157    #[clap(short = 'n', long, action = clap::ArgAction::SetTrue)]
158    no_preempt: bool,
159
160    /// Enable per-CPU tasks prioritization.
161    ///
162    /// This allows to prioritize per-CPU tasks that usually tend to be de-prioritized (since they
163    /// can't be migrated when their only usable CPU is busy). Enabling this option can introduce
164    /// unfairness and potentially trigger stalls, but it can improve performance of server-type
165    /// workloads (such as large parallel builds).
166    #[clap(short = 'p', long, action = clap::ArgAction::SetTrue)]
167    local_pcpu: bool,
168
169    /// Enable kthreads prioritization (EXPERIMENTAL).
170    ///
171    /// Enabling this can improve system performance, but it may also introduce noticeable
172    /// interactivity issues or unfairness in scenarios with high kthread activity, such as heavy
173    /// I/O or network traffic.
174    ///
175    /// Use it only when conducting specific experiments or if you have a clear understanding of
176    /// its implications.
177    #[clap(short = 'k', long, action = clap::ArgAction::SetTrue)]
178    local_kthreads: bool,
179
180    /// Disable direct dispatch during synchronous wakeups.
181    ///
182    /// Enabling this option can lead to a more uniform load distribution across available cores,
183    /// potentially improving performance in certain scenarios. However, it may come at the cost of
184    /// reduced efficiency for pipe-intensive workloads that benefit from tighter producer-consumer
185    /// coupling.
186    #[clap(short = 'w', long, action = clap::ArgAction::SetTrue)]
187    no_wake_sync: bool,
188
189    /// Specifies the initial set of CPUs, represented as a bitmask in hex (e.g., 0xff), that the
190    /// scheduler will use to dispatch tasks, until the system becomes saturated, at which point
191    /// tasks may overflow to other available CPUs.
192    ///
193    /// Special values:
194    ///  - "auto" = automatically detect the CPUs based on the active power profile
195    ///  - "performance" = automatically detect and prioritize the fastest CPUs
196    ///  - "powersave" = automatically detect and prioritize the slowest CPUs
197    ///  - "all" = all CPUs assigned to the primary domain
198    ///  - "none" = no prioritization, tasks are dispatched on the first CPU available
199    #[clap(short = 'm', long, default_value = "auto")]
200    primary_domain: String,
201
202    /// Disable L2 cache awareness.
203    #[clap(long, action = clap::ArgAction::SetTrue)]
204    disable_l2: bool,
205
206    /// Disable L3 cache awareness.
207    #[clap(long, action = clap::ArgAction::SetTrue)]
208    disable_l3: bool,
209
210    /// Disable SMT awareness.
211    #[clap(long, action = clap::ArgAction::SetTrue)]
212    disable_smt: bool,
213
214    /// Disable NUMA rebalancing.
215    #[clap(long, action = clap::ArgAction::SetTrue)]
216    disable_numa: bool,
217
218    /// Enable CPU frequency control (only with schedutil governor).
219    ///
220    /// With this option enabled the CPU frequency will be automatically scaled based on the load.
221    #[clap(short = 'f', long, action = clap::ArgAction::SetTrue)]
222    cpufreq: bool,
223
224    /// [DEPRECATED] Maximum threshold of voluntary context switches per second. This is used to
225    /// classify interactive.
226    ///
227    /// tasks (0 = disable interactive tasks classification).
228    #[clap(short = 'c', long, default_value = "10", hide = true)]
229    nvcsw_max_thresh: u64,
230
231    /// Enable stats monitoring with the specified interval.
232    #[clap(long)]
233    stats: Option<f64>,
234
235    /// Run in stats monitoring mode with the specified interval. Scheduler
236    /// is not launched.
237    #[clap(long)]
238    monitor: Option<f64>,
239
240    /// Enable BPF debugging via /sys/kernel/tracing/trace_pipe.
241    #[clap(short = 'd', long, action = clap::ArgAction::SetTrue)]
242    debug: bool,
243
244    /// Enable verbose output, including libbpf details.
245    #[clap(short = 'v', long, action = clap::ArgAction::SetTrue)]
246    verbose: bool,
247
248    /// Print scheduler version and exit.
249    #[clap(short = 'V', long, action = clap::ArgAction::SetTrue)]
250    version: bool,
251
252    /// Show descriptions for statistics.
253    #[clap(long)]
254    help_stats: bool,
255}
256
257struct Scheduler<'a> {
258    skel: BpfSkel<'a>,
259    struct_ops: Option<libbpf_rs::Link>,
260    opts: &'a Opts,
261    topo: Topology,
262    power_profile: PowerProfile,
263    stats_server: StatsServer<(), Metrics>,
264    user_restart: bool,
265}
266
267impl<'a> Scheduler<'a> {
268    fn init(opts: &'a Opts, open_object: &'a mut MaybeUninit<OpenObject>) -> Result<Self> {
269        set_rlimit_infinity();
270
271        // Validate command line arguments.
272        assert!(opts.slice_us >= opts.slice_us_min);
273
274        // Initialize CPU topology.
275        let topo = Topology::new().unwrap();
276
277        // Check host topology to determine if we need to enable SMT capabilities.
278        let smt_enabled = !opts.disable_smt && topo.smt_enabled;
279
280        info!(
281            "{} {} {}",
282            SCHEDULER_NAME,
283            build_id::full_version(env!("CARGO_PKG_VERSION")),
284            if smt_enabled { "SMT on" } else { "SMT off" }
285        );
286
287        if opts.idle_resume_us >= 0 {
288            if !cpu_idle_resume_latency_supported() {
289                warn!("idle resume latency not supported");
290            } else {
291                info!("Setting idle QoS to {} us", opts.idle_resume_us);
292                for cpu in topo.all_cpus.values() {
293                    update_cpu_idle_resume_latency(
294                        cpu.id,
295                        opts.idle_resume_us.try_into().unwrap(),
296                    )?;
297                }
298            }
299        }
300
301        // Initialize BPF connector.
302        let mut skel_builder = BpfSkelBuilder::default();
303        skel_builder.obj_builder.debug(opts.verbose);
304        let mut skel = scx_ops_open!(skel_builder, open_object, bpfland_ops)?;
305
306        skel.struct_ops.bpfland_ops_mut().exit_dump_len = opts.exit_dump_len;
307
308        // Override default BPF scheduling parameters.
309        skel.maps.rodata_data.debug = opts.debug;
310        skel.maps.rodata_data.smt_enabled = smt_enabled;
311        skel.maps.rodata_data.numa_disabled = opts.disable_numa;
312        skel.maps.rodata_data.local_pcpu = opts.local_pcpu;
313        skel.maps.rodata_data.no_preempt = opts.no_preempt;
314        skel.maps.rodata_data.no_wake_sync = opts.no_wake_sync;
315        skel.maps.rodata_data.slice_max = opts.slice_us * 1000;
316        skel.maps.rodata_data.slice_min = opts.slice_us_min * 1000;
317        skel.maps.rodata_data.slice_lag = opts.slice_us_lag * 1000;
318        skel.maps.rodata_data.throttle_ns = opts.throttle_us * 1000;
319
320        // Implicitly enable direct dispatch of per-CPU kthreads if CPU throttling is enabled
321        // (it's never a good idea to throttle per-CPU kthreads).
322        skel.maps.rodata_data.local_kthreads = opts.local_kthreads || opts.throttle_us > 0;
323
324        // Set scheduler compatibility flags.
325        skel.maps.rodata_data.__COMPAT_SCX_PICK_IDLE_IN_NODE = *compat::SCX_PICK_IDLE_IN_NODE;
326
327        // Set scheduler flags.
328        skel.struct_ops.bpfland_ops_mut().flags = *compat::SCX_OPS_ENQ_EXITING
329            | *compat::SCX_OPS_ENQ_LAST
330            | *compat::SCX_OPS_ENQ_MIGRATION_DISABLED
331            | *compat::SCX_OPS_BUILTIN_IDLE_PER_NODE
332            | *compat::SCX_OPS_ALLOW_QUEUED_WAKEUP;
333        info!(
334            "scheduler flags: {:#x}",
335            skel.struct_ops.bpfland_ops_mut().flags
336        );
337
338        // Load the BPF program for validation.
339        let mut skel = scx_ops_load!(skel, bpfland_ops, uei)?;
340
341        // Initialize the primary scheduling domain and the preferred domain.
342        let power_profile = Self::power_profile();
343        if let Err(err) = Self::init_energy_domain(&mut skel, &opts.primary_domain, power_profile) {
344            warn!("failed to initialize primary domain: error {}", err);
345        }
346        if let Err(err) = Self::init_cpufreq_perf(&mut skel, &opts.primary_domain, opts.cpufreq) {
347            warn!(
348                "failed to initialize cpufreq performance level: error {}",
349                err
350            );
351        }
352
353        // Initialize SMT domains.
354        if smt_enabled {
355            Self::init_smt_domains(&mut skel, &topo)?;
356        }
357
358        // Initialize L2 cache domains.
359        if !opts.disable_l2 {
360            Self::init_l2_cache_domains(&mut skel, &topo)?;
361        }
362        // Initialize L3 cache domains.
363        if !opts.disable_l3 {
364            Self::init_l3_cache_domains(&mut skel, &topo)?;
365        }
366
367        // Attach the scheduler.
368        let struct_ops = Some(scx_ops_attach!(skel, bpfland_ops)?);
369        let stats_server = StatsServer::new(stats::server_data()).launch()?;
370
371        Ok(Self {
372            skel,
373            struct_ops,
374            opts,
375            topo,
376            power_profile,
377            stats_server,
378            user_restart: false,
379        })
380    }
381
382    fn enable_primary_cpu(skel: &mut BpfSkel<'_>, cpu: i32) -> Result<(), u32> {
383        let prog = &mut skel.progs.enable_primary_cpu;
384        let mut args = cpu_arg {
385            cpu_id: cpu as c_int,
386        };
387        let input = ProgramInput {
388            context_in: Some(unsafe {
389                std::slice::from_raw_parts_mut(
390                    &mut args as *mut _ as *mut u8,
391                    std::mem::size_of_val(&args),
392                )
393            }),
394            ..Default::default()
395        };
396        let out = prog.test_run(input).unwrap();
397        if out.return_value != 0 {
398            return Err(out.return_value);
399        }
400
401        Ok(())
402    }
403
404    fn epp_to_cpumask(profile: Powermode) -> Result<Cpumask> {
405        let mut cpus = get_primary_cpus(profile).unwrap_or_default();
406        if cpus.is_empty() {
407            cpus = get_primary_cpus(Powermode::Any).unwrap_or_default();
408        }
409        Cpumask::from_str(&cpus_to_cpumask(&cpus))
410    }
411
412    fn init_energy_domain(
413        skel: &mut BpfSkel<'_>,
414        primary_domain: &str,
415        power_profile: PowerProfile,
416    ) -> Result<()> {
417        let domain = match primary_domain {
418            "powersave" => Self::epp_to_cpumask(Powermode::Powersave)?,
419            "performance" => Self::epp_to_cpumask(Powermode::Performance)?,
420            "auto" => match power_profile {
421                PowerProfile::Powersave => Self::epp_to_cpumask(Powermode::Powersave)?,
422                PowerProfile::Balanced { power: true } => {
423                    Self::epp_to_cpumask(Powermode::Powersave)?
424                }
425                PowerProfile::Balanced { power: false } => Self::epp_to_cpumask(Powermode::Any)?,
426                PowerProfile::Performance => Self::epp_to_cpumask(Powermode::Any)?,
427                PowerProfile::Unknown => Self::epp_to_cpumask(Powermode::Any)?,
428            },
429            "all" => Self::epp_to_cpumask(Powermode::Any)?,
430            &_ => Cpumask::from_str(primary_domain)?,
431        };
432
433        info!("primary CPU domain = 0x{:x}", domain);
434
435        // Clear the primary domain by passing a negative CPU id.
436        if let Err(err) = Self::enable_primary_cpu(skel, -1) {
437            warn!("failed to reset primary domain: error {}", err);
438        }
439        // Update primary scheduling domain.
440        for cpu in 0..*NR_CPU_IDS {
441            if domain.test_cpu(cpu) {
442                if let Err(err) = Self::enable_primary_cpu(skel, cpu as i32) {
443                    warn!("failed to add CPU {} to primary domain: error {}", cpu, err);
444                }
445            }
446        }
447
448        Ok(())
449    }
450
451    // Update hint for the cpufreq governor.
452    fn init_cpufreq_perf(
453        skel: &mut BpfSkel<'_>,
454        primary_domain: &String,
455        auto: bool,
456    ) -> Result<()> {
457        // If we are using the powersave profile always scale the CPU frequency to the minimum,
458        // otherwise use the maximum, unless automatic frequency scaling is enabled.
459        let perf_lvl: i64 = match primary_domain.as_str() {
460            "powersave" => 0,
461            _ if auto => -1,
462            _ => 1024,
463        };
464        info!(
465            "cpufreq performance level: {}",
466            match perf_lvl {
467                1024 => "max".into(),
468                0 => "min".into(),
469                n if n < 0 => "auto".into(),
470                _ => perf_lvl.to_string(),
471            }
472        );
473        skel.maps.bss_data.cpufreq_perf_lvl = perf_lvl;
474
475        Ok(())
476    }
477
478    fn power_profile() -> PowerProfile {
479        let profile = fetch_power_profile(true);
480        if profile == PowerProfile::Unknown {
481            fetch_power_profile(false)
482        } else {
483            profile
484        }
485    }
486
487    fn refresh_sched_domain(&mut self) -> bool {
488        if self.power_profile != PowerProfile::Unknown {
489            let power_profile = Self::power_profile();
490            if power_profile != self.power_profile {
491                self.power_profile = power_profile;
492
493                if self.opts.primary_domain == "auto" {
494                    return true;
495                }
496                if let Err(err) = Self::init_cpufreq_perf(
497                    &mut self.skel,
498                    &self.opts.primary_domain,
499                    self.opts.cpufreq,
500                ) {
501                    warn!("failed to refresh cpufreq performance level: error {}", err);
502                }
503            }
504        }
505
506        false
507    }
508
509    fn enable_sibling_cpu(
510        skel: &mut BpfSkel<'_>,
511        lvl: usize,
512        cpu: usize,
513        sibling_cpu: usize,
514    ) -> Result<(), u32> {
515        let prog = &mut skel.progs.enable_sibling_cpu;
516        let mut args = domain_arg {
517            lvl_id: lvl as c_int,
518            cpu_id: cpu as c_int,
519            sibling_cpu_id: sibling_cpu as c_int,
520        };
521        let input = ProgramInput {
522            context_in: Some(unsafe {
523                std::slice::from_raw_parts_mut(
524                    &mut args as *mut _ as *mut u8,
525                    std::mem::size_of_val(&args),
526                )
527            }),
528            ..Default::default()
529        };
530        let out = prog.test_run(input).unwrap();
531        if out.return_value != 0 {
532            return Err(out.return_value);
533        }
534
535        Ok(())
536    }
537
538    fn init_smt_domains(skel: &mut BpfSkel<'_>, topo: &Topology) -> Result<(), std::io::Error> {
539        let smt_siblings = topo.sibling_cpus();
540
541        info!("SMT sibling CPUs: {:?}", smt_siblings);
542        for (cpu, sibling_cpu) in smt_siblings.iter().enumerate() {
543            Self::enable_sibling_cpu(skel, 0, cpu, *sibling_cpu as usize).unwrap();
544        }
545
546        Ok(())
547    }
548
549    fn are_smt_siblings(topo: &Topology, cpus: &[usize]) -> bool {
550        // Single CPU or empty array are considered siblings.
551        if cpus.len() <= 1 {
552            return true;
553        }
554
555        // Check if each CPU is a sibling of the first CPU.
556        let first_cpu = cpus[0];
557        let smt_siblings = topo.sibling_cpus();
558        cpus.iter().all(|&cpu| {
559            cpu == first_cpu
560                || smt_siblings[cpu] == first_cpu as i32
561                || (smt_siblings[first_cpu] >= 0 && smt_siblings[first_cpu] == cpu as i32)
562        })
563    }
564
565    fn init_cache_domains(
566        skel: &mut BpfSkel<'_>,
567        topo: &Topology,
568        cache_lvl: usize,
569        enable_sibling_cpu_fn: &dyn Fn(&mut BpfSkel<'_>, usize, usize, usize) -> Result<(), u32>,
570    ) -> Result<(), std::io::Error> {
571        // Determine the list of CPU IDs associated to each cache node.
572        let mut cache_id_map: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
573        for core in topo.all_cores.values() {
574            for (cpu_id, cpu) in &core.cpus {
575                let cache_id = match cache_lvl {
576                    2 => cpu.l2_id,
577                    3 => cpu.llc_id,
578                    _ => panic!("invalid cache level {}", cache_lvl),
579                };
580                cache_id_map.entry(cache_id).or_default().push(*cpu_id);
581            }
582        }
583
584        // Update the BPF cpumasks for the cache domains.
585        for (cache_id, cpus) in cache_id_map {
586            // Ignore the cache domain if it includes a single CPU.
587            if cpus.len() <= 1 {
588                continue;
589            }
590
591            // Ignore the cache domain if all the CPUs are part of the same SMT core.
592            if Self::are_smt_siblings(topo, &cpus) {
593                continue;
594            }
595
596            info!(
597                "L{} cache ID {}: sibling CPUs: {:?}",
598                cache_lvl, cache_id, cpus
599            );
600            for cpu in &cpus {
601                for sibling_cpu in &cpus {
602                    if enable_sibling_cpu_fn(skel, cache_lvl, *cpu, *sibling_cpu).is_err() {
603                        warn!(
604                            "L{} cache ID {}: failed to set CPU {} sibling {}",
605                            cache_lvl, cache_id, *cpu, *sibling_cpu
606                        );
607                    }
608                }
609            }
610        }
611
612        Ok(())
613    }
614
615    fn init_l2_cache_domains(
616        skel: &mut BpfSkel<'_>,
617        topo: &Topology,
618    ) -> Result<(), std::io::Error> {
619        Self::init_cache_domains(skel, topo, 2, &|skel, lvl, cpu, sibling_cpu| {
620            Self::enable_sibling_cpu(skel, lvl, cpu, sibling_cpu)
621        })
622    }
623
624    fn init_l3_cache_domains(
625        skel: &mut BpfSkel<'_>,
626        topo: &Topology,
627    ) -> Result<(), std::io::Error> {
628        Self::init_cache_domains(skel, topo, 3, &|skel, lvl, cpu, sibling_cpu| {
629            Self::enable_sibling_cpu(skel, lvl, cpu, sibling_cpu)
630        })
631    }
632
633    fn get_metrics(&self) -> Metrics {
634        Metrics {
635            nr_running: self.skel.maps.bss_data.nr_running,
636            nr_cpus: self.skel.maps.bss_data.nr_online_cpus,
637            nr_kthread_dispatches: self.skel.maps.bss_data.nr_kthread_dispatches,
638            nr_direct_dispatches: self.skel.maps.bss_data.nr_direct_dispatches,
639            nr_shared_dispatches: self.skel.maps.bss_data.nr_shared_dispatches,
640        }
641    }
642
643    pub fn exited(&mut self) -> bool {
644        uei_exited!(&self.skel, uei)
645    }
646
647    fn run(&mut self, shutdown: Arc<AtomicBool>) -> Result<UserExitInfo> {
648        let (res_ch, req_ch) = self.stats_server.channels();
649        while !shutdown.load(Ordering::Relaxed) && !self.exited() {
650            if self.refresh_sched_domain() {
651                self.user_restart = true;
652                break;
653            }
654            match req_ch.recv_timeout(Duration::from_secs(1)) {
655                Ok(()) => res_ch.send(self.get_metrics())?,
656                Err(RecvTimeoutError::Timeout) => {}
657                Err(e) => Err(e)?,
658            }
659        }
660
661        let _ = self.struct_ops.take();
662        uei_report!(&self.skel, uei)
663    }
664}
665
666impl Drop for Scheduler<'_> {
667    fn drop(&mut self) {
668        info!("Unregister {} scheduler", SCHEDULER_NAME);
669
670        // Restore default CPU idle QoS resume latency.
671        if self.opts.idle_resume_us >= 0 {
672            if cpu_idle_resume_latency_supported() {
673                for cpu in self.topo.all_cpus.values() {
674                    update_cpu_idle_resume_latency(cpu.id, cpu.pm_qos_resume_latency_us as i32)
675                        .unwrap();
676                }
677            }
678        }
679    }
680}
681
682fn main() -> Result<()> {
683    let opts = Opts::parse();
684
685    if opts.version {
686        println!(
687            "{} {}",
688            SCHEDULER_NAME,
689            build_id::full_version(env!("CARGO_PKG_VERSION"))
690        );
691        return Ok(());
692    }
693
694    if opts.help_stats {
695        stats::server_data().describe_meta(&mut std::io::stdout(), None)?;
696        return Ok(());
697    }
698
699    let loglevel = simplelog::LevelFilter::Info;
700
701    let mut lcfg = simplelog::ConfigBuilder::new();
702    lcfg.set_time_offset_to_local()
703        .expect("Failed to set local time offset")
704        .set_time_level(simplelog::LevelFilter::Error)
705        .set_location_level(simplelog::LevelFilter::Off)
706        .set_target_level(simplelog::LevelFilter::Off)
707        .set_thread_level(simplelog::LevelFilter::Off);
708    simplelog::TermLogger::init(
709        loglevel,
710        lcfg.build(),
711        simplelog::TerminalMode::Stderr,
712        simplelog::ColorChoice::Auto,
713    )?;
714
715    let shutdown = Arc::new(AtomicBool::new(false));
716    let shutdown_clone = shutdown.clone();
717    ctrlc::set_handler(move || {
718        shutdown_clone.store(true, Ordering::Relaxed);
719    })
720    .context("Error setting Ctrl-C handler")?;
721
722    if let Some(intv) = opts.monitor.or(opts.stats) {
723        let shutdown_copy = shutdown.clone();
724        let jh = std::thread::spawn(move || {
725            match stats::monitor(Duration::from_secs_f64(intv), shutdown_copy) {
726                Ok(_) => {
727                    debug!("stats monitor thread finished successfully")
728                }
729                Err(error_object) => {
730                    warn!(
731                        "stats monitor thread finished because of an error {}",
732                        error_object
733                    )
734                }
735            }
736        });
737        if opts.monitor.is_some() {
738            let _ = jh.join();
739            return Ok(());
740        }
741    }
742
743    let mut open_object = MaybeUninit::uninit();
744    loop {
745        let mut sched = Scheduler::init(&opts, &mut open_object)?;
746        if !sched.run(shutdown.clone())?.should_restart() {
747            if sched.user_restart {
748                continue;
749            }
750            break;
751        }
752    }
753
754    Ok(())
755}