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
#![cfg_attr(not(target_family = "unix"), no_std)]
#![crate_name = "klogger"]
#![crate_type = "lib"]

#[cfg(not(target_os = "none"))]
extern crate core;
extern crate heapless;

use core::fmt;
use core::ops;

#[macro_use]
pub mod macros;

extern crate log;
extern crate termcodes;

#[cfg(target_arch = "x86_64")]
extern crate x86;

#[cfg(any(
    feature = "use_ioports",
    all(target_arch = "x86_64", target_os = "none")
))]
#[path = "arch/x86.rs"]
mod arch;

#[cfg(all(not(feature = "use_ioports"), target_family = "unix"))]
#[path = "arch/unix.rs"]
mod arch;

use heapless::consts::*;
use heapless::{String, Vec};
use log::{Level, LevelFilter, Metadata, Record, SetLoggerError};
use termcodes::color; // type level integer used to specify capacity

/// One Mhz is that many Hz.
const MHZ_TO_HZ: u64 = 1000 * 1000;

/// One Khz is that many Hz.
const KHZ_TO_HZ: u64 = 1000;

/// One sec has that many ns.
const _NS_PER_SEC: u64 = 1_000_000_000u64;

/// Global lock to protect serial line from concurrent printing.
pub static SERIAL_LINE_MUTEX: spin::Mutex<bool> = spin::Mutex::new(false);

#[derive(Debug)]
pub struct Directive {
    name: Option<String<U16>>,
    level: LevelFilter,
}

//unsafe impl ArrayLength<Directive> for Directive;

#[derive(Debug)]
struct KLogger {
    /// Do we even have a TSC?
    ///
    /// If not bad.
    has_tsc: bool,
    /// Is the underlying TSC invariant?
    ///
    /// If not, bad.
    has_invariant_tsc: bool,
    /// Point in time when this Klogger got initialized
    tsc_start: u64,
    /// Frequency in Hz
    ///
    /// Sometimes we can't figure this out (yet)
    tsc_frequency: Option<u64>,
    /// Filter(s) used by Klogger.
    ///
    /// Use module name or log level or both for filtering.
    filter: Vec<Directive, U8>,
}

enum ElapsedTime {
    Undetermined,
    Nanoseconds(u64),
    Cycles(u64),
}

impl fmt::Display for ElapsedTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ElapsedTime::Nanoseconds(ns) => write!(f, "{:>10}", ns),
            // the cyc is added here so we are made aware it's not nano-seconds
            ElapsedTime::Cycles(cycles) => write!(f, "{:>10} cyc", cycles),
            ElapsedTime::Undetermined => write!(f, ""),
        }
    }
}

impl KLogger {
    /// Time in nano seconds since KLogger init.
    fn elapsed(&self) -> ElapsedTime {
        if self.has_tsc {
            let cur = unsafe { x86::time::rdtsc() };

            if self.has_invariant_tsc && self.tsc_frequency.is_some() {
                let elapsed_cycles = cur - self.tsc_start;
                let _tsc_frequency_hz = self.tsc_frequency.unwrap_or(1); // This won't fail, checked by if above

                // Basic is: let ns = elapsed_cycles / (tsc_frequency / NS_PER_SEC);
                // But we avoid removing all precision with division:
                // TODO: fix overflow with * NS_PER_SEC
                //let ns = (elapsed_cycles * NS_PER_SEC) / tsc_frequency_hz;
                let ns = elapsed_cycles;

                ElapsedTime::Nanoseconds(ns)
            } else {
                // We can't convert cycles to a time
                ElapsedTime::Cycles(cur)
            }
        } else {
            // We don't know
            ElapsedTime::Undetermined
        }
    }

    /// Returns the maximum `LevelFilter` that this filter instance is
    /// configured to output.
    pub fn filter(&self) -> LevelFilter {
        return self
            .filter
            .iter()
            .map(|d| d.level)
            .max()
            .unwrap_or(LevelFilter::Off);
    }
}

impl log::Log for KLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        let level = metadata.level();
        let target = metadata.target();

        enabled(&self.filter, level, target)
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            let color = match record.level() {
                Level::Error => color::AnsiValue(202),
                Level::Warn => color::AnsiValue(167),
                Level::Info => color::AnsiValue(136),
                Level::Debug => color::AnsiValue(64),
                Level::Trace => color::AnsiValue(32),
            };

            sprintln!(
                "{}{}{} [{}{:5}{}] - {}: {}{}{}",
                color::Fg(color::LightYellow),
                self.elapsed(),
                color::Fg(color::Reset),
                color::Fg(color),
                record.level(),
                color::Fg(color::Reset),
                record.target(),
                color::Fg(color::LightWhite),
                record.args(),
                color::Fg(color::Reset),
            );
        }
    }

    fn flush(&self) {}
}

static mut LOGGER: KLogger = KLogger {
    has_tsc: false,
    has_invariant_tsc: false,
    tsc_start: 0,
    tsc_frequency: None,
    filter: Vec(heapless::i::Vec::new()),
};

/// A writer for the serial line. It holds a lock so
/// multiple cores/threads can print at the same time.
pub struct Writer<'a> {
    /// Lock on the serial line, it is implicitly released on a drop.
    #[allow(dead_code)]
    line_lock: spin::MutexGuard<'a, bool>,
}

impl<'a> Writer<'a> {
    /// Obtain a logger for the specified module.
    pub fn get_module(module: &str) -> Writer<'a> {
        use core::fmt::Write;
        let line_lock = SERIAL_LINE_MUTEX.lock();
        let mut ret = Writer { line_lock };
        write!(&mut ret, "[{}] ", module).expect("Writer");
        ret
    }

    /// Obtain a logger.
    pub fn get() -> Writer<'a> {
        let line_lock = SERIAL_LINE_MUTEX.lock();
        Writer { line_lock }
    }
}

impl<'a> ops::Drop for Writer<'a> {
    /// Release the logger (and the line_lock), end output with a newline.
    ///
    /// Serial standard mandates the use of '\r\n' for a newline and
    /// resetting the curser to the beginning.
    fn drop(&mut self) {
        use core::fmt::Write;
        #[allow(clippy::write_with_newline)]
        write!(self, "\r\n").expect("Newline");
    }
}

impl<'a> fmt::Write for Writer<'a> {
    /// Write stuff to serial out.
    fn write_str(&mut self, s: &str) -> fmt::Result {
        unsafe {
            arch::puts(s);
        }
        Ok(())
    }
}

/// A writer that doesn't respect the locking procedure and tries to write at all costs.
///
/// It's used by sprint at the moment. It can also be useful as part of panics handlers
/// where we really want to print in all circumstances.
pub struct WriterNoDrop;

impl WriterNoDrop {
    pub fn get() -> WriterNoDrop {
        WriterNoDrop
    }
}

impl fmt::Write for WriterNoDrop {
    /// Write stuff to serial out.
    fn write_str(&mut self, s: &str) -> fmt::Result {
        unsafe {
            arch::puts(s);
        }
        Ok(())
    }
}

pub fn init(args: &str) -> Result<(), SetLoggerError> {
    let cpuid = x86::cpuid::CpuId::new();

    unsafe {
        LOGGER.has_tsc = cpuid
            .get_feature_info()
            .map_or(false, |finfo| finfo.has_tsc());
        LOGGER.has_invariant_tsc = cpuid
            .get_extended_function_info()
            .map_or(false, |efinfo| efinfo.has_invariant_tsc());

        if LOGGER.has_tsc {
            LOGGER.tsc_start = x86::time::rdtsc();
        }

        let tsc_frequency_hz: Option<u64> = cpuid.get_tsc_info().and_then(|tinfo| {
            if tinfo.nominal_frequency() != 0 {
                // If we have a crystal clock we can calculate the tsc frequency directly
                Some(tinfo.tsc_frequency())
            } else if tinfo.numerator() != 0 && tinfo.denominator() != 0 {
                // Skylake and Kabylake don't report the crystal clock frequency,
                // so we approximate with CPU base frequency:
                cpuid.get_processor_frequency_info().map(|pinfo| {
                    let cpu_base_freq_hz = pinfo.processor_base_frequency() as u64 * MHZ_TO_HZ;
                    let crystal_hz =
                        cpu_base_freq_hz * tinfo.denominator() as u64 / tinfo.numerator() as u64;
                    crystal_hz * tinfo.numerator() as u64 / tinfo.denominator() as u64
                })
            } else {
                // We couldn't figure out the TSC frequency
                None
            }
        });

        // Check if we run in a VM and the hypervisor can give us the TSC frequency
        let vmm_tsc_frequency_hz: Option<u64> = cpuid
            .get_hypervisor_info()
            .and_then(|hv| hv.tsc_frequency().map(|tsc_khz| tsc_khz as u64 * KHZ_TO_HZ));

        if tsc_frequency_hz.is_some() {
            LOGGER.tsc_frequency = tsc_frequency_hz;
        } else if vmm_tsc_frequency_hz.is_some() {
            LOGGER.tsc_frequency = vmm_tsc_frequency_hz;
        }

        // Another way that segfaults in KVM:
        // The scalable bus frequency is encoded in the bit field MSR_PLATFORM_INFO[15:8]
        // and the nominal TSC frequency can be determined by multiplying this number
        // by a bus speed of 100 MHz.
        //(&mut LOGGER).tsc_frequency =
        //    ((x86::msr::rdmsr(x86::msr::MSR_PLATFORM_INFO) >> 8) & 0xff) * 1000000;

        parse_args(&mut LOGGER.filter, args);
        log::set_logger(&LOGGER).map(|()| log::set_max_level(LOGGER.filter()))
    }
}

pub fn putchar(c: char) {
    unsafe {
        arch::putc(c);
    }
}

/// Most of the filtering code is inspired or copied from
/// https://github.com/sebasmagri/env_logger/blob/master/src/filter/mod.rs
///
/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=error")
/// and return a vector with log directives.
fn parse_args(filter: &mut Vec<Directive, U8>, spec: &str) {
    let mut parts = spec.split('/');
    let mods = parts.next();
    if parts.next().is_some() {
        sprintln!(
            "warning: invalid logging spec '{}', \
             ignoring it (too many '/'s)",
            spec
        );
        return;
    }
    mods.map(|m| {
        for s in m.split(',') {
            if s.len() == 0 {
                continue;
            }
            let mut parts = s.split('=');
            let (log_level, name) =
                match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) {
                    (Some(part0), None, None) => {
                        // if the single argument is a log-level string or number,
                        // treat that as a global fallback
                        match part0.parse() {
                            Ok(num) => (num, None),
                            Err(_) => (LevelFilter::max(), Some(part0)),
                        }
                    }
                    (Some(part0), Some(""), None) => (LevelFilter::max(), Some(part0)),
                    (Some(part0), Some(part1), None) => match part1.parse() {
                        Ok(num) => (num, Some(part0)),
                        _ => {
                            sprintln!(
                                "warning: invalid logging spec '{}', \
                                 ignoring it",
                                part1
                            );
                            continue;
                        }
                    },
                    _ => {
                        sprintln!(
                            "warning: invalid logging spec '{}', \
                             ignoring it",
                            s
                        );
                        continue;
                    }
                };

            match filter.push(Directive {
                name: match name {
                    None => None,
                    Some(name) => Some(String::from(name)),
                },
                level: log_level,
            }) {
                Ok(_) => {}
                Err(e) => {
                    sprintln!("Unable to add new filter {:?}", e);
                }
            }
        }
    });
}

// Check whether a level and target are enabled by the set of directives.
fn enabled(directives: &[Directive], level: Level, target: &str) -> bool {
    // Search for the longest match, the vector is assumed to be pre-sorted.
    for directive in directives.iter().rev() {
        match directive.name {
            Some(ref name) if !target.starts_with(&**name) => {}
            Some(..) | None => return level <= directive.level,
        }
    }
    false
}

#[cfg(test)]
mod test {
    use heapless::consts::*;
    use heapless::String;
    use heapless::Vec as VEC;
    use log::{Level, LevelFilter};

    use super::{enabled, parse_args, Directive};

    #[test]
    fn filter_info() {
        let mut filter: Vec<Directive> = Vec::new();
        filter.push(Directive {
            name: None,
            level: LevelFilter::Info,
        });
        assert!(enabled(&filter, Level::Info, "crate1"));
        assert!(!enabled(&filter, Level::Debug, "crate1"));
    }

    #[test]
    fn filter_beginning_longest_match() {
        let mut filter: Vec<Directive> = Vec::new();
        filter.push(Directive {
            name: Some(String::from("crate2")),
            level: LevelFilter::Info,
        });
        filter.push(Directive {
            name: Some(String::from("crate2::mod")),
            level: LevelFilter::Debug,
        });
        filter.push(Directive {
            name: Some(String::from("crate1::mod1")),
            level: LevelFilter::Warn,
        });
        assert!(enabled(&filter, Level::Debug, "crate2::mod1"));
        assert!(!enabled(&filter, Level::Debug, "crate2"));
    }

    #[test]
    fn parse_default() {
        let mut filter: VEC<Directive, U8> = VEC::new();
        parse_args(&mut filter, "info,crate1::mod1=warn");
        assert!(enabled(&filter, Level::Warn, "crate1::mod1"));
        assert!(enabled(&filter, Level::Info, "crate2::mod2"));
    }

    #[test]
    fn match_full_path() {
        let logger = vec![
            Directive {
                name: Some(String::from("crate2")),
                level: LevelFilter::Info,
            },
            Directive {
                name: Some(String::from("crate1::mod1")),
                level: LevelFilter::Warn,
            },
        ];
        assert!(enabled(&logger, Level::Warn, "crate1::mod1"));
        assert!(!enabled(&logger, Level::Info, "crate1::mod1"));
        assert!(enabled(&logger, Level::Info, "crate2"));
        assert!(!enabled(&logger, Level::Debug, "crate2"));
    }

    #[test]
    fn no_match() {
        let logger = vec![
            Directive {
                name: Some(String::from("crate2")),
                level: LevelFilter::Info,
            },
            Directive {
                name: Some(String::from("crate1::mod1")),
                level: LevelFilter::Warn,
            },
        ];
        assert!(!enabled(&logger, Level::Warn, "crate3"));
    }

    #[test]
    fn match_beginning() {
        let logger = vec![
            Directive {
                name: Some(String::from("crate2")),
                level: LevelFilter::Info,
            },
            Directive {
                name: Some(String::from("crate1::mod1")),
                level: LevelFilter::Warn,
            },
        ];
        assert!(enabled(&logger, Level::Info, "crate2::mod1"));
    }

    #[test]
    fn match_beginning_longest_match() {
        let logger = vec![
            Directive {
                name: Some(String::from("crate2")),
                level: LevelFilter::Info,
            },
            Directive {
                name: Some(String::from("crate2::mod")),
                level: LevelFilter::Debug,
            },
            Directive {
                name: Some(String::from("crate1::mod1")),
                level: LevelFilter::Warn,
            },
        ];
        assert!(enabled(&logger, Level::Debug, "crate2::mod1"));
        assert!(!enabled(&logger, Level::Debug, "crate2"));
    }

    #[test]
    fn match_default() {
        let logger = vec![
            Directive {
                name: None,
                level: LevelFilter::Info,
            },
            Directive {
                name: Some(String::from("crate1::mod1")),
                level: LevelFilter::Warn,
            },
        ];
        assert!(enabled(&logger, Level::Warn, "crate1::mod1"));
        assert!(enabled(&logger, Level::Info, "crate2::mod2"));
    }

    #[test]
    fn zero_level() {
        let logger = vec![
            Directive {
                name: None,
                level: LevelFilter::Info,
            },
            Directive {
                name: Some(String::from("crate1::mod1")),
                level: LevelFilter::Off,
            },
        ];
        assert!(!enabled(&logger, Level::Error, "crate1::mod1"));
        assert!(enabled(&logger, Level::Info, "crate2::mod2"));
    }

    #[test]
    fn parse_args_valid() {
        let mut dirs: VEC<Directive, U8> = VEC::new();
        parse_args(&mut dirs, "crate1::mod1=error,crate1::mod2,crate2=debug");

        assert_eq!(dirs.len(), 3);
        assert_eq!(dirs[0].name, Some(String::from("crate1::mod1")));
        assert_eq!(dirs[0].level, LevelFilter::Error);

        assert_eq!(dirs[1].name, Some(String::from("crate1::mod2")));
        assert_eq!(dirs[1].level, LevelFilter::max());

        assert_eq!(dirs[2].name, Some(String::from("crate2")));
        assert_eq!(dirs[2].level, LevelFilter::Debug);
    }

    #[test]
    fn parse_spec_invalid_crate() {
        // test parse_spec with multiple = in specification
        let mut dirs: VEC<Directive, U8> = VEC::new();
        parse_args(&mut dirs, "crate1::mod1=warn=info,crate2=debug");

        assert_eq!(dirs.len(), 1);
        assert_eq!(dirs[0].name, Some(String::from("crate2")));
        assert_eq!(dirs[0].level, LevelFilter::Debug);
    }

    #[test]
    fn parse_spec_invalid_level() {
        // test parse_spec with 'noNumber' as log level
        let mut dirs: VEC<Directive, U8> = VEC::new();
        parse_args(&mut dirs, "crate1::mod1=noNumber,crate2=debug");

        assert_eq!(dirs.len(), 1);
        assert_eq!(dirs[0].name, Some(String::from("crate2")));
        assert_eq!(dirs[0].level, LevelFilter::Debug);
    }

    #[test]
    fn parse_spec_string_level() {
        // test parse_spec with 'warn' as log level
        let mut dirs: VEC<Directive, U8> = VEC::new();
        parse_args(&mut dirs, "crate1::mod1=wrong,crate2=warn");

        assert_eq!(dirs.len(), 1);
        assert_eq!(dirs[0].name, Some(String::from("crate2")));
        assert_eq!(dirs[0].level, LevelFilter::Warn);
    }

    #[test]
    fn parse_spec_empty_level() {
        // test parse_spec with '' as log level\
        let mut dirs: VEC<Directive, U8> = VEC::new();
        parse_args(&mut dirs, "crate1::mod1=wrong,crate2=");

        assert_eq!(dirs.len(), 1);
        assert_eq!(dirs[0].name, Some(String::from("crate2")));
        assert_eq!(dirs[0].level, LevelFilter::max());
    }

    #[test]
    fn parse_spec_global() {
        // test parse_spec with no crate
        let mut dirs: VEC<Directive, U8> = VEC::new();
        parse_args(&mut dirs, "warn,crate2=debug");

        assert_eq!(dirs.len(), 2);
        assert_eq!(dirs[0].name, None);
        assert_eq!(dirs[0].level, LevelFilter::Warn);
        assert_eq!(dirs[1].name, Some(String::from("crate2")));
        assert_eq!(dirs[1].level, LevelFilter::Debug);
    }
}