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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (c) 2024 NervoSys
//! Windows disk monitoring via WMI and Windows Storage APIs
//!
//! This module provides disk monitoring for Windows using:
//! - WMI Win32_DiskDrive for device information
//! - Performance Counters for I/O statistics
//! - DeviceIoControl for SMART data
use crate::disk::traits::*;
use std::collections::HashMap;
use std::path::PathBuf;
use wmi::{COMLibrary, WMIConnection};
/// Create WMI connection with robust COM initialization
/// Handles cases where COM is already initialized by the GUI framework
fn create_wmi_connection() -> Result<WMIConnection, Error> {
// Strategy 1: Fresh COM initialization (works best in background threads)
if let Ok(com) = COMLibrary::new() {
if let Ok(conn) = WMIConnection::with_namespace_path("root\\CIMV2", com) {
return Ok(conn);
}
}
// Strategy 2: COM without security init
if let Ok(com) = COMLibrary::without_security() {
if let Ok(conn) = WMIConnection::with_namespace_path("root\\CIMV2", com) {
return Ok(conn);
}
}
// Strategy 3: Assume COM is already initialized by the runtime (e.g., GUI apps)
let com = unsafe { COMLibrary::assume_initialized() };
WMIConnection::with_namespace_path("root\\CIMV2", com)
.map_err(|e| Error::InitializationFailed(e.to_string()))
}
/// Rows from one WMI query. A failed query is recorded in `failure` and reads as
/// no rows, so a caller can tell "the query failed" from "the machine has none".
fn wmi_rows<T: serde::de::DeserializeOwned>(
con: &WMIConnection,
query: &str,
failure: &mut Option<String>,
) -> Vec<T> {
match con.raw_query(query) {
Ok(rows) => rows,
Err(e) => {
if failure.is_none() {
*failure = Some(format!("{query}: {e}"));
}
Vec::new()
}
}
}
/// What `MSFT_PhysicalDisk` reports about one drive.
struct PhysicalDiskFacts {
size: Option<u64>,
kind: DiskType,
}
/// The drive's kind from `MSFT_PhysicalDisk.BusType` and `MediaType`.
///
/// BusType: 1 SCSI, 3 ATA, 7 USB, 8 RAID, 10 SAS, 11 SATA, 14 Virtual,
/// 15 File-backed virtual, 17 NVMe. MediaType: 3 HDD, 4 SSD, 0 unspecified.
/// A SATA or ATA drive whose medium is unspecified is `Unknown` -- which of
/// the two it is, is exactly the question.
fn kind_from_bus_and_media(bus: Option<u64>, media: Option<u64>) -> DiskType {
match (bus, media) {
(Some(17), _) => DiskType::NvmeSsd,
(Some(3 | 11), Some(4)) => DiskType::SataSsd,
(Some(3 | 11), Some(3)) => DiskType::SataHdd,
(Some(7), _) => DiskType::Usb,
(Some(1 | 8 | 10), _) => DiskType::Scsi,
(Some(14 | 15), _) => DiskType::Virtual,
_ => DiskType::Unknown,
}
}
/// Windows disk device implementation
pub struct WindowsDisk {
name: String,
device_path: PathBuf,
disk_type: DiskType,
model: Option<String>,
serial: Option<String>,
/// Capacity in bytes, or `None` where it has not been determined. WMI
/// already reports this as optional; it used to be flattened to `0` here.
size: Option<u64>,
disk_index: u32,
interface_type: Option<String>,
}
impl WindowsDisk {
// Mirrors the fields the Win32 disk enumeration hands back in one shot.
#[allow(clippy::too_many_arguments)]
pub fn new(
name: String,
device_path: PathBuf,
disk_type: DiskType,
model: Option<String>,
serial: Option<String>,
size: Option<u64>,
disk_index: u32,
interface_type: Option<String>,
) -> Self {
Self {
name,
device_path,
disk_type,
model,
serial,
size,
disk_index,
interface_type,
}
}
/// Create from device index (e.g., 0 for PhysicalDrive0)
pub fn from_index(index: u32) -> Result<Self, Error> {
let name = format!("PhysicalDrive{}", index);
let device_path = PathBuf::from(format!("\\\\.\\PhysicalDrive{}", index));
// Try to detect disk type
let disk_type = Self::detect_disk_type(index);
Ok(Self {
name,
device_path,
disk_type,
model: None,
serial: None,
// Not yet determined, rather than a zero-byte disk.
size: None,
disk_index: index,
interface_type: None,
})
}
/// Detect disk type from Windows APIs
fn detect_disk_type(_index: u32) -> DiskType {
// Would use IOCTL_STORAGE_QUERY_PROPERTY with StorageDeviceProperty
// For now, default to unknown
DiskType::Unknown
}
/// Read this drive's cumulative I/O counters.
///
/// Three defects were fixed here together, because each hid the next.
///
/// The class was `Win32_PerfFormattedData_PerfDisk_PhysicalDisk`, whose
/// `DiskReadBytesPerSec` is what its name says: an instantaneous **rate**.
/// It was stored in `DiskIoStats::read_bytes`, documented "Total bytes read
/// since boot" and rendered by the GUI as a byte total. On an idle machine
/// the rate is 0, so a host that had read 3.87 TB since boot reported 0 B.
/// `Win32_PerfRawData_PerfDisk_PhysicalDisk` carries the same property
/// names as raw cumulative counters, which is the quantity the field
/// promises and the quantity Linux's `/sys/block/*/stat` already supplied.
///
/// The instance filter was `Name LIKE '%{index}'`, matching the index as a
/// **suffix**. The instances are named `0 C:`, `1 E:`, `2`, `3 D:` — so on
/// a machine with a lettered drive the filter matched nothing, every call
/// fell through to the `_Total` fallback, and each disk reported the whole
/// machine's I/O as its own. The filter is now a prefix match, and there is
/// no `_Total` fallback: a drive with no instance has no counters, which is
/// not the same as having the sum of every other drive's.
///
/// `read_time_ms`, `write_time_ms` and `queue_depth` were hardcoded
/// `Some(0)` while this very class published all three.
fn read_io_counters(&self) -> Result<DiskIoStats, Error> {
// The instance name is the physical index, optionally followed by a
// space and the drive letters: "0 C:", "1 E:", "2".
let index = self.name.replace("PhysicalDrive", "");
let query =
format!("{DISK_PERF_SELECT} WHERE Name = \'{index}\' OR Name LIKE \'{index} %\'");
// A failed query is an error. Read as an empty table it would say this
// drive has no instance, which is a different claim.
let perfs: Vec<DiskPerf> = create_wmi_connection()?
.raw_query(&query)
.map_err(|e| Error::QueryFailed(format!("PhysicalDisk performance query: {e}")))?;
let Some(perf) = perfs.first() else {
return Err(Error::QueryFailed(format!(
"no PhysicalDisk performance instance named \'{index}\'"
)));
};
Ok(perf.to_io_stats())
}
}
/// One row of `Win32_PerfRawData_PerfDisk_PhysicalDisk`.
#[derive(serde::Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct DiskPerf {
name: String,
disk_read_bytes_per_sec: u64,
disk_write_bytes_per_sec: u64,
disk_reads_per_sec: u64,
disk_writes_per_sec: u64,
percent_disk_read_time: u64,
percent_disk_write_time: u64,
current_disk_queue_length: u32,
}
const DISK_PERF_SELECT: &str = "SELECT Name, DiskReadBytesPerSec, DiskWriteBytesPerSec, \
DiskReadsPerSec, DiskWritesPerSec, PercentDiskReadTime, PercentDiskWriteTime, \
CurrentDiskQueueLength FROM Win32_PerfRawData_PerfDisk_PhysicalDisk";
impl DiskPerf {
fn to_io_stats(&self) -> DiskIoStats {
DiskIoStats {
// `Win32_PerfRawData_*` gives raw cumulative counters; the
// `_per_sec` suffix is the counter's display semantics, not its
// value. These are real readings.
read_bytes: Some(self.disk_read_bytes_per_sec),
write_bytes: Some(self.disk_write_bytes_per_sec),
read_ops: Some(self.disk_reads_per_sec),
write_ops: Some(self.disk_writes_per_sec),
// The two timers are PERF_PRECISION_100NS_TIMER: the raw value is
// busy time in 100-nanosecond units.
read_time_ms: Some(self.percent_disk_read_time / 10_000),
write_time_ms: Some(self.percent_disk_write_time / 10_000),
queue_depth: Some(self.current_disk_queue_length),
// Both need two samples to difference; one call has nothing to
// difference against.
avg_latency_us: None,
read_throughput: None,
write_throughput: None,
}
}
/// The physical drive index this instance belongs to, from names shaped
/// `"0 C:"`, `"1 E:"` or `"2"`. `_Total` and anything unparseable is None.
fn physical_index(&self) -> Option<u32> {
self.name
.split_whitespace()
.next()
.and_then(|first| first.parse().ok())
}
}
/// Every physical drive's cumulative I/O counters, in one query.
///
/// `read_io_counters` opens a WMI connection and runs a filtered query *per
/// disk*, and the connection is what costs: four drives on this machine measured
/// 772 ms in total, ~193 ms each, against 0.5 ms for the capacity-only path.
/// Both the Prometheus exporter and the pipeline want counters for every drive
/// at once, and paying for one connection instead of N takes that to a single
/// round trip.
///
/// Keyed by `PhysicalDriveN` to match [`DiskInfo::name`], so a caller can join
/// against an enumeration without re-deriving the index.
pub fn all_io_counters() -> Result<std::collections::HashMap<String, DiskIoStats>, Error> {
// A failed query is an error. An empty map would say the machine has no
// drives, which a failed WMI call has not established.
let perfs: Vec<DiskPerf> = create_wmi_connection()?
.raw_query(DISK_PERF_SELECT)
.map_err(|e| Error::QueryFailed(format!("PhysicalDisk performance query: {e}")))?;
Ok(perfs
.iter()
.filter_map(|perf| {
// No `_Total`: it is the sum over every drive, and attributing that
// to any one of them is the defect this reader was fixed for once
// already.
let index = perf.physical_index()?;
Some((format!("PhysicalDrive{index}"), perf.to_io_stats()))
})
.collect())
}
impl WindowsDisk {
/// This drive's entry from the SMART collector, matched on physical index.
///
/// The collector enumerates every drive in one PowerShell round trip, so
/// picking one entry out of it used to cost a subprocess per call. It now
/// reads a run shared across every drive and every accessor —
/// [`crate::smart::SmartMonitor::cached_disks`] — which is what makes the
/// per-device trait affordable over a whole machine.
fn smart_disk(&self) -> Option<crate::smart::SmartDiskInfo> {
let wanted = format!(r"\\.\PhysicalDrive{}", self.disk_index);
crate::smart::SmartMonitor::cached_disks()
.iter()
.find(|d| d.device == wanted)
.cloned()
}
/// Build [`NvmeInfo`] from what the controller itself reported.
///
/// Fields stay `None` when the controller did not report them. `percentage_used`
/// of 0 and `critical_warnings` of 0 are readings — a new drive with nothing
/// wrong — and are preserved as such.
fn nvme_info_from_controller(&self, data: crate::disk::windows_nvme::NvmeData) -> NvmeInfo {
let id = data.identify;
let health = data.health;
// Identity from Identify Controller, falling back to WMI if the controller
// served the log page but not the identify structure.
let wmi = if id.is_none() {
self.smart_disk()
} else {
None
};
let identity = |from_id: Option<String>, from_wmi: Option<String>| {
from_id.unwrap_or_else(|| from_wmi.unwrap_or_default())
};
NvmeInfo {
model: identity(
id.as_ref().map(|i| i.model.clone()),
wmi.as_ref().map(|w| w.model.clone()),
),
serial: identity(
id.as_ref().map(|i| i.serial.clone()),
wmi.as_ref().map(|w| w.serial.clone()),
),
firmware: identity(
id.as_ref().map(|i| i.firmware.clone()),
wmi.as_ref().map(|w| w.firmware.clone()),
),
nvme_version: id.as_ref().and_then(|i| i.version.clone()),
// Identify Controller first, WMI second, and `None` if neither
// answered. The trailing `.unwrap_or(0)` here turned "no source
// knew" into a zero-byte drive.
total_capacity: id
.as_ref()
.and_then(|i| i.total_capacity)
.map(|c| c.min(u64::MAX as u128) as u64)
.or_else(|| wmi.as_ref().and_then(|w| w.capacity_bytes)),
unallocated_capacity: id
.as_ref()
.and_then(|i| i.unallocated_capacity)
.map(|c| c.min(u64::MAX as u128) as u64),
controller_id: id.as_ref().map(|i| i.controller_id),
num_namespaces: id.as_ref().map(|i| i.num_namespaces),
temperature_sensors: health
.as_ref()
.and_then(|h| h.temperature_celsius())
.map(|t| vec![t])
.unwrap_or_default(),
// From Get Features (FID 0x02); the available states below come from
// Identify, so the list can be populated while the current state is
// not, on a controller that does not implement Get Features.
power_state: data.power_state,
available_power_states: id
.as_ref()
.map(|i| {
i.power_states
.iter()
.map(|p| NvmePowerState {
state: p.state,
max_power_watts: p.max_power_watts,
entry_latency_us: p.entry_latency_us,
exit_latency_us: p.exit_latency_us,
})
.collect()
})
.unwrap_or_default(),
percentage_used: health.as_ref().map(|h| h.percentage_used),
data_units_read: health
.as_ref()
.map(|h| h.data_units_read.min(u64::MAX as u128) as u64),
data_units_written: health
.as_ref()
.map(|h| h.data_units_written.min(u64::MAX as u128) as u64),
host_read_commands: health
.as_ref()
.map(|h| h.host_read_commands.min(u64::MAX as u128) as u64),
host_write_commands: health
.as_ref()
.map(|h| h.host_write_commands.min(u64::MAX as u128) as u64),
critical_warnings: health.as_ref().map(|h| h.critical_warning),
available_spare: health.as_ref().map(|h| h.available_spare_percent),
available_spare_threshold: health.as_ref().map(|h| h.available_spare_threshold_percent),
controller_busy_time_minutes: health
.as_ref()
.map(|h| h.controller_busy_time.min(u64::MAX as u128) as u64),
unsafe_shutdowns: health
.as_ref()
.map(|h| h.unsafe_shutdowns.min(u64::MAX as u128) as u64),
}
}
/// The pre-3.1 path: identity from WMI, with everything the controller alone
/// can answer left `None`. Reached only when the passthrough fails on a device
/// that is nonetheless NVMe.
fn nvme_info_from_wmi(&self) -> Result<NvmeInfo, Error> {
let Some(disk) = self.smart_disk() else {
return Err(Error::QueryFailed(format!(
"no device data for physical drive {}",
self.disk_index
)));
};
if disk.media_type != crate::smart::DriveMediaType::NVMe {
return Err(Error::NotSupported);
}
Ok(NvmeInfo {
model: disk.model.clone(),
serial: disk.serial.clone(),
firmware: disk.firmware.clone(),
nvme_version: None,
total_capacity: disk.capacity_bytes,
unallocated_capacity: None,
controller_id: None,
num_namespaces: None,
temperature_sensors: disk
.temperature_celsius
.map(|t| vec![t as f32])
.unwrap_or_default(),
power_state: None,
available_power_states: Vec::new(),
percentage_used: disk.nvme_percentage_used,
// Bytes into NVMe data units of 1000 x 512 bytes, the unit the controller
// path above reports. Dividing by 512 gave a count 1000 times too large.
data_units_read: disk
.total_bytes_read
.map(|b| b / (crate::disk::nvme_log::BYTES_PER_DATA_UNIT as u64)),
data_units_written: disk
.total_bytes_written
.map(|b| b / (crate::disk::nvme_log::BYTES_PER_DATA_UNIT as u64)),
host_read_commands: None,
host_write_commands: None,
critical_warnings: None,
// This fallback never reads the health log, so the SMART/Health fields
// stay unread rather than being filled from WMI.
available_spare: None,
available_spare_threshold: None,
controller_busy_time_minutes: None,
unsafe_shutdowns: None,
})
}
}
impl DiskDevice for WindowsDisk {
fn name(&self) -> &str {
&self.name
}
fn disk_type(&self) -> DiskType {
self.disk_type
}
fn info(&self) -> Result<DiskInfo, Error> {
Ok(DiskInfo {
name: self.name.clone(),
// Unread is `None`. This used to be the string "Unknown".
model: self.model.clone(),
serial: self.serial.clone(),
firmware: None,
capacity: self.size,
block_size: None,
disk_type: self.disk_type,
interface_type: self.interface_type.clone(),
// Not read. `IOCTL_STORAGE_QUERY_PROPERTY` with
// `StorageAccessAlignmentProperty` reports both; until that is
// called, 512 was the common value standing in for this drive's.
physical_sector_size: None,
logical_sector_size: None,
// Not read. This was `Some(7200)` under the comment "Common HDD
// speed" for every drive not already known to be an SSD -- an
// invented RPM, not this drive's. A real rate comes from ATA
// IDENTIFY word 217; `disk_type` already carries SSD vs HDD.
rotation_rate: None,
vendor: None,
})
}
fn io_stats(&self) -> Result<DiskIoStats, Error> {
self.read_io_counters()
}
fn health(&self) -> Result<DiskHealth, Error> {
// An NVMe controller grades itself. Critical warning bits are the drive
// saying something is wrong now; spare below its own threshold and wear at
// or past 100% are conditions it will not flag until they bite.
if let Ok(data) = crate::disk::windows_nvme::query(self.disk_index) {
if let Some(health) = data.health {
// Bit 0 spare below threshold, 1 temperature past threshold,
// 2 reliability degraded, 3 read-only, 4 volatile backup failed.
const RELIABILITY_DEGRADED: u8 = 0b0000_0100;
const READ_ONLY: u8 = 0b0000_1000;
return Ok(
if health.critical_warning & (RELIABILITY_DEGRADED | READ_ONLY) != 0 {
DiskHealth::Critical
} else if health.critical_warning != 0
|| health.percentage_used >= 100
|| health.available_spare_percent < health.available_spare_threshold_percent
{
DiskHealth::Warning
} else {
DiskHealth::Healthy
},
);
}
}
// For an ATA device the same question goes to the storage driver, which
// answers with the drive's own failure prediction. That prediction is a
// reading, so grading `Healthy` from it is not the empty-scorecard problem
// `smart::tests::a_drive_with_no_readable_counters_is_not_graded_healthy`
// guards against: here the drive was asked and said no.
if let Ok(ata) = crate::disk::windows_ata::query(self.disk_index) {
if ata.predict_failure == Some(true) {
return Ok(DiskHealth::Failed);
}
// Sectors the drive could not read and has not yet remapped are data at
// risk now, and it will not predict failure over them. Reallocated
// sectors are deliberately not graded: whether a count is alarming is
// the threshold's call, and SMART READ THRESHOLDS is not reachable
// through this ioctl.
if let Some(smart) = &ata.smart {
// Unread counters fall through to the Windows status below, not to Healthy.
let graded =
grade_at_risk_sectors(smart.pending_sectors(), smart.uncorrectable_sectors());
if graded != DiskHealth::Unknown {
return Ok(graded);
}
}
}
// Windows publishes a HealthStatus per physical disk; the SMART collector
// already reads it, so ask that rather than guessing Unknown.
match self.smart_disk() {
Some(disk) => Ok(match disk.health {
crate::smart::DiskHealth::Good => DiskHealth::Healthy,
crate::smart::DiskHealth::Warning => DiskHealth::Warning,
crate::smart::DiskHealth::Critical => DiskHealth::Critical,
crate::smart::DiskHealth::Failed => DiskHealth::Failed,
crate::smart::DiskHealth::Unknown => DiskHealth::Unknown,
}),
None => Ok(DiskHealth::Unknown),
}
}
fn smart_info(&self) -> Result<SmartInfo, Error> {
// On NVMe the health log page carries temperature, power-on hours, power
// cycles and error counts, and needs no elevation. The WMI path below
// reaches the same numbers only through `Get-StorageReliabilityCounter`,
// which does require it — so prefer the controller and keep WMI for the
// SATA and USB devices that have no log page.
if let Ok(data) = crate::disk::windows_nvme::query(self.disk_index) {
if let Some(health) = data.health {
return Ok(SmartInfo {
// The critical warning field is the drive's own verdict: any
// bit set means it is reporting a condition against itself.
// The NVMe log page is the controller grading itself.
passed: Some(health.critical_warning == 0),
attributes: Vec::new(),
temperature: health.temperature_celsius(),
power_on_hours: Some(health.power_on_hours.min(u64::MAX as u128) as u64),
power_cycle_count: Some(health.power_cycles.min(u64::MAX as u128) as u64),
// NVMe has no reallocated or pending sector concept; those are
// ATA notions. Reporting 0 would assert a healthy count that
// was never measured.
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_sectors: Some(health.media_errors.min(u64::MAX as u128) as u64),
source: SmartSource::NvmeLogPage,
});
}
}
// SATA and USB drives have no log page, but the storage driver will issue
// SMART READ DATA on their behalf for an unelevated caller. This is the
// only path on Windows to reallocated and pending sector counts — the WMI
// fallback below cannot reach them at all, and needs elevation for the
// counters it can reach.
if let Ok(ata) = crate::disk::windows_ata::query(self.disk_index) {
if let Some(smart) = ata.smart {
return Ok(SmartInfo {
// The drive's own prediction, not a verdict computed from the
// attributes below.
// The ATA failure prediction is the drive grading itself.
passed: ata.predict_failure.map(|failing| !failing),
attributes: smart
.attributes
.iter()
.map(|a| SmartAttribute {
id: a.id,
name: a.name(),
value: a.value,
worst: a.worst,
// SMART READ THRESHOLDS is a separate ATA command with
// no ioctl of its own, so no threshold was read here.
threshold: None,
raw_value: a.raw,
critical: a.pre_fail(),
})
.collect(),
temperature: smart.temperature_celsius().map(|c| c as f32),
power_on_hours: smart.power_on_hours(),
power_cycle_count: smart.power_cycle_count(),
reallocated_sectors: smart.reallocated_sectors(),
pending_sectors: smart.pending_sectors(),
uncorrectable_sectors: smart.uncorrectable_sectors(),
source: SmartSource::AtaAttributes,
});
}
}
let Some(disk) = self.smart_disk() else {
return Err(Error::QueryFailed(format!(
"no SMART data for physical drive {}",
self.disk_index
)));
};
// Every counter is Option because the Windows storage stack only exposes
// them to an elevated caller: unelevated, `Get-StorageReliabilityCounter`
// fails with PermissionDenied and there is genuinely nothing to report.
// `passed` reflects the platform's own health verdict, which *is*
// available without elevation.
Ok(SmartInfo {
// Not read on this path. Neither the NVMe log page nor the ATA
// prediction was reachable, and what is left is Windows'
// `HealthStatus` -- the storage stack's opinion, not the drive's
// verdict, and `smart::DiskHealth` is partly a score computed here
// from the counters. `disk.{n}.health` publishes that verdict
// separately and honestly; this field is for the drive's own.
passed: None,
attributes: disk
.attributes
.iter()
.map(|a| SmartAttribute {
id: a.id.min(u8::MAX as u16) as u8,
name: a.name.clone(),
value: a.value.min(u8::MAX as u64) as u8,
worst: a.worst.min(u8::MAX as u64) as u8,
threshold: a.threshold.map(|t| t.min(u8::MAX as u64) as u8),
raw_value: a.raw_value,
critical: a.pre_fail,
})
.collect(),
temperature: disk.temperature_celsius.map(|t| t as f32),
power_on_hours: disk.power_on_hours,
power_cycle_count: disk.power_cycle_count,
reallocated_sectors: disk.reallocated_sectors,
pending_sectors: disk.pending_sectors,
uncorrectable_sectors: disk.uncorrectable_errors,
source: SmartSource::StorageStack,
})
}
fn nvme_info(&self) -> Result<NvmeInfo, Error> {
// Ask the controller directly. This settles "is this NVMe" without
// consulting WMI's MediaType, which reports the medium (`SSD`) rather than
// the transport and so classified every NVMe drive here as a plain SSD
// until 3.0.0 — making this method refuse the very drives it exists for.
// The device itself rejecting the NVMe protocol is a better answer than any
// string comparison.
match crate::disk::windows_nvme::query(self.disk_index) {
Ok(data) => Ok(self.nvme_info_from_controller(data)),
Err(Error::NotSupported) => Err(Error::NotSupported),
// The passthrough can fail on a drive that is genuinely NVMe — a driver
// that does not implement the protocol query, for instance. Fall back
// to what WMI knows rather than losing the identity fields entirely.
Err(_) => self.nvme_info_from_wmi(),
}
}
fn device_path(&self) -> PathBuf {
self.device_path.clone()
}
fn filesystem_info(&self) -> Result<Vec<FilesystemInfo>, Error> {
use serde::Deserialize;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32DiskPartition {
device_i_d: String,
disk_index: u32,
index: u32,
size: Option<u64>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32LogicalDiskToPartition {
antecedent: String,
dependent: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32LogicalDisk {
device_i_d: String,
file_system: Option<String>,
size: Option<u64>,
free_space: Option<u64>,
volume_name: Option<String>,
}
let mut filesystems = Vec::new();
// A WMI failure is kept rather than read as an empty table: a machine whose
// queries failed must not look like one with no filesystems.
let mut wmi_failure: Option<String> = None;
// Try WMI approach first to get partition-to-logical disk mapping
let wmi_con = create_wmi_connection();
if let Err(e) = &wmi_con {
wmi_failure = Some(format!("WMI connection: {e}"));
}
if let Ok(wmi_con) = wmi_con {
// Get partitions for this disk
let partition_query = format!(
"SELECT DeviceID, DiskIndex, Index, Size FROM Win32_DiskPartition WHERE DiskIndex = {}",
self.disk_index
);
let partitions: Vec<Win32DiskPartition> =
wmi_rows(&wmi_con, &partition_query, &mut wmi_failure);
// Get logical disk to partition mappings
let mappings: Vec<Win32LogicalDiskToPartition> = wmi_rows(
&wmi_con,
"SELECT Antecedent, Dependent FROM Win32_LogicalDiskToPartition",
&mut wmi_failure,
);
// Get all logical disks
let logical_disks: Vec<Win32LogicalDisk> = wmi_rows(
&wmi_con,
"SELECT DeviceID, FileSystem, Size, FreeSpace, VolumeName FROM Win32_LogicalDisk",
&mut wmi_failure,
);
// Match partitions to logical disks
for partition in &partitions {
// Find mapping for this partition
for mapping in &mappings {
// Matched with its closing quote. A bare `contains` let
// "Disk #0, Partition #1" match "Disk #0, Partition #10", so
// a disk with ten or more partitions listed volumes twice.
let quoted = format!("DeviceID=\"{}\"", partition.device_i_d);
if mapping.antecedent.contains("ed) {
// Extract drive letter from dependent (e.g., "Win32_LogicalDisk.DeviceID=\"C:\"")
if let Some(start) = mapping.dependent.find("DeviceID=\"") {
let start = start + 10;
if let Some(end) = mapping.dependent[start..].find('"') {
let drive_letter = &mapping.dependent[start..start + end];
// Find the logical disk info
if let Some(ld) =
logical_disks.iter().find(|d| d.device_i_d == drive_letter)
{
// WMI reports both as nullable and they
// were flattened to 0 here, so a drive with
// a null `Size` became a filesystem of no
// size with none of it used.
let total_size = ld.size;
let free_space = ld.free_space;
let used_size = match (total_size, free_space) {
(Some(total), Some(free)) => {
Some(total.saturating_sub(free))
}
_ => None,
};
filesystems.push(FilesystemInfo {
mount_point: PathBuf::from(format!("{}\\", drive_letter)),
// Empty when WMI did not report the file system. This used
// to be the string "Unknown", a value the reader had not
// read presented as a file system name. The ontology and
// the observability API both treat "" as absent.
fs_type: ld.file_system.clone().unwrap_or_default(),
total_size,
used_size,
available_size: free_space,
total_inodes: None,
used_inodes: None,
read_only: None,
});
}
}
}
}
}
}
}
// There used to be a fallback here that, when no partition of this disk
// mapped to a volume, listed every fixed and removable drive letter on the
// machine as this disk's filesystems ("won't correctly map to physical
// disks but at least shows something"). A disk with no lettered volume, such
// as one holding only Linux partitions, was reported as mounted at C:. A
// drive letter that cannot be tied to this disk is not one of its
// filesystems, so the fallback is gone.
// No filesystem was found and a WMI query failed: that is an error,
// not a machine with none.
if filesystems.is_empty() {
if let Some(reason) = wmi_failure {
return Err(Error::QueryFailed(format!(
"filesystem enumeration: {reason}"
)));
}
}
Ok(filesystems)
}
}
/// Enumerate Windows disk devices using WMI
pub fn enumerate() -> Result<Vec<Box<dyn DiskDevice>>, Error> {
use serde::Deserialize;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Win32DiskDrive {
device_i_d: String,
model: Option<String>,
serial_number: Option<String>,
size: Option<u64>,
media_type: Option<String>,
interface_type: Option<String>,
index: u32,
}
let mut disks: Vec<Box<dyn DiskDevice>> = Vec::new();
// Each drive's real length, keyed by disk index.
//
// `Win32_DiskDrive.Size` is not the drive's length: Windows computes it
// from a legacy geometry -- cylinders x 255 heads x 63 sectors x 512 bytes
// -- and drops the partial cylinder at the end. On the machine this was
// measured on every drive read 2,612,736 bytes short (a 4 TB 990 PRO as
// 4,000,784,417,280 against 4,000,787,030,016), published as a
// measurement. `MSFT_PhysicalDisk.Size`, what `Get-PhysicalDisk` reads, is
// the length. Where that class is unavailable (before Windows 8) the
// geometric figure remains, and is a slight undercount.
//
// The same class carries `BusType` and `MediaType`, which say what the
// drive is. The kind used to be inferred from the model string -- "990
// PRO" meant NVMe -- and anything on a SCSI interface defaulted to an NVMe
// SSD, so a hard disk behind a RAID or SAS controller was published as
// `nvme_ssd`.
// A failed query leaves this map empty, which only lowers each drive's kind
// to the interface check below, or to Unknown. It never drops a drive, so it
// is not the failure the enumeration reports.
let physical: HashMap<u32, PhysicalDiskFacts> = crate::platform::windows::wmi_query(
"root\\Microsoft\\Windows\\Storage",
"SELECT DeviceId, Size, BusType, MediaType FROM MSFT_PhysicalDisk",
)
.map(|rows| {
rows.iter()
.filter_map(|row| {
let index = crate::platform::windows::wmi_str(row, "DeviceId")
.parse::<u32>()
.ok()?;
let number = |key: &str| -> Option<u64> {
match row.get(key)? {
wmi::Variant::UI8(v) => Some(*v),
wmi::Variant::I8(v) => u64::try_from(*v).ok(),
wmi::Variant::UI4(v) => Some(*v as u64),
wmi::Variant::I4(v) => u64::try_from(*v).ok(),
wmi::Variant::UI2(v) => Some(*v as u64),
wmi::Variant::I2(v) => u64::try_from(*v).ok(),
wmi::Variant::String(s) => s.parse().ok(),
_ => None,
}
};
Some((
index,
PhysicalDiskFacts {
size: number("Size"),
kind: kind_from_bus_and_media(number("BusType"), number("MediaType")),
},
))
})
.collect()
})
.unwrap_or_default();
// A failed connection or query is recorded here, not read as an empty drive
// list: a machine whose WMI query failed must not look like one with no
// disks. It is returned below if the raw-device fallback finds nothing.
let mut wmi_failure: Option<String> = None;
// Use robust WMI connection that handles GUI context
let wmi_con = create_wmi_connection();
if let Err(e) = &wmi_con {
wmi_failure = Some(format!("WMI connection: {e}"));
}
if let Ok(wmi_con) = wmi_con {
let wmi_disks: Vec<Win32DiskDrive> = wmi_rows(
&wmi_con,
"SELECT DeviceID, Model, SerialNumber, Size, MediaType, InterfaceType, Index FROM Win32_DiskDrive",
&mut wmi_failure,
);
for wmi_disk in wmi_disks {
// Determine disk type - check multiple sources for best accuracy
// Read, not inferred. Without `MSFT_PhysicalDisk` only an interface
// Windows names as USB says anything; the rest is unknown rather
// than guessed from a model string.
let disk_type = match physical.get(&wmi_disk.index) {
Some(facts) => facts.kind,
None => match wmi_disk.interface_type.as_deref() {
Some(iface) if iface.eq_ignore_ascii_case("USB") => DiskType::Usb,
_ => DiskType::Unknown,
},
};
// Format interface type for display
let interface_type = wmi_disk.interface_type.map(|iface| {
match iface.to_uppercase().as_str() {
"SCSI" => {
// SCSI often means NVMe on modern systems
if matches!(disk_type, DiskType::NvmeSsd) {
"NVMe (PCIe)".to_string()
} else {
"SCSI".to_string()
}
}
"IDE" => "SATA".to_string(),
"USB" => "USB".to_string(),
"1394" => "FireWire".to_string(),
other => other.to_string(),
}
});
let disk = WindowsDisk::new(
format!("PhysicalDrive{}", wmi_disk.index),
PathBuf::from(format!("\\\\.\\PhysicalDrive{}", wmi_disk.index)),
disk_type,
wmi_disk.model,
wmi_disk.serial_number.map(|s| s.trim().to_string()),
// WMI already answers `Option`; this used to discard it.
physical
.get(&wmi_disk.index)
.and_then(|f| f.size)
.or(wmi_disk.size),
wmi_disk.index,
interface_type,
);
disks.push(Box::new(disk));
}
}
// Fallback: try to enumerate physical drives directly
if disks.is_empty() {
for index in 0..8 {
match WindowsDisk::from_index(index) {
Ok(disk) => {
use std::fs::OpenOptions;
use std::os::windows::fs::OpenOptionsExt;
const FILE_FLAG_NO_BUFFERING: u32 = 0x20000000;
const FILE_SHARE_READ: u32 = 0x00000001;
const FILE_SHARE_WRITE: u32 = 0x00000002;
let device_path = format!("\\\\.\\PhysicalDrive{}", index);
if let Ok(_file) = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_NO_BUFFERING)
.open(&device_path)
{
disks.push(Box::new(disk));
}
}
Err(_) => continue,
}
}
}
// If no disks found, return error. A failed WMI read is reported as that
// failure, not as "no disks", which the caller would render as none.
if disks.is_empty() {
if let Some(reason) = wmi_failure {
return Err(Error::QueryFailed(format!("disk enumeration: {reason}")));
}
return Err(Error::NotFound);
}
Ok(disks)
}
/// Enhanced disk monitor with caching
pub struct WindowsDiskMonitor {
disks: HashMap<String, WindowsDisk>,
}
impl WindowsDiskMonitor {
pub fn new() -> Result<Self, Error> {
let disks_vec = enumerate()?;
let mut disks = HashMap::new();
for disk in disks_vec.iter() {
// The physical index is the number in the name. The position in the
// list is not: a drive missing from enumeration shifts every later one.
let Some(disk_index) = disk
.name()
.strip_prefix("PhysicalDrive")
.and_then(|n| n.parse::<u32>().ok())
else {
continue;
};
disks.insert(
disk.name().to_string(),
WindowsDisk {
name: disk.name().to_string(),
device_path: disk.device_path(),
disk_type: disk.disk_type(),
model: None,
serial: None,
size: None,
disk_index,
interface_type: None,
},
);
}
Ok(Self { disks })
}
pub fn disks(&self) -> Vec<&WindowsDisk> {
self.disks.values().collect()
}
pub fn disk_by_name(&self, name: &str) -> Option<&WindowsDisk> {
self.disks.get(name)
}
}
impl Default for WindowsDiskMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
disks: HashMap::new(),
})
}
}
/// Grades the sectors at risk on an ATA drive. `None` is a counter that was not
/// read. A non-zero counter is a reading that says something is wrong; two zero
/// readings are a clean drive; a zero beside an unread counter is half a
/// question, and is not graded Healthy.
fn grade_at_risk_sectors(pending: Option<u64>, uncorrectable: Option<u64>) -> DiskHealth {
if matches!(pending, Some(n) if n > 0) || matches!(uncorrectable, Some(n) if n > 0) {
return DiskHealth::Warning;
}
match (pending, uncorrectable) {
(Some(_), Some(_)) => DiskHealth::Healthy,
_ => DiskHealth::Unknown,
}
}
#[cfg(test)]
mod kind_tests {
use super::*;
/// The kind is what Windows reports, and an unreported medium stays
/// unknown -- not the NVMe SSD the old heuristic defaulted to.
#[test]
fn disk_kind_comes_from_bus_and_media() {
assert_eq!(
kind_from_bus_and_media(Some(17), Some(4)),
DiskType::NvmeSsd
);
assert_eq!(
kind_from_bus_and_media(Some(11), Some(3)),
DiskType::SataHdd
);
assert_eq!(
kind_from_bus_and_media(Some(11), Some(4)),
DiskType::SataSsd
);
assert_eq!(
kind_from_bus_and_media(Some(11), Some(0)),
DiskType::Unknown
);
assert_eq!(kind_from_bus_and_media(Some(8), Some(3)), DiskType::Scsi);
assert_eq!(kind_from_bus_and_media(Some(7), Some(0)), DiskType::Usb);
assert_eq!(kind_from_bus_and_media(None, None), DiskType::Unknown);
}
}
#[cfg(test)]
mod sector_grade_tests {
use super::*;
/// A counter nobody read is not a clean one, and a clean reading beside it
/// is not a whole picture. Only both counters read zero grade Healthy.
#[test]
fn unread_sector_counters_are_not_graded_healthy() {
assert_eq!(grade_at_risk_sectors(Some(0), Some(0)), DiskHealth::Healthy);
assert_eq!(grade_at_risk_sectors(None, None), DiskHealth::Unknown);
assert_eq!(grade_at_risk_sectors(Some(0), None), DiskHealth::Unknown);
assert_eq!(grade_at_risk_sectors(None, Some(0)), DiskHealth::Unknown);
assert_eq!(grade_at_risk_sectors(None, Some(3)), DiskHealth::Warning);
assert_eq!(grade_at_risk_sectors(Some(1), None), DiskHealth::Warning);
}
}