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