syd 3.52.0

rock-solid application kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
//
// Syd: rock-solid application kernel
// src/syslog.rs: syslog(2) interface
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

// syslog.rs
//
// A self-contained Rust module that implements a kernel-like syslog(2)
// interface on top of a ring buffer from `ringbuf`, with multi-producer
// and multi-consumer semantics, using exactly one `parking_lot::RwLock`
// to synchronize concurrent producers (writers) and consumers
// (readers).
//
// SECURITY & CONCURRENCY DISCLAIMER:
//   - The ring buffer is shared among multiple producer threads (which
//   take a write lock) and multiple consumer threads (which typically
//   take a read lock). Certain consumer operations that modify the ring
//   (like CLEAR, READ_CLEAR) require upgradable or exclusive write
//   locks. We minimize lock hold times.
//   - Once locked (via `lock()`), the ring buffer is freed and any
//   subsequent ring-based operations return EPERM. Writes to the main
//   fd continue. Writes to the console fd do NOT continue after locked.
//
// If the "log" feature is not enabled, we provide stubs that return ENOSYS.

use btoi::btoi;
use memchr::arch::all::is_equal;

/// Kernel log levels (KERN_*).
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum LogLevel {
    /// KERN_EMERG
    Emergent = 0,
    /// KERN_ALERT
    Alert = 1,
    /// KERN_CRIT
    Crit = 2,
    /// KERN_ERR
    Err = 3,
    /// KERN_WARNING
    Warn = 4,
    /// KERN_NOTICE
    Notice = 5,
    /// KERN_INFO
    Info = 6,
    /// KERN_DEBUG
    Debug = 7,
}

impl LogLevel {
    /// Converts `LogLevel` to a number.
    pub fn as_u8(self) -> u8 {
        self as u8
    }

    /// Converts `LogLevel` to a bytestring.
    pub fn as_bytes(self) -> &'static [u8] {
        match self {
            Self::Emergent => b"emerg",
            Self::Alert => b"alert",
            Self::Crit => b"crit",
            Self::Err => b"error",
            Self::Warn => b"warn",
            Self::Notice => b"notice",
            Self::Info => b"info",
            Self::Debug => b"debug",
        }
    }
}

impl From<u8> for LogLevel {
    fn from(level: u8) -> Self {
        let level = level.clamp(Self::Emergent.as_u8(), Self::Debug.as_u8());

        if level == Self::Emergent.as_u8() {
            Self::Emergent
        } else if level == Self::Alert.as_u8() {
            Self::Alert
        } else if level == Self::Crit.as_u8() {
            Self::Crit
        } else if level == Self::Err.as_u8() {
            Self::Err
        } else if level == Self::Warn.as_u8() {
            Self::Warn
        } else if level == Self::Notice.as_u8() {
            Self::Notice
        } else if level == Self::Info.as_u8() {
            Self::Info
        } else {
            Self::Debug
        }
    }
}

impl From<i64> for LogLevel {
    #[expect(clippy::cast_possible_truncation)]
    #[expect(clippy::cast_sign_loss)]
    fn from(level: i64) -> Self {
        (level.clamp(Self::Emergent.as_u8().into(), Self::Debug.as_u8().into()) as u8).into()
    }
}

/// Translate a string log level from environment to `LogLevel`
/// or fallback to the given default `LogLevel`.
pub fn parse_loglevel(level: &[u8], default: LogLevel) -> LogLevel {
    let level = level.trim_ascii();
    if level.is_empty() {
        default
    } else if let Ok(level) = btoi::<i64>(level) {
        level.into()
    } else if is_equal(level, b"emerg") {
        LogLevel::Emergent
    } else if is_equal(level, b"alert") {
        LogLevel::Alert
    } else if is_equal(level, b"crit") {
        LogLevel::Crit
    } else if is_equal(level, b"error") {
        LogLevel::Err
    } else if is_equal(level, b"warn") {
        LogLevel::Warn
    } else if is_equal(level, b"notice") {
        LogLevel::Notice
    } else if is_equal(level, b"info") {
        LogLevel::Info
    } else if is_equal(level, b"debug") {
        LogLevel::Debug
    } else {
        default
    }
}

//
// Syslog action constants
//

/// Close the log.  Currently a NOP.
pub const SYSLOG_ACTION_CLOSE: libc::c_int = 0;

/// Open the log.  Currently a NOP.
pub const SYSLOG_ACTION_OPEN: libc::c_int = 1;

/// Read from the log. The call waits until the kernel log buffer
/// is nonempty, and then reads at most len bytes into the buffer
/// pointed to by bufp. The call returns the number of bytes read.
/// Bytes read from the log disappear from the log buffer: the
/// information can be read only once. This is the function
/// executed by the kernel when a user program reads /proc/kmsg.
pub const SYSLOG_ACTION_READ: libc::c_int = 2;

/// Read all messages remaining in the ring buffer, placing them in
/// the buffer pointed to by bufp.  The call reads the last len
/// bytes from the log buffer (nondestructively), but will not read
/// more than was written into the buffer since the last "clear ring
/// buffer" command (see command 5 below)).  The call returns the
/// number of bytes read.
pub const SYSLOG_ACTION_READ_ALL: libc::c_int = 3;

/// Read and clear all messages remaining in the ring buffer.
/// The call does precisely the same as for a type of 3, but
/// also executes the "clear ring buffer" command.
pub const SYSLOG_ACTION_READ_CLEAR: libc::c_int = 4;

/// The call executes just the "clear ring buffer" command.
/// The bufp and len arguments are ignored.
///
/// This command does not really clear the ring buffer.
/// Rather, it sets a kernel bookkeeping variable that
/// determines the results returned by commands 3
/// (SYSLOG_ACTION_READ_ALL) and 4 (SYSLOG_ACTION_READ_CLEAR).
/// This command has no effect on commands 2
/// (SYSLOG_ACTION_READ) and 9 (SYSLOG_ACTION_SIZE_UNREAD).
pub const SYSLOG_ACTION_CLEAR: libc::c_int = 5;

/// The command saves the current value of console_loglevel
/// and then sets console_loglevel to
/// minimum_console_loglevel, so that no messages are printed
/// to the console.  Before Linux 2.6.32, the command simply
/// sets console_loglevel to minimum_console_loglevel.  See
/// the discussion of /proc/sys/kernel/printk, below.
///
/// The bufp and len arguments are ignored.
pub const SYSLOG_ACTION_CONSOLE_OFF: libc::c_int = 6;

/// If a previous SYSLOG_ACTION_CONSOLE_OFF command has been
/// performed, this command restores console_loglevel to the
/// value that was saved by that command.  Before Linux
/// 2.6.32, this command simply sets console_loglevel to
/// default_console_loglevel.  See the discussion of
/// /proc/sys/kernel/printk, below.
///
/// The bufp and len arguments are ignored.
pub const SYSLOG_ACTION_CONSOLE_ON: libc::c_int = 7;

/// The call sets console_loglevel to the value given in len,
/// which must be an integer between 1 and 8 (inclusive).  The
/// kernel silently enforces a minimum value of
/// minimum_console_loglevel for len.  See the log level
/// section for details.  The bufp argument is ignored.
pub const SYSLOG_ACTION_CONSOLE_LEVEL: libc::c_int = 8;

/// The call returns the number of bytes currently available
/// to be read from the kernel log buffer via command 2
/// (SYSLOG_ACTION_READ).  The bufp and len arguments are
/// ignored.
pub const SYSLOG_ACTION_SIZE_UNREAD: libc::c_int = 9;

/// This command returns the total size of the kernel log
/// buffer.  The bufp and len arguments are ignored.
pub const SYSLOG_ACTION_SIZE_BUFFER: libc::c_int = 10;

// LOG-ENABLED IMPLEMENTATION
#[cfg(feature = "log")]
mod syslog_enabled {
    use std::{
        io::{BufWriter, Write},
        mem::MaybeUninit,
        os::fd::BorrowedFd,
        sync::{
            atomic::{AtomicBool, AtomicU8, Ordering},
            OnceLock, RwLock,
        },
    };

    use nix::{
        errno::Errno,
        time::{clock_gettime, ClockId},
    };
    use ringbuf::{
        storage::{Array, Heap},
        traits::*,
        wrap::caching::Caching,
        Arc, SharedRb,
    };

    use crate::{config::SYSLOG_STACK_SIZE, log::LockedWriter, syslog::*};

    // Store ring data in an enum to handle "heap" vs "static" capacity.
    // Store Arc<SharedRb<...>> plus Caching wrappers to fix all trait bounds.
    enum RbMode {
        Heap {
            shared: Arc<SharedRb<Heap<u8>>>,
            prod: Caching<Arc<SharedRb<Heap<u8>>>, true, false>,
            cons: Caching<Arc<SharedRb<Heap<u8>>>, false, true>,
        },
        Static {
            shared: Arc<SharedRb<Array<u8, SYSLOG_STACK_SIZE>>>,
            prod: Caching<Arc<SharedRb<Array<u8, SYSLOG_STACK_SIZE>>>, true, false>,
            cons: Caching<Arc<SharedRb<Array<u8, SYSLOG_STACK_SIZE>>>, false, true>,
        },
    }

    // The main ring data behind the RwLock. Freed after locked==true.
    struct RingData {
        mode: RbMode,
    }

    /// Syslog: multi-producer, multi-consumer ring protected by RwLock.
    ///
    ///  - Many producers each do ring_lock.write() to push logs.
    ///  - Many consumers do ring_lock.read() to read logs.
    ///  - read_clear or clear requires write lock.
    ///  - If locked => ring is freed => ring ops => EPERM.
    ///    We still write to fd + host syslog after locking.
    pub struct Syslog {
        ring_lock: RwLock<Option<RingData>>,

        // Ring is freed when it's locked.
        locked: AtomicBool,

        // Log level.
        level: AtomicU8,
    }

    // SAFETY: The ringbuf uses interior mutability, but SharedRb + Arc
    // is thread-safe. So we can allow Syslog to be Sync:
    unsafe impl Sync for Syslog {}

    impl Syslog {
        /// Creates a multi-producer, multi-consumer Syslog.
        /// - If `use_stack == true`, uses a SharedRb<Array<u8, SYSLOG_STACK_SIZE>>.
        /// - Otherwise, uses a SharedRb<Heap<u8>> of capacity `capacity`.
        pub fn new(capacity: usize, level: LogLevel, use_stack: bool) -> Self {
            let ring_data = if use_stack {
                // Static array-based ring
                let shared = Arc::new(SharedRb::<Array<u8, SYSLOG_STACK_SIZE>>::default());
                let prod = Caching::new(Arc::clone(&shared));
                let cons = Caching::new(Arc::clone(&shared));
                Some(RingData {
                    mode: RbMode::Static { shared, prod, cons },
                })
            } else {
                // Heap-based ring
                // ringbuf expects capacity > 0
                // (the caller is presumably ensuring capacity > 0 if not stack).
                let shared = Arc::new(SharedRb::<Heap<u8>>::new(capacity));
                let prod = Caching::new(Arc::clone(&shared));
                let cons = Caching::new(Arc::clone(&shared));
                Some(RingData {
                    mode: RbMode::Heap { shared, prod, cons },
                })
            };

            Syslog {
                ring_lock: RwLock::new(ring_data),
                locked: AtomicBool::new(false),
                level: AtomicU8::new(level as u8),
            }
        }

        /// Write a log message at `level`.
        /// - Always writes the raw message to the `fd` (if present).
        /// - If not locked, also writes the formatted ring message to the ring,
        ///   under a short write lock.
        ///
        /// If locked => no ring operations, but still writes to fd + host syslog.
        pub fn write_log(&self, level: LogLevel, msg: &str, msg_pretty: Option<&str>) {
            if level.as_u8() > self.loglevel() {
                // Return immediately if the level is not enabled.
                return;
            }

            // Always attempt to write message to log fd, append a new line to the message.
            // Use formatting as necessary. We take a OFD write lock here.
            let msg = msg_pretty.unwrap_or(msg);
            if let Some(fd) = Self::logfd() {
                if let Ok(mut writer) = LockedWriter::new(fd).map(BufWriter::new) {
                    let _ = writer.write_all(msg.as_bytes());
                    let _ = writer.write_all(b"\n");
                }
            }

            // If locked => skip ring.
            if self.is_locked() {
                return;
            }

            // Build ring message, use formatting as necessary.
            let ring_str = self.format_ring_message(level, msg);

            // Acquire write lock for ring push.
            {
                let mut guard = self
                    .ring_lock
                    .write()
                    .unwrap_or_else(|err| err.into_inner());
                if self.locked.load(Ordering::SeqCst) {
                    // ring locked in meantime => skip
                } else if let Some(ring_data) = guard.as_mut() {
                    match &mut ring_data.mode {
                        RbMode::Heap { prod, .. } => {
                            let _ = prod.push_slice(ring_str.as_bytes());
                        }
                        RbMode::Static { prod, .. } => {
                            let _ = prod.push_slice(ring_str.as_bytes());
                        }
                    }
                }
            }
        }

        /// syslog(2)-like interface. Returns Ok((count, data)) on success,
        /// or Err(errno) on error.
        ///
        /// # Errors:
        /// - EPERM if locked (// ring is freed, cannot proceed).
        ///
        /// Multiple consumers can do read locks, but if they need to mutate
        /// ring (like CLEAR), they do an exclusive lock.
        #[expect(clippy::type_complexity)]
        pub fn syslog(
            &self,
            action: libc::c_int,
            len: usize,
        ) -> Result<(usize, Option<Vec<u8>>), Errno> {
            if self.is_locked() {
                // ring is locked => EPERM
                // ring is freed, no ring ops allowed.
                return Err(Errno::EPERM);
            }

            match action {
                SYSLOG_ACTION_CLOSE | SYSLOG_ACTION_OPEN => Ok((0, None)),

                SYSLOG_ACTION_READ => {
                    if len == 0 {
                        return Ok((0, None));
                    }
                    // We'll do a write lock to gather data and then to pop.
                    let mut write_guard = self.ring_lock.try_write().or(Err(Errno::EINTR))?;
                    let ring_data = match write_guard.as_mut() {
                        None => {
                            // ring is None => locked/freed in between.
                            return Ok((0, None));
                        }
                        Some(ring_data) => ring_data,
                    };
                    Ok(self.read_and_consume(ring_data, len))
                }

                SYSLOG_ACTION_READ_ALL => {
                    if len == 0 {
                        return Ok((0, None));
                    }
                    // read lock, gather data, do not consume.
                    let read_guard = self.ring_lock.try_read().or(Err(Errno::EINTR))?;
                    let ring_data = match read_guard.as_ref() {
                        None => {
                            // ring freed.
                            return Ok((0, None));
                        }
                        Some(ring_data) => ring_data,
                    };
                    Ok(self.read_all_no_consume(ring_data, len))
                }

                SYSLOG_ACTION_READ_CLEAR => {
                    if len == 0 {
                        return Ok((0, None));
                    }
                    // exclusive lock, read data & pop.
                    let mut write_guard = self.ring_lock.try_write().or(Err(Errno::EINTR))?;
                    let ring_data = match write_guard.as_mut() {
                        None => {
                            // ring is None => locked/freed in between.
                            return Ok((0, None));
                        }
                        Some(ring_data) => ring_data,
                    };
                    let (count, data_vec) = self.read_all_no_consume_mut(ring_data, len);
                    if count > 0 {
                        self.pop_count(ring_data, count);
                    }
                    Ok((count, data_vec))
                }

                SYSLOG_ACTION_CLEAR => {
                    // exclusive lock, skip entire ring.
                    let mut write_guard = self.ring_lock.try_write().or(Err(Errno::EINTR))?;
                    let ring_data = match write_guard.as_mut() {
                        None => {
                            // ring is None => locked/freed in between.
                            return Ok((0, None));
                        }
                        Some(ring_data) => ring_data,
                    };
                    self.skip_all(ring_data);
                    Ok((0, None))
                }

                SYSLOG_ACTION_CONSOLE_OFF => {
                    self.set_loglevel(LogLevel::Emergent.as_u8());
                    Ok((0, None))
                }

                SYSLOG_ACTION_CONSOLE_ON => {
                    self.set_loglevel(LogLevel::Warn.as_u8());
                    Ok((0, None))
                }

                SYSLOG_ACTION_CONSOLE_LEVEL => {
                    // Linux rejects if level isn't in range 1..=8.
                    let level: u8 = len.try_into().or(Err(Errno::EINVAL))?;
                    if !(1..=8).contains(&level) {
                        return Err(Errno::EINVAL);
                    }
                    self.set_loglevel(level);
                    Ok((0, None))
                }

                SYSLOG_ACTION_SIZE_UNREAD => {
                    let read_guard = self.ring_lock.try_read().or(Err(Errno::EINTR))?;
                    let ring_data = match read_guard.as_ref() {
                        None => {
                            // ring freed.
                            return Ok((0, None));
                        }
                        Some(ring_data) => ring_data,
                    };
                    let unread = self.ring_unread(ring_data);
                    Ok((unread, None))
                }

                SYSLOG_ACTION_SIZE_BUFFER => {
                    let read_guard = self.ring_lock.try_read().or(Err(Errno::EINTR))?;
                    let ring_data = match read_guard.as_ref() {
                        None => {
                            // ring freed.
                            return Ok((0, None));
                        }
                        Some(ring_data) => ring_data,
                    };
                    let cap = self.ring_capacity(ring_data);
                    Ok((cap, None))
                }

                _ => {
                    // invalid action
                    Err(Errno::EINVAL)
                }
            }
        }

        /// Return `Some(BorrowedFd)` if logging is enabled, `None` otherwise.
        pub fn logfd() -> Option<BorrowedFd<'static>> {
            let fd = crate::log::LOG_FD.load(Ordering::Relaxed);
            if fd >= 0 {
                // SAFETY: `LOG_FD` is valid for process lifetime.
                Some(unsafe { BorrowedFd::borrow_raw(fd) })
            } else {
                None
            }
        }

        /// Returns the current console log level (0..7).
        pub fn loglevel(&self) -> u8 {
            self.level.load(Ordering::SeqCst)
        }

        /// Sets console log level, clamped to [0..7].
        pub fn set_loglevel(&self, level: u8) {
            let lv = level.clamp(LogLevel::Emergent.as_u8(), LogLevel::Debug.as_u8());
            self.level.store(lv, Ordering::SeqCst);
        }

        /// Returns true if syslog is locked.
        pub fn is_locked(&self) -> bool {
            self.locked.load(Ordering::SeqCst)
        }

        /// Lock the syslog, freeing ring data. Return true if we locked now,
        /// false if already locked previously.
        pub fn lock(&self) -> bool {
            // Attempt to set locked from false->true
            if self
                .locked
                .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
                .is_ok()
            {
                // Freed ring
                let mut guard = self
                    .ring_lock
                    .write()
                    .unwrap_or_else(|err| err.into_inner());
                *guard = None; // ring data freed.
                true
            } else {
                false
            }
        }

        // HELPER: Format "<LEVEL>[   12.345678] msg\n"
        fn format_ring_message(&self, level: LogLevel, msg: &str) -> String {
            #[expect(clippy::cast_precision_loss)]
            let now = match clock_gettime(ClockId::CLOCK_BOOTTIME) {
                Ok(ts) => ts.tv_sec() as f64 + (ts.tv_nsec() as f64 / 1_000_000_000.0),
                Err(_) => 0.0,
            };
            format!("<{}>[{:12.6}] {}\n", level.as_u8(), now, msg)
        }

        // HELPER: read and consume ring data.
        fn read_and_consume(
            &self,
            ring_data: &mut RingData,
            len: usize,
        ) -> (usize, Option<Vec<u8>>) {
            // Read data.
            let (count, out) = self.peek_and_copy(ring_data, len);
            if count == 0 {
                return (0, None);
            }

            // Now pop them.
            self.pop_count(ring_data, count);

            (count, Some(out))
        }

        // HELPER: read-all without consumption
        fn read_all_no_consume(
            &self,
            ring_data: &RingData,
            len: usize,
        ) -> (usize, Option<Vec<u8>>) {
            let (count, out) = self.peek_and_copy(ring_data, len);
            if count == 0 {
                (0, None)
            } else {
                (count, Some(out))
            }
        }

        // For read_clear, same approach but do it under same exclusive lock:
        fn read_all_no_consume_mut(
            &self,
            ring_data: &mut RingData,
            len: usize,
        ) -> (usize, Option<Vec<u8>>) {
            let (count, out) = self.peek_and_copy_mut(ring_data, len);
            if count == 0 {
                (0, None)
            } else {
                (count, Some(out))
            }
        }

        // HELPER: skip all ring content.
        fn skip_all(&self, ring_data: &mut RingData) {
            match &mut ring_data.mode {
                RbMode::Heap { cons, .. } => {
                    let to_skip = cons.occupied_len();
                    if to_skip > 0 {
                        let mut scratch = vec![MaybeUninit::<u8>::uninit(); to_skip];
                        let _ = cons.pop_slice_uninit(&mut scratch);
                    }
                }
                RbMode::Static { cons, .. } => {
                    let to_skip = cons.occupied_len();
                    if to_skip > 0 {
                        let mut scratch = vec![MaybeUninit::<u8>::uninit(); to_skip];
                        let _ = cons.pop_slice_uninit(&mut scratch);
                    }
                }
            }
        }

        // HELPER: pop 'count' items from ring.
        fn pop_count(&self, ring_data: &mut RingData, count: usize) {
            if count == 0 {
                return;
            }
            match &mut ring_data.mode {
                RbMode::Heap { cons, .. } => {
                    let mut scratch = vec![MaybeUninit::<u8>::uninit(); count];
                    let _ = cons.pop_slice_uninit(&mut scratch);
                }
                RbMode::Static { cons, .. } => {
                    let mut scratch = vec![MaybeUninit::<u8>::uninit(); count];
                    let _ = cons.pop_slice_uninit(&mut scratch);
                }
            }
        }

        // HELPER: read (peek) up to `len` items from ring into a Vec<u8>.
        // Does not consume them from the ring.
        fn peek_and_copy(&self, ring_data: &RingData, len: usize) -> (usize, Vec<u8>) {
            match &ring_data.mode {
                RbMode::Heap { cons, .. } => {
                    let rlen = cons.occupied_len().min(len);
                    if rlen == 0 {
                        return (0, Vec::new());
                    }
                    let mut tmp = vec![MaybeUninit::<u8>::uninit(); rlen];
                    let actual = cons.peek_slice_uninit(&mut tmp);
                    let mut out = Vec::with_capacity(actual);
                    for item in tmp.iter().take(actual) {
                        // SAFETY: ring data wrote these items.
                        out.push(unsafe { item.assume_init() });
                    }
                    (actual, out)
                }
                RbMode::Static { cons, .. } => {
                    let rlen = cons.occupied_len().min(len);
                    if rlen == 0 {
                        return (0, Vec::new());
                    }
                    let mut tmp = vec![MaybeUninit::<u8>::uninit(); rlen];
                    let actual = cons.peek_slice_uninit(&mut tmp);
                    let mut out = Vec::with_capacity(actual);
                    for item in tmp.iter().take(actual) {
                        // SAFETY: ring data wrote these items.
                        out.push(unsafe { item.assume_init() });
                    }
                    (actual, out)
                }
            }
        }

        // same but ring_data is mutable reference.
        fn peek_and_copy_mut(&self, ring_data: &mut RingData, len: usize) -> (usize, Vec<u8>) {
            match &mut ring_data.mode {
                RbMode::Heap { cons, .. } => {
                    let rlen = cons.occupied_len().min(len);
                    if rlen == 0 {
                        return (0, Vec::new());
                    }
                    let mut tmp = vec![MaybeUninit::<u8>::uninit(); rlen];
                    let actual = cons.peek_slice_uninit(&mut tmp);
                    let mut out = Vec::with_capacity(actual);
                    for item in tmp.iter().take(actual) {
                        // SAFETY: ring data wrote these items.
                        out.push(unsafe { item.assume_init() });
                    }
                    (actual, out)
                }
                RbMode::Static { cons, .. } => {
                    let rlen = cons.occupied_len().min(len);
                    if rlen == 0 {
                        return (0, Vec::new());
                    }
                    let mut tmp = vec![MaybeUninit::<u8>::uninit(); rlen];
                    let actual = cons.peek_slice_uninit(&mut tmp);
                    let mut out = Vec::with_capacity(actual);
                    for item in tmp.iter().take(actual) {
                        // SAFETY: ring data wrote these items.
                        out.push(unsafe { item.assume_init() });
                    }
                    (actual, out)
                }
            }
        }

        // HELPER: read the current unread length (no pop).
        fn ring_unread(&self, ring_data: &RingData) -> usize {
            match &ring_data.mode {
                RbMode::Heap { cons, .. } => cons.occupied_len(),
                RbMode::Static { cons, .. } => cons.occupied_len(),
            }
        }

        // HELPER: get ring capacity.
        fn ring_capacity(&self, ring_data: &RingData) -> usize {
            match &ring_data.mode {
                RbMode::Heap { shared, .. } => shared.capacity().get(),
                RbMode::Static { shared, .. } => shared.capacity().get(),
            }
        }
    }

    /// Global syslog instance.
    pub static SYSLOG_INSTANCE: OnceLock<Syslog> = OnceLock::new();

    /// Initialize the global `Syslog` instance.
    pub fn init_global_syslog(
        capacity: usize,
        level: LogLevel,
        use_stack: bool,
    ) -> Result<(), Errno> {
        if !use_stack && capacity == 0 {
            // Cannot create a heap-based syslog with zero capacity!
            return Err(Errno::EINVAL);
        }

        SYSLOG_INSTANCE
            .set(Syslog::new(capacity, level, use_stack))
            .or(Err(Errno::EAGAIN))
    }

    /// Returns the global `Syslog` instance.
    pub fn global_syslog() -> Option<&'static Syslog> {
        SYSLOG_INSTANCE.get()
    }
} // end of syslog_enabled

// PUBLIC RE-EXPORTS
#[cfg(feature = "log")]
pub use syslog_enabled::*;

/// Returns current log level of the global `Syslog`.
#[cfg(feature = "log")]
#[inline(always)]
pub fn current_loglevel() -> u8 {
    global_syslog().map(|sys| sys.loglevel()).unwrap_or(4)
}

/// This still parses log level from SYD_LOG,
/// so dry run with SYD_LOG=debug works,
/// even if the log feature is disabled.
#[cfg(not(feature = "log"))]
#[inline(always)]
pub fn current_loglevel() -> u8 {
    use std::{os::unix::ffi::OsStrExt, sync::LazyLock};

    static LOGLEVEL: LazyLock<u8> = LazyLock::new(|| {
        std::env::var_os(crate::config::ENV_LOG)
            .map(|val| parse_loglevel(val.as_os_str().as_bytes(), LogLevel::Warn))
            .unwrap_or(LogLevel::Warn)
            .as_u8()
    });

    *LOGLEVEL
}

/// Returns whether given log level is enabled.
#[macro_export]
macro_rules! log_enabled {
    ($level:expr) => {
        $crate::syslog::current_loglevel() >= $level.as_u8()
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_log_level_1() {
        assert_eq!(LogLevel::Emergent.as_u8(), 0);
        assert_eq!(LogLevel::Alert.as_u8(), 1);
        assert_eq!(LogLevel::Crit.as_u8(), 2);
        assert_eq!(LogLevel::Err.as_u8(), 3);
        assert_eq!(LogLevel::Warn.as_u8(), 4);
        assert_eq!(LogLevel::Notice.as_u8(), 5);
        assert_eq!(LogLevel::Info.as_u8(), 6);
        assert_eq!(LogLevel::Debug.as_u8(), 7);
    }

    #[test]
    fn test_log_level_2() {
        assert_eq!(LogLevel::Emergent.as_bytes(), b"emerg");
        assert_eq!(LogLevel::Alert.as_bytes(), b"alert");
        assert_eq!(LogLevel::Crit.as_bytes(), b"crit");
        assert_eq!(LogLevel::Err.as_bytes(), b"error");
        assert_eq!(LogLevel::Warn.as_bytes(), b"warn");
        assert_eq!(LogLevel::Notice.as_bytes(), b"notice");
        assert_eq!(LogLevel::Info.as_bytes(), b"info");
        assert_eq!(LogLevel::Debug.as_bytes(), b"debug");
    }

    #[test]
    fn test_log_level_3() {
        assert_eq!(LogLevel::from(0u8), LogLevel::Emergent);
        assert_eq!(LogLevel::from(1u8), LogLevel::Alert);
        assert_eq!(LogLevel::from(2u8), LogLevel::Crit);
        assert_eq!(LogLevel::from(3u8), LogLevel::Err);
        assert_eq!(LogLevel::from(4u8), LogLevel::Warn);
        assert_eq!(LogLevel::from(5u8), LogLevel::Notice);
        assert_eq!(LogLevel::from(6u8), LogLevel::Info);
        assert_eq!(LogLevel::from(7u8), LogLevel::Debug);
    }

    #[test]
    fn test_log_level_4() {
        assert_eq!(LogLevel::from(8u8), LogLevel::Debug);
        assert_eq!(LogLevel::from(255u8), LogLevel::Debug);
    }

    #[test]
    fn test_log_level_5() {
        assert_eq!(LogLevel::from(0i64), LogLevel::Emergent);
        assert_eq!(LogLevel::from(3i64), LogLevel::Err);
        assert_eq!(LogLevel::from(7i64), LogLevel::Debug);
    }

    #[test]
    fn test_log_level_6() {
        assert_eq!(LogLevel::from(-1i64), LogLevel::Emergent);
        assert_eq!(LogLevel::from(-100i64), LogLevel::Emergent);
    }

    #[test]
    fn test_log_level_7() {
        assert_eq!(LogLevel::from(100i64), LogLevel::Debug);
    }

    #[test]
    fn test_log_level_8() {
        assert!(LogLevel::Emergent < LogLevel::Alert);
        assert!(LogLevel::Alert < LogLevel::Crit);
        assert!(LogLevel::Crit < LogLevel::Err);
        assert!(LogLevel::Err < LogLevel::Warn);
        assert!(LogLevel::Warn < LogLevel::Notice);
        assert!(LogLevel::Notice < LogLevel::Info);
        assert!(LogLevel::Info < LogLevel::Debug);
    }

    #[test]
    fn test_log_level_9() {
        let level = LogLevel::Info;
        let cloned = level;
        assert_eq!(level, cloned);
    }

    #[test]
    fn test_parse_loglevel_1() {
        assert_eq!(parse_loglevel(b"0", LogLevel::Warn), LogLevel::Emergent);
        assert_eq!(parse_loglevel(b"3", LogLevel::Warn), LogLevel::Err);
        assert_eq!(parse_loglevel(b"7", LogLevel::Warn), LogLevel::Debug);
    }

    #[test]
    fn test_parse_loglevel_2() {
        assert_eq!(parse_loglevel(b"emerg", LogLevel::Warn), LogLevel::Emergent);
        assert_eq!(parse_loglevel(b"alert", LogLevel::Warn), LogLevel::Alert);
        assert_eq!(parse_loglevel(b"crit", LogLevel::Warn), LogLevel::Crit);
        assert_eq!(parse_loglevel(b"error", LogLevel::Warn), LogLevel::Err);
        assert_eq!(parse_loglevel(b"warn", LogLevel::Warn), LogLevel::Warn);
        assert_eq!(parse_loglevel(b"notice", LogLevel::Warn), LogLevel::Notice);
        assert_eq!(parse_loglevel(b"info", LogLevel::Warn), LogLevel::Info);
        assert_eq!(parse_loglevel(b"debug", LogLevel::Warn), LogLevel::Debug);
    }

    #[test]
    fn test_parse_loglevel_3() {
        assert_eq!(parse_loglevel(b"", LogLevel::Info), LogLevel::Info);
    }

    #[test]
    fn test_parse_loglevel_4() {
        assert_eq!(parse_loglevel(b"  ", LogLevel::Info), LogLevel::Info);
    }

    #[test]
    fn test_parse_loglevel_5() {
        assert_eq!(parse_loglevel(b" debug ", LogLevel::Warn), LogLevel::Debug);
    }

    #[test]
    fn test_parse_loglevel_6() {
        assert_eq!(parse_loglevel(b"unknown", LogLevel::Info), LogLevel::Info);
    }

    #[test]
    fn test_parse_loglevel_7() {
        assert_eq!(parse_loglevel(b"-1", LogLevel::Warn), LogLevel::Emergent);
    }

    #[test]
    fn test_parse_loglevel_8() {
        assert_eq!(parse_loglevel(b"100", LogLevel::Warn), LogLevel::Debug);
    }

    #[test]
    fn test_syslog_1() {
        assert_eq!(SYSLOG_ACTION_CLOSE, 0);
        assert_eq!(SYSLOG_ACTION_OPEN, 1);
        assert_eq!(SYSLOG_ACTION_READ, 2);
        assert_eq!(SYSLOG_ACTION_READ_ALL, 3);
        assert_eq!(SYSLOG_ACTION_READ_CLEAR, 4);
        assert_eq!(SYSLOG_ACTION_CLEAR, 5);
        assert_eq!(SYSLOG_ACTION_CONSOLE_OFF, 6);
        assert_eq!(SYSLOG_ACTION_CONSOLE_ON, 7);
        assert_eq!(SYSLOG_ACTION_CONSOLE_LEVEL, 8);
        assert_eq!(SYSLOG_ACTION_SIZE_UNREAD, 9);
        assert_eq!(SYSLOG_ACTION_SIZE_BUFFER, 10);
    }

    #[cfg(feature = "log")]
    mod syslog_tests {
        use super::*;

        #[test]
        fn test_syslog_1() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            assert!(!syslog.is_locked());
            assert_eq!(syslog.loglevel(), LogLevel::Info.as_u8());
        }

        #[test]
        fn test_syslog_2() {
            let syslog = Syslog::new(0, LogLevel::Warn, true);
            assert!(!syslog.is_locked());
            assert_eq!(syslog.loglevel(), LogLevel::Warn.as_u8());
        }

        #[test]
        fn test_syslog_3() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            syslog.set_loglevel(0);
            assert_eq!(syslog.loglevel(), 0);
            syslog.set_loglevel(7);
            assert_eq!(syslog.loglevel(), 7);
            syslog.set_loglevel(255);
            assert_eq!(syslog.loglevel(), 7);
        }

        #[test]
        fn test_syslog_4() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            assert!(!syslog.is_locked());
            assert!(syslog.lock());
            assert!(syslog.is_locked());
            assert!(!syslog.lock());
        }

        #[test]
        fn test_syslog_5() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            syslog.lock();
            let result = syslog.syslog(SYSLOG_ACTION_READ_ALL, 100);
            assert_eq!(result, Err(nix::errno::Errno::EPERM));
        }

        #[test]
        fn test_syslog_6() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            assert_eq!(syslog.syslog(SYSLOG_ACTION_CLOSE, 0), Ok((0, None)));
            assert_eq!(syslog.syslog(SYSLOG_ACTION_OPEN, 0), Ok((0, None)));
        }

        #[test]
        fn test_syslog_7() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            assert_eq!(syslog.syslog(99, 100), Err(nix::errno::Errno::EINVAL));
        }

        #[test]
        fn test_syslog_8() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            assert_eq!(syslog.syslog(SYSLOG_ACTION_READ, 0), Ok((0, None)));
            assert_eq!(syslog.syslog(SYSLOG_ACTION_READ_ALL, 0), Ok((0, None)));
            assert_eq!(syslog.syslog(SYSLOG_ACTION_READ_CLEAR, 0), Ok((0, None)));
        }

        #[test]
        fn test_syslog_9() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            syslog.syslog(SYSLOG_ACTION_CONSOLE_OFF, 0).unwrap();
            assert_eq!(syslog.loglevel(), LogLevel::Emergent.as_u8());

            syslog.syslog(SYSLOG_ACTION_CONSOLE_ON, 0).unwrap();
            assert_eq!(syslog.loglevel(), LogLevel::Warn.as_u8());
        }

        #[test]
        fn test_syslog_10() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            syslog.syslog(SYSLOG_ACTION_CONSOLE_LEVEL, 5).unwrap();
            assert_eq!(syslog.loglevel(), 5);
        }

        #[test]
        fn test_syslog_11() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            let (cap, _) = syslog.syslog(SYSLOG_ACTION_SIZE_BUFFER, 0).unwrap();
            assert!(cap > 0);
        }

        #[test]
        fn test_syslog_12() {
            let syslog = Syslog::new(1024, LogLevel::Info, false);
            let (unread, _) = syslog.syslog(SYSLOG_ACTION_SIZE_UNREAD, 0).unwrap();
            assert_eq!(unread, 0);
        }

        #[test]
        fn test_syslog_13() {
            let syslog = Syslog::new(4096, LogLevel::Debug, false);
            syslog.write_log(LogLevel::Info, "test message", None);

            let (unread, _) = syslog.syslog(SYSLOG_ACTION_SIZE_UNREAD, 0).unwrap();
            assert!(unread > 0);

            let (count, data) = syslog.syslog(SYSLOG_ACTION_READ_ALL, 4096).unwrap();
            assert!(count > 0);
            let data = data.unwrap();
            let text = String::from_utf8_lossy(&data);
            assert!(text.contains("test message"));
        }

        #[test]
        fn test_syslog_14() {
            let syslog = Syslog::new(4096, LogLevel::Err, false);
            syslog.write_log(LogLevel::Info, "filtered message", None);

            let (unread, _) = syslog.syslog(SYSLOG_ACTION_SIZE_UNREAD, 0).unwrap();
            assert_eq!(unread, 0);
        }

        #[test]
        fn test_syslog_15() {
            let syslog = Syslog::new(4096, LogLevel::Debug, false);
            syslog.write_log(LogLevel::Info, "clear test", None);
            syslog.syslog(SYSLOG_ACTION_CLEAR, 0).unwrap();

            let (count, _) = syslog.syslog(SYSLOG_ACTION_READ_ALL, 4096).unwrap();
            assert_eq!(count, 0);
        }

        #[test]
        fn test_syslog_16() {
            let syslog = Syslog::new(4096, LogLevel::Debug, false);
            syslog.write_log(LogLevel::Info, "read_clear test", None);

            let (count, data) = syslog.syslog(SYSLOG_ACTION_READ_CLEAR, 4096).unwrap();
            assert!(count > 0);
            assert!(data.is_some());

            let (unread, _) = syslog.syslog(SYSLOG_ACTION_SIZE_UNREAD, 0).unwrap();
            assert_eq!(unread, 0);
        }
    }
}