joularcore 0.2.0

Joular Core is a platform to measure power and energy across all systems, OSes and devices
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
/*
 * Copyright (c) 2025-2026, Adel Noureddine.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the
 * GNU Lesser General Public License v3.0 only (LGPL-3.0-only)
 * which accompanies this distribution, and is available at
 * https://www.gnu.org/licenses/lgpl-3.0.en.html
 *
 * Author : Adel Noureddine
 */

//! Windows backend.
//!
//! CPU power comes from RAPL model-specific registers, which user space cannot
//! read directly; the [Scaphandre RAPL driver] exposes them through a device
//! ([`rapl`]). CPU time comes from the Win32 process and system clocks
//! ([`cpu`]), and GPU power from the vendor command-line tools.
//!
//! [Scaphandre RAPL driver]: https://github.com/hubblo-org/windows-rapl-driver

use crate::config::AppMatch;
use crate::platform::cpu_usage::AppMonitor;
use crate::platform::gpu::VendorGpu;
use crate::sensor::{
    AppCpuUtilization, CpuUtilization, Platform, PowerSensor, ProcessCpuUtilization,
};
use std::time::Duration;

/// The Windows backend.
#[derive(Debug, Default)]
pub(crate) struct WindowsPlatform;

impl Platform for WindowsPlatform {
    fn cpu(&self) -> Box<dyn PowerSensor> {
        Box::new(rapl::RaplSensor::new(rapl::RaplDriver::open()))
    }

    fn gpu(&self) -> Box<dyn PowerSensor> {
        Box::new(VendorGpu)
    }

    fn cpu_usage(&self) -> Box<dyn CpuUtilization> {
        Box::new(cpu::cpu_usage())
    }

    fn process_cpu_usage(&self) -> Option<Box<dyn ProcessCpuUtilization>> {
        Some(cpu::process_tracker())
    }

    fn app_cpu_usage(
        &self,
        refresh_interval: Duration,
        app_match: AppMatch,
    ) -> Option<Box<dyn AppCpuUtilization>> {
        Some(AppMonitor::boxed(
            cpu::process_tracker,
            refresh_interval,
            app_match,
        ))
    }
}

/// CPU package energy from the Scaphandre RAPL driver.
mod rapl {
    use crate::platform::counter::{Interval, WrappingCounter, repeat_failure, warn_unavailable};
    use crate::sensor::PowerSensor;
    use crate::{Error, Result};
    use std::mem;

    use windows::Win32::Foundation::{CloseHandle, HANDLE};
    use windows::Win32::Storage::FileSystem::{
        CreateFileW, FILE_FLAG_OVERLAPPED, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_READ,
        FILE_SHARE_WRITE, OPEN_EXISTING,
    };
    use windows::Win32::System::IO::DeviceIoControl;
    use windows::core::w;

    /// How this sensor is named in errors.
    pub(crate) const SENSOR: &str = "Scaphandre RAPL driver";

    /// Intel RAPL model-specific registers.
    const MSR_INTEL_RAPL_POWER_UNIT: u64 = 0x606;
    const MSR_INTEL_PKG_ENERGY_STATUS: u64 = 0x611;

    /// AMD RAPL model-specific registers.
    const MSR_AMD_RAPL_POWER_UNIT: u64 = 0xc001_0299;
    const MSR_AMD_PKG_ENERGY_STATUS: u64 = 0xc001_029b;

    const FILE_DEVICE_UNKNOWN: u32 = 0x0000_0022;
    const METHOD_BUFFERED: u32 = 0;
    const FILE_READ_DATA: u32 = 0x0001;
    const FILE_WRITE_DATA: u32 = 0x0002;

    /// The package energy counter is 32 bits wide, so it wraps at 2^32 units.
    const ENERGY_COUNTER_MODULUS: f64 = 4_294_967_296.0;

    /// The driver's `CTL_CODE` macro, in const form.
    const fn ctl_code(device_type: u32, function: u32, method: u32, access: u32) -> u32 {
        (device_type << 16) | (access << 14) | (function << 2) | method
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum CpuVendor {
        Intel,
        Amd,
    }

    impl CpuVendor {
        fn power_unit_msr(self) -> u64 {
            match self {
                CpuVendor::Intel => MSR_INTEL_RAPL_POWER_UNIT,
                CpuVendor::Amd => MSR_AMD_RAPL_POWER_UNIT,
            }
        }

        fn package_energy_msr(self) -> u64 {
            match self {
                CpuVendor::Intel => MSR_INTEL_PKG_ENERGY_STATUS,
                CpuVendor::Amd => MSR_AMD_PKG_ENERGY_STATUS,
            }
        }
    }

    /// A handle on the Scaphandre RAPL driver.
    pub(crate) struct RaplDriver {
        handle: HANDLE,
        vendor: CpuVendor,
        /// Joules per counter unit.
        energy_unit: f64,
        counter: WrappingCounter,
    }

    // SAFETY: the handle is owned exclusively by this struct, which is reached only
    // through `&mut self` on the sensor holding it, so no two threads can use it at
    // once.
    unsafe impl Send for RaplDriver {}

    impl RaplDriver {
        /// Open the driver and probe the CPU vendor and energy units.
        ///
        /// Fails if the driver is not installed, if neither vendor's registers can
        /// be read, or if the package energy counter reads as zero — all of which
        /// would otherwise surface as a stream of zero-watt readings.
        pub(crate) fn open() -> Result<Self> {
            // SAFETY: the path is a static wide string and every other argument is
            // a plain value.
            let handle = unsafe {
                CreateFileW(
                    w!(r"\\.\ScaphandreDriver"),
                    FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0,
                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                    None,
                    OPEN_EXISTING,
                    FILE_FLAG_OVERLAPPED,
                    None,
                )
            }
            .map_err(|e| {
                Error::sensor(
                    SENSOR,
                    format!("cannot open \\\\.\\ScaphandreDriver ({e}); is the driver installed?"),
                )
            })?;

            // Probing needs the handle, so the driver is built with placeholder
            // readings and then filled in as each register is read.
            let mut driver = Self {
                handle,
                vendor: CpuVendor::Intel,
                energy_unit: 0.0,
                counter: WrappingCounter::new(0.0, 0.0),
            };

            driver.vendor = driver.detect_vendor()?;
            driver.energy_unit = driver.read_energy_unit()?;

            // A package counter reading zero means this CPU does not report package
            // energy through the driver, so no power figure is available at all.
            if driver.read_msr(driver.vendor.package_energy_msr())? == 0 {
                return Err(Error::sensor(
                    SENSOR,
                    "the CPU package energy counter reads zero",
                ));
            }

            // The 32-bit register counts in units of `energy_unit` joules, so it
            // wraps once it has counted 2^32 of them.
            driver.counter = WrappingCounter::new(
                ENERGY_COUNTER_MODULUS * driver.energy_unit,
                driver.read_energy()?,
            );

            Ok(driver)
        }

        /// Read one model-specific register through the driver.
        fn read_msr(&self, msr: u64) -> Result<u64> {
            let mut reply: u64 = 0;
            let mut bytes_returned: u32 = 0;
            let control_code = ctl_code(
                FILE_DEVICE_UNKNOWN,
                (msr & 0xFFF) as u32,
                METHOD_BUFFERED,
                FILE_READ_DATA | FILE_WRITE_DATA,
            );

            // SAFETY: the input and output buffers are `u64` locals whose sizes are
            // passed alongside them, and `handle` is a live device handle.
            unsafe {
                DeviceIoControl(
                    self.handle,
                    control_code,
                    Some(std::ptr::from_ref(&msr).cast()),
                    mem::size_of::<u64>() as u32,
                    Some(std::ptr::from_mut(&mut reply).cast()),
                    mem::size_of::<u64>() as u32,
                    Some(&mut bytes_returned),
                    None,
                )
            }
            .map_err(|e| Error::sensor(SENSOR, format!("reading MSR {msr:#x} failed: {e}")))?;

            Ok(reply)
        }

        /// Which vendor's register layout this CPU answers to.
        fn detect_vendor(&self) -> Result<CpuVendor> {
            for vendor in [CpuVendor::Intel, CpuVendor::Amd] {
                if self.read_msr(vendor.power_unit_msr()).is_ok() {
                    return Ok(vendor);
                }
            }

            Err(Error::sensor(
                SENSOR,
                "neither the Intel nor the AMD power unit register could be read",
            ))
        }

        /// Joules per energy counter unit, from the power unit register.
        fn read_energy_unit(&self) -> Result<f64> {
            const ENERGY_MASK: u64 = 0x1F00;

            let raw = self.read_msr(self.vendor.power_unit_msr())?;
            let exponent = ((raw & ENERGY_MASK) >> 8) as i32;
            let unit = 1.0 / 2.0_f64.powi(exponent);

            // A driver returning unexpected register contents would otherwise
            // cascade into NaN or infinite power figures.
            if !unit.is_finite() || unit <= 0.0 {
                return Err(Error::sensor(
                    SENSOR,
                    format!("implausible energy unit from register value {raw:#x}"),
                ));
            }

            Ok(unit)
        }

        /// The package energy counter, in joules.
        fn read_energy(&self) -> Result<f64> {
            let raw = self.read_msr(self.vendor.package_energy_msr())?;
            Ok((raw & 0xFFFF_FFFF) as f64 * self.energy_unit)
        }
    }

    /// CPU power, as driver-reported joules over the time they took to accumulate.
    pub(crate) struct RaplSensor {
        /// The open driver, or the reason it could not be opened — which is then
        /// reported on every read rather than once at construction.
        driver: Result<RaplDriver>,
        interval: Interval,
    }

    impl RaplSensor {
        pub(crate) fn new(driver: Result<RaplDriver>) -> Self {
            warn_unavailable(SENSOR, &driver);
            Self {
                driver,
                interval: Interval::default(),
            }
        }
    }

    impl PowerSensor for RaplSensor {
        fn power(&mut self) -> Result<f64> {
            let driver = match &mut self.driver {
                Ok(driver) => driver,
                Err(e) => return Err(repeat_failure(SENSOR, e)),
            };

            let joules = driver.counter.delta(driver.read_energy()?);

            // The first reading only establishes the baseline, and it has to be
            // taken even though it is discarded: skipping it would leave the
            // counter without a value to difference against.
            let Some(seconds) = self.interval.tick() else {
                return Ok(0.0);
            };

            Ok(joules / seconds)
        }
    }

    impl Drop for RaplDriver {
        fn drop(&mut self) {
            // SAFETY: `handle` came from CreateFileW and is not used afterwards.
            unsafe {
                let _ = CloseHandle(self.handle);
            }
        }
    }

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

        #[test]
        fn control_codes_match_the_drivers_ctl_code_macro() {
            // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x606 & 0xFFF, METHOD_BUFFERED,
            //          FILE_READ_DATA | FILE_WRITE_DATA)
            let expected = (FILE_DEVICE_UNKNOWN << 16) | (3 << 14) | (0x606 << 2);
            assert_eq!(
                ctl_code(
                    FILE_DEVICE_UNKNOWN,
                    0x606,
                    METHOD_BUFFERED,
                    FILE_READ_DATA | FILE_WRITE_DATA
                ),
                expected
            );
        }

        #[test]
        fn the_energy_counter_wraps_at_two_to_the_thirty_two() {
            // Losing one unit per wrap, as `0xFFFFFFFF` would, is a silent
            // under-count on every wrap.
            assert_eq!(ENERGY_COUNTER_MODULUS, 2f64.powi(32));
            assert_eq!(ENERGY_COUNTER_MODULUS as u64, 0xFFFF_FFFFu64 + 1);
        }

        #[test]
        fn each_vendor_uses_its_own_registers() {
            assert_eq!(CpuVendor::Intel.power_unit_msr(), 0x606);
            assert_eq!(CpuVendor::Intel.package_energy_msr(), 0x611);
            assert_eq!(CpuVendor::Amd.power_unit_msr(), 0xc001_0299);
            assert_eq!(CpuVendor::Amd.package_energy_msr(), 0xc001_029b);
        }
    }
}

/// CPU time: the system clock, per-process clocks, and process enumeration.
///
/// `pub(crate)` so `platform::cpu_usage` can name `cpu::ToolhelpPids` as this
/// target's process enumerator.
pub(crate) mod cpu {
    use crate::config::AppMatch;
    use crate::platform::cpu_usage::{CpuTimeDelta, TotalsSampler, matches_app_name};
    use crate::sensor::{CpuTotals, ProcessCpuUtilization};
    use std::mem;

    use windows::Win32::Foundation::{CloseHandle, FILETIME};
    use windows::Win32::System::Diagnostics::ToolHelp::{
        CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
        TH32CS_SNAPPROCESS,
    };
    use windows::Win32::System::Threading::{
        GetProcessTimes, GetSystemTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
    };

    /// Whole-system CPU utilization from `GetSystemTimes`.
    pub(crate) fn cpu_usage() -> TotalsSampler {
        TotalsSampler::new(system_cpu_totals)
    }

    /// A per-process tracker using `GetProcessTimes`.
    pub(crate) fn process_tracker() -> Box<dyn ProcessCpuUtilization> {
        Box::new(WindowsProcessTracker::default())
    }

    /// CPU utilization of a single process, from `GetProcessTimes` over
    /// `GetSystemTimes`.
    ///
    /// Both report the same unit — 100-nanosecond intervals — so a process's share
    /// of the machine is one delta over the other, the same arithmetic Linux does
    /// with `/proc`.
    #[derive(Debug, Default)]
    struct WindowsProcessTracker {
        delta: CpuTimeDelta,
    }

    impl ProcessCpuUtilization for WindowsProcessTracker {
        fn process_cpu_utilization(&mut self, pid: u32, cpu_total: Option<u64>) -> f64 {
            // Prefer the total the monitor measured, so the process share and the
            // system figure it is compared against cover the same interval.
            let Some(cpu_total) = cpu_total.or_else(system_cpu_total) else {
                return 0.0;
            };
            let Some(process_time) = process_time(pid) else {
                return 0.0;
            };

            self.delta.share(cpu_total, process_time)
        }
    }

    /// Convert a `FILETIME` to a count of 100-nanosecond intervals.
    fn filetime_to_u64(time: &FILETIME) -> u64 {
        ((time.dwHighDateTime as u64) << 32) | (time.dwLowDateTime as u64)
    }

    /// Cumulative system-wide CPU time.
    ///
    /// On Windows the kernel figure already includes idle time, so it is the total.
    fn system_cpu_totals() -> Option<CpuTotals> {
        let mut idle = FILETIME::default();
        let mut kernel = FILETIME::default();
        let mut user = FILETIME::default();

        // SAFETY: all three out-parameters are valid, correctly sized locals.
        let result = unsafe { GetSystemTimes(Some(&mut idle), Some(&mut kernel), Some(&mut user)) };
        if result.is_err() {
            return None;
        }

        Some(CpuTotals::new(
            filetime_to_u64(&kernel) + filetime_to_u64(&user),
            filetime_to_u64(&idle),
        ))
    }

    /// Cumulative system-wide CPU time, for when the caller has no reading of its
    /// own to share.
    fn system_cpu_total() -> Option<u64> {
        system_cpu_totals().map(|totals| totals.total)
    }

    /// Total kernel + user time for `pid`, in 100-nanosecond intervals.
    fn process_time(pid: u32) -> Option<u64> {
        // LIMITED_INFORMATION is enough for GetProcessTimes and, unlike
        // QUERY_INFORMATION, is grantable for processes of other users.
        // SAFETY: the arguments are plain values; the handle is closed below.
        let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }.ok()?;

        let mut creation = FILETIME::default();
        let mut exit = FILETIME::default();
        let mut kernel = FILETIME::default();
        let mut user = FILETIME::default();

        // SAFETY: `handle` is a live process handle and the four out-parameters are
        // valid locals.
        let result =
            unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) };
        // SAFETY: `handle` came from OpenProcess and is not used afterwards.
        let _ = unsafe { CloseHandle(handle) };

        result.ok()?;
        Some(filetime_to_u64(&kernel) + filetime_to_u64(&user))
    }

    /// Process enumeration through a toolhelp snapshot.
    ///
    /// Stateless — a snapshot is taken per sweep — but it takes `&mut self` to match
    /// the `sysinfo` enumerator on other platforms, which caches a process list.
    #[derive(Debug, Default)]
    pub(crate) struct ToolhelpPids;

    impl ToolhelpPids {
        /// PIDs of every live process whose image name matches `app_name`.
        pub(crate) fn matching_pids(&mut self, app_name: &str, app_match: AppMatch) -> Vec<u32> {
            snapshot_pids(app_name, app_match)
        }
    }

    /// Walk a toolhelp snapshot, collecting PIDs whose image name matches.
    fn snapshot_pids(app_name: &str, app_match: AppMatch) -> Vec<u32> {
        // SAFETY: TH32CS_SNAPPROCESS with pid 0 snapshots all processes.
        let Ok(snapshot) = (unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }) else {
            return Vec::new();
        };

        let mut pids = Vec::new();
        let mut entry = PROCESSENTRY32W {
            dwSize: mem::size_of::<PROCESSENTRY32W>() as u32,
            ..Default::default()
        };

        // SAFETY: `snapshot` is a live snapshot handle and `entry` has its dwSize
        // set as the API requires.
        if unsafe { Process32FirstW(snapshot, &mut entry) }.is_ok() {
            loop {
                let name_length = entry
                    .szExeFile
                    .iter()
                    .position(|&c| c == 0)
                    .unwrap_or(entry.szExeFile.len());
                let name = String::from_utf16_lossy(&entry.szExeFile[..name_length]);

                if matches_app_name(&name, app_name, app_match) {
                    pids.push(entry.th32ProcessID);
                }

                // SAFETY: as above; iteration stops when the API reports no more.
                if unsafe { Process32NextW(snapshot, &mut entry) }.is_err() {
                    break;
                }
            }
        }

        // SAFETY: `snapshot` came from CreateToolhelp32Snapshot and is not used
        // afterwards.
        let _ = unsafe { CloseHandle(snapshot) };

        pids
    }

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

        #[test]
        fn filetimes_are_read_as_one_64_bit_count() {
            let time = FILETIME {
                dwHighDateTime: 2,
                dwLowDateTime: 5,
            };
            assert_eq!(filetime_to_u64(&time), (2 << 32) + 5);
        }

        #[test]
        fn the_running_system_reports_cpu_time() {
            // The Windows clocks are always available, so a failure here means the
            // out-parameters are being passed wrongly.
            let totals = system_cpu_totals().expect("GetSystemTimes");
            assert!(totals.total > 0);
            assert!(totals.idle <= totals.total);
        }

        #[test]
        fn a_process_that_does_not_exist_reports_nothing() {
            // PID 0 is the idle process and cannot be opened for query.
            assert_eq!(process_time(0), None);
        }
    }
}