vck-windrv 0.0.3

Windows kernel-mode driver framework for VolumeCrypt-Kit
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
// SPDX-FileCopyrightText: 2026 JC-Lab <joseph@jc-lab.net>
//
// SPDX-License-Identifier: Apache-2.0

//! Volume filter device attach/detach.
//!
//! Creates an unnamed filter device object and attaches it to a volume's
//! storage device stack. For NTFS I/O to pass through the filter (required for
//! transparent encryption), the filter must be placed BELOW the filesystem (NTFS)
//! and ABOVE the raw partition device — i.e.:
//!
//!   NTFS VCB
//!     └── [Our Filter]   ← must be here
//!          └── Raw Volume / Partition
//!
//! The only reliable way to achieve this without lock/dismount is via
//! `IoRegisterFsRegistrationChange` (see `register_fs_change` below): the
//! kernel calls our notification before the FSD finishes mounting, allowing us
//! to attach to the raw partition device BEFORE NTFS places its VCB above it.
//!
//! `attach_to_device` is the low-level primitive used by both the notification
//! path and the manual IOCTL path; the IOCTL path (`handle_jvck_attach`) calls
//! it before the FSD has had a chance to attach to the raw device by supplying
//! the raw partition device path directly.

use alloc::sync::Arc;
use core::ptr::null_mut;

use vck_common::{VckError, VckResult};
use wdk_sys::{
    ntddk::{
        IoAttachDeviceToDeviceStackSafe, IoCreateDevice, IoDeleteDevice, IoDetachDevice,
        IoGetDeviceObjectPointer, ObfDereferenceObject,
    },
    DEVICE_OBJECT, DO_BUFFERED_IO, DO_DEVICE_INITIALIZING, DO_DIRECT_IO, DO_POWER_PAGABLE,
    DRIVER_OBJECT, FILE_DEVICE_DISK, FILE_READ_DATA, FILE_WRITE_DATA, PDEVICE_OBJECT, PFILE_OBJECT,
};

use crate::{
    device::{DeviceExtension, DEVICE_EXTENSION_SIZE, DEVICE_KIND_FILTER},
    nt::{nt_success, UnicodeString},
    registry::AttachedVolume,
};

/// Create a filter device and attach it above the volume named by
/// `target_nt_path` (e.g. `\??\D:`). On success the returned device object's
/// extension owns a reference to `volume` (released by [`detach_filter`]).
/// Returns `(filter_device_object, lower_device_object)`.
///
/// The filter is attached to the CURRENT top of the device stack. If the FSD
/// (e.g. NTFS) has already mounted on the volume, the filter will land ABOVE
/// the FSD. For correct transparent encryption the caller should ensure the
/// filter is attached below the FSD (via the `IoRegisterFsRegistrationChange`
/// path) or accept size-interception-only semantics.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn attach_filter(
    driver: *mut DRIVER_OBJECT,
    target_nt_path: &str,
    volume: Arc<AttachedVolume>,
) -> VckResult<(PDEVICE_OBJECT, PDEVICE_OBJECT)> {
    let mut filter_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoCreateDevice(
            driver,
            DEVICE_EXTENSION_SIZE,
            null_mut(), // unnamed
            FILE_DEVICE_DISK,
            0,
            0, // Exclusive = FALSE
            &mut filter_do,
        )
    };
    if !nt_success(status) {
        return Err(VckError::Io("IoCreateDevice(filter) failed".into()));
    }

    // Resolve the target volume device (top of its stack right now).
    let name = UnicodeString::new(target_nt_path);
    let mut file_obj: PFILE_OBJECT = null_mut();
    let mut target_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoGetDeviceObjectPointer(
            name.as_ptr(),
            FILE_READ_DATA | FILE_WRITE_DATA,
            &mut file_obj,
            &mut target_do,
        )
    };
    if !nt_success(status) {
        unsafe { IoDeleteDevice(filter_do) };
        return Err(VckError::Io(
            "IoGetDeviceObjectPointer(target) failed".into(),
        ));
    }

    let mut lower: PDEVICE_OBJECT = null_mut();
    let status = unsafe { IoAttachDeviceToDeviceStackSafe(filter_do, target_do, &mut lower) };
    unsafe { ObfDereferenceObject(file_obj.cast()) };
    if !nt_success(status) || lower.is_null() {
        unsafe { IoDeleteDevice(filter_do) };
        return Err(VckError::Io(
            "IoAttachDeviceToDeviceStackSafe failed".into(),
        ));
    }

    unsafe {
        let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
        (*ext).kind = DEVICE_KIND_FILTER;
        (*ext).lower_device = lower;
        (*ext).volume = Arc::into_raw(volume.clone());
        (*ext).vthread = null_mut();
        crate::filter::volume_thread::bind(filter_do, volume);

        // Inherit the relevant flags / type from the device below us.
        (*filter_do).Flags |= (*lower).Flags & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE);
        (*filter_do).DeviceType = (*lower).DeviceType;
        (*filter_do).Characteristics = (*lower).Characteristics;
        (*filter_do).Flags &= !DO_DEVICE_INITIALIZING;
    }

    crate::vck_log!(
        "filter: attached filter={:p} lower={:p} (NOTE: may be above FSD if FSD already mounted)",
        filter_do,
        lower
    );
    Ok((filter_do, lower))
}

/// Create and attach a filter device object without binding it to a volume yet.
///
/// Used when the volume metadata needs to be read AFTER the filter is in place
/// (e.g. the volume is dismounted so `ZwCreateFile` fails, but
/// `IoAttachDeviceToDeviceStackSafe` still works via `IoGetDeviceObjectPointer`).
/// Caller must call [`filter_bind_volume`] to complete setup once the
/// `AttachedVolume` is built. If setup fails, call [`detach_filter`] to clean up.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn attach_filter_unbound(
    driver: *mut DRIVER_OBJECT,
    target_nt_path: &str,
) -> VckResult<(PDEVICE_OBJECT, PDEVICE_OBJECT)> {
    let mut filter_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoCreateDevice(
            driver,
            DEVICE_EXTENSION_SIZE,
            null_mut(),
            FILE_DEVICE_DISK,
            0,
            0,
            &mut filter_do,
        )
    };
    if !nt_success(status) {
        return Err(VckError::Io("IoCreateDevice(filter) failed".into()));
    }

    let name = UnicodeString::new(target_nt_path);
    let mut file_obj: PFILE_OBJECT = null_mut();
    let mut target_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoGetDeviceObjectPointer(
            name.as_ptr(),
            FILE_READ_DATA | FILE_WRITE_DATA,
            &mut file_obj,
            &mut target_do,
        )
    };
    if !nt_success(status) {
        unsafe { IoDeleteDevice(filter_do) };
        return Err(VckError::Io(
            "IoGetDeviceObjectPointer(unbound) failed".into(),
        ));
    }

    let mut lower: PDEVICE_OBJECT = null_mut();
    let status = unsafe { IoAttachDeviceToDeviceStackSafe(filter_do, target_do, &mut lower) };
    unsafe { ObfDereferenceObject(file_obj.cast()) };
    if !nt_success(status) || lower.is_null() {
        unsafe { IoDeleteDevice(filter_do) };
        return Err(VckError::Io(
            "IoAttachDeviceToDeviceStackSafe(unbound) failed".into(),
        ));
    }

    unsafe {
        // Mark as filter but leave volume pointer null until filter_bind_volume.
        let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
        (*ext).kind = DEVICE_KIND_FILTER;
        (*ext).lower_device = lower;
        (*ext).volume = null_mut();
        (*ext).vthread = null_mut();

        (*filter_do).Flags |= (*lower).Flags & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE);
        (*filter_do).DeviceType = (*lower).DeviceType;
        (*filter_do).Characteristics = (*lower).Characteristics;
        (*filter_do).Flags &= !DO_DEVICE_INITIALIZING;
    }
    Ok((filter_do, lower))
}

/// Like [`attach_filter_unbound`] but takes a device object pointer directly
/// instead of resolving one via `IoGetDeviceObjectPointer`. Use this when the
/// device object is already known (e.g. obtained from an open file handle) and
/// `IoGetDeviceObjectPointer` would fail (e.g. after the filesystem dismounts).
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn attach_filter_to_raw_device(
    driver: *mut DRIVER_OBJECT,
    target_do: PDEVICE_OBJECT,
) -> VckResult<(PDEVICE_OBJECT, PDEVICE_OBJECT)> {
    let mut filter_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoCreateDevice(
            driver,
            DEVICE_EXTENSION_SIZE,
            null_mut(),
            FILE_DEVICE_DISK,
            0,
            0,
            &mut filter_do,
        )
    };
    if !nt_success(status) {
        return Err(VckError::Io("IoCreateDevice(filter-raw) failed".into()));
    }

    let mut lower: PDEVICE_OBJECT = null_mut();
    let status = unsafe { IoAttachDeviceToDeviceStackSafe(filter_do, target_do, &mut lower) };
    if !nt_success(status) || lower.is_null() {
        unsafe { IoDeleteDevice(filter_do) };
        return Err(VckError::Io(
            "IoAttachDeviceToDeviceStackSafe(raw) failed".into(),
        ));
    }

    unsafe {
        let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
        (*ext).kind = DEVICE_KIND_FILTER;
        (*ext).lower_device = lower;
        (*ext).volume = null_mut(); // bound later via filter_bind_volume
        (*ext).vthread = null_mut();

        (*filter_do).Flags |= (*lower).Flags & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE);
        (*filter_do).DeviceType = (*lower).DeviceType;
        (*filter_do).Characteristics = (*lower).Characteristics;
        (*filter_do).Flags &= !DO_DEVICE_INITIALIZING;
    }
    Ok((filter_do, lower))
}

/// Replace the `AttachedVolume` bound to an existing filter device. The old
/// volume Arc is properly dropped. Used by `handle_jvck_attach` to swap the
/// provisional (PREPARE-phase) volume for the complete (FVEK-ready) volume.
///
/// # Safety
/// `filter_do` must be a filter device object with a non-null `volume` pointer
/// set by a previous `filter_bind_volume` call.
pub unsafe fn filter_rebind_volume(filter_do: PDEVICE_OBJECT, volume: Arc<AttachedVolume>) {
    let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
    let old_ptr = (*ext).volume;
    if !old_ptr.is_null() {
        drop(Arc::from_raw(old_ptr));
    }
    (*ext).volume = Arc::into_raw(volume.clone());
    // Start the volume thread (if cipher now present) or swap its current volume.
    crate::filter::volume_thread::bind(filter_do, volume);
}

/// Bind an `AttachedVolume` to a previously unbound filter device (see
/// [`attach_filter_unbound`]).
///
/// # Safety
/// `filter_do` must be one returned by `attach_filter_unbound` that has not yet
/// been bound or detached.
pub unsafe fn filter_bind_volume(filter_do: PDEVICE_OBJECT, volume: Arc<AttachedVolume>) {
    let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
    (*ext).volume = Arc::into_raw(volume.clone());
    // Start the volume thread if this volume carries a cipher.
    crate::filter::volume_thread::bind(filter_do, volume);
}

/// Attach our filter to a specific device object (called from the
/// `IoRegisterFsRegistrationChange` notification path where we know the raw
/// partition device and can insert BELOW the FSD before it mounts).
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn attach_filter_to_device(
    driver: *mut DRIVER_OBJECT,
    target_do: PDEVICE_OBJECT,
    volume: Arc<AttachedVolume>,
) -> VckResult<(PDEVICE_OBJECT, PDEVICE_OBJECT)> {
    let mut filter_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoCreateDevice(
            driver,
            DEVICE_EXTENSION_SIZE,
            null_mut(),
            FILE_DEVICE_DISK,
            0,
            0,
            &mut filter_do,
        )
    };
    if !nt_success(status) {
        return Err(VckError::Io("IoCreateDevice(filter) failed".into()));
    }

    let mut lower: PDEVICE_OBJECT = null_mut();
    let status = unsafe { IoAttachDeviceToDeviceStackSafe(filter_do, target_do, &mut lower) };
    if !nt_success(status) || lower.is_null() {
        unsafe { IoDeleteDevice(filter_do) };
        return Err(VckError::Io(
            "IoAttachDeviceToDeviceStackSafe(device) failed".into(),
        ));
    }

    unsafe {
        let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
        (*ext).kind = DEVICE_KIND_FILTER;
        (*ext).lower_device = lower;
        (*ext).volume = Arc::into_raw(volume.clone());
        (*ext).vthread = null_mut();
        crate::filter::volume_thread::bind(filter_do, volume);

        (*filter_do).Flags |= (*lower).Flags & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE);
        (*filter_do).DeviceType = (*lower).DeviceType;
        (*filter_do).Characteristics = (*lower).Characteristics;
        (*filter_do).Flags &= !DO_DEVICE_INITIALIZING;
    }

    Ok((filter_do, lower))
}

/// Unbind the cipher/volume from a filter and return it to **pass-through**
/// (the AddDevice unbound state), but KEEP the filter device attached to the
/// stack (and its PDO→filter map entry valid). Used by user-initiated detach
/// (`data-volume detach` = dismount) so the volume can be re-attached later
/// without a reboot.
///
/// Contrast with [`detach_filter`], which fully tears the filter down
/// (IoDetachDevice + IoDeleteDevice) — reserved for driver unload / shutdown /
/// half-attach error cleanup, where the device must actually go away.
///
/// # Safety
/// `filter_do` must be a filter device object owned by this driver.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn unbind_filter(filter_do: PDEVICE_OBJECT) {
    if filter_do.is_null() {
        return;
    }
    unsafe {
        let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
        // Stop the per-volume IO+sweep thread FIRST so no thread touches the
        // lower device or the volume Arc after this point.
        if !(*ext).vthread.is_null() {
            let vt = alloc::boxed::Box::from_raw((*ext).vthread);
            vt.stop();
            (*ext).vthread = null_mut();
            // `vt` dropped here: drains any leftover IRPs + drops its volume Arc.
        }
        // Release the bound volume Arc -> filter becomes pass-through. The filter
        // device and its `lower_device` attachment STAY, so a later attach can
        // re-bind via `filter_bind_volume` (the PDO map still points here).
        if !(*ext).volume.is_null() {
            drop(Arc::from_raw((*ext).volume));
            (*ext).volume = null_mut();
        }
    }
}

/// Detach and delete a filter device, releasing the `Arc<AttachedVolume>` held
/// in its extension.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn detach_filter(filter_do: PDEVICE_OBJECT) {
    if filter_do.is_null() {
        return;
    }
    unsafe {
        let ext = (*filter_do).DeviceExtension as *mut DeviceExtension;
        // Stop the per-volume IO+sweep thread FIRST so no thread touches the
        // lower device or the volume Arc after this point.
        if !(*ext).vthread.is_null() {
            let vt = alloc::boxed::Box::from_raw((*ext).vthread);
            vt.stop();
            (*ext).vthread = null_mut();
            // `vt` dropped here: drains any leftover IRPs + drops its volume Arc.
        }
        if !(*ext).lower_device.is_null() {
            IoDetachDevice((*ext).lower_device);
            (*ext).lower_device = null_mut();
        }
        if !(*ext).volume.is_null() {
            drop(Arc::from_raw((*ext).volume));
            (*ext).volume = null_mut();
        }
        IoDeleteDevice(filter_do);
    }
}

/// Find our filter for the volume at `nt_path` using the PDO → filter map
/// built by add_device. Falls back to stack-walk for compatibility.
///
/// When AddDevice fires before NTFS mounts, the filter is at the correct
/// position. NTFS uses the VPB mechanism (not IoAttachDeviceToDeviceStackSafe)
/// for mounting, so stack-walking via IoGetLowerDeviceObject from the NTFS VCB
/// does NOT reach our filter. The PDO map approach is reliable.
/// Find the filter for the volume at `nt_path` using:
/// 1. Name-based PDO map lookup (primary — Volume class PDO ≠ namespace device object)
/// 2. Device pointer lookup in PDO map (fallback)
/// 3. Device stack walk (last resort)
pub fn find_filter_for_volume<F, FN>(
    nt_path: &str,
    lookup_fn: F,
    name_lookup_fn: FN,
) -> Option<(PDEVICE_OBJECT, PDEVICE_OBJECT)>
where
    F: Fn(PDEVICE_OBJECT) -> Option<(PDEVICE_OBJECT, PDEVICE_OBJECT)>,
    FN: Fn(&str) -> Option<(PDEVICE_OBJECT, PDEVICE_OBJECT)>,
{
    use wdk_sys::ntddk::{IoGetDeviceAttachmentBaseRef, ObfDereferenceObject};
    use wdk_sys::{FILE_READ_DATA, PFILE_OBJECT};

    let name = UnicodeString::new(nt_path);
    let mut file_obj: PFILE_OBJECT = null_mut();
    let mut vol_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoGetDeviceObjectPointer(name.as_ptr(), FILE_READ_DATA, &mut file_obj, &mut vol_do)
    };
    if !nt_success(status) || vol_do.is_null() {
        return None;
    }
    unsafe { ObfDereferenceObject(file_obj.cast()) };

    // Get the BASE device of the attachment stack for the volume. This is the
    // device object that was the PDO when AddDevice was called.
    let base_dev = unsafe { IoGetDeviceAttachmentBaseRef(vol_do) };
    crate::vck_log!(
        "find_filter: vol_do={:p} base_dev={:p} nt_path={}",
        vol_do,
        base_dev,
        nt_path
    );
    // Primary: name-based lookup using the actual device object name.
    // vol_do might be e.g. \Device\HarddiskVolume5 even if nt_path=\??\D:.
    // Query the name of vol_do directly.
    let dev_name = unsafe {
        use wdk_sys::ntddk::ObQueryNameString;
        let mut buf = [0u8; 256];
        let mut ret_len: u32 = 0;
        let st = ObQueryNameString(vol_do.cast(), buf.as_mut_ptr().cast(), 256, &mut ret_len);
        if st >= 0 {
            let name_len = u16::from_le_bytes([buf[0], buf[1]]) as usize / 2;
            let name_ptr = usize::from_le_bytes(buf[8..16].try_into().unwrap_or([0; 8]));
            if name_len > 0 && name_ptr != 0 {
                let chars = core::slice::from_raw_parts(name_ptr as *const u16, name_len.min(64));
                let mut s = alloc::string::String::new();
                for &c in chars {
                    if (0x20..0x7F).contains(&c) {
                        s.push(c as u8 as char);
                    } else {
                        s.push('?');
                    }
                }
                s
            } else {
                alloc::string::String::new()
            }
        } else {
            alloc::string::String::new()
        }
    };
    crate::vck_log!(
        "find_filter: vol_do_name='{}' nt_path='{}'",
        dev_name,
        nt_path
    );
    if !dev_name.is_empty() {
        if let Some(result) = name_lookup_fn(&dev_name) {
            crate::vck_log!("find_filter: found via vol_do_name={}", dev_name);
            return Some(result);
        }
    }
    // Also try nt_path directly.
    if let Some(result) = name_lookup_fn(nt_path) {
        crate::vck_log!("find_filter: found via nt_path={}", nt_path);
        return Some(result);
    }

    // Fallback: device pointer lookup
    if !base_dev.is_null() {
        unsafe { ObfDereferenceObject(base_dev.cast()) };
        if let Some(result) = lookup_fn(base_dev) {
            crate::vck_log!("find_filter: found via base_dev={:p}", base_dev);
            return Some(result);
        }
    }
    if let Some(result) = lookup_fn(vol_do) {
        crate::vck_log!("find_filter: found via vol_do={:p}", vol_do);
        return Some(result);
    }
    let top_dev = unsafe { wdk_sys::ntddk::IoGetAttachedDeviceReference(vol_do) };
    if !top_dev.is_null() {
        let result = lookup_fn(top_dev);
        unsafe { wdk_sys::ntddk::ObfDereferenceObject(top_dev.cast()) };
        if let Some(r) = result {
            crate::vck_log!("find_filter: found via top_dev={:p}", top_dev);
            return Some(r);
        }
    }

    // Final fallback: walk the attachment stack and match our filter device by
    // its extension kind. Handles path forms (e.g. `\??\Volume{GUID}`) whose
    // `IoGetDeviceObjectPointer` returns an unnamed upper device that no
    // name/pointer lookup matches, but which still sits in the same stack as our
    // AddDevice-attached filter — e.g. the OS volume queried by its volume GUID
    // instead of by its PDO name (`\Device\HarddiskVolumeN`).
    if let Some(result) = find_our_filter_in_stack(nt_path) {
        crate::vck_log!("find_filter: found via stack walk for {}", nt_path);
        return Some(result);
    }

    crate::vck_log!("find_filter: not found for {}", nt_path);
    None
}

/// Walk the device stack from the top of `nt_path` downward and return the
/// first filter device object that belongs to this driver, along with its
/// `lower_device`.
///
/// After `AddDevice` fires and NTFS mounts, the stack looks like:
///   NTFS VCB → [Our Filter] → Raw Partition/Volume
///
/// `IoGetDeviceObjectPointer(nt_path)` returns the NTFS VCB.
/// `IoGetLowerDeviceObject(NTFS_VCB)` returns Our Filter (since NTFS attached
/// above it). We verify by checking `DeviceExtension->kind == DEVICE_KIND_FILTER`.
///
/// Returns `Some((filter_do, lower_do))` if found, `None` otherwise.
pub fn find_our_filter_in_stack(nt_path: &str) -> Option<(PDEVICE_OBJECT, PDEVICE_OBJECT)> {
    use wdk_sys::ntddk::{IoGetLowerDeviceObject, ObfDereferenceObject};
    use wdk_sys::{FILE_READ_DATA, PFILE_OBJECT};

    use wdk_sys::ntddk::IoGetAttachedDeviceReference;

    let name = UnicodeString::new(nt_path);
    let mut file_obj: PFILE_OBJECT = null_mut();
    let mut vol_do: PDEVICE_OBJECT = null_mut();
    let status = unsafe {
        IoGetDeviceObjectPointer(name.as_ptr(), FILE_READ_DATA, &mut file_obj, &mut vol_do)
    };
    if !nt_success(status) || vol_do.is_null() {
        return None;
    }
    // Release the file object reference — we only need the device pointer.
    unsafe { ObfDereferenceObject(file_obj.cast()) };

    // IoGetDeviceObjectPointer returns the device the path NAME maps to (e.g.
    // HarddiskVolume5), which is NOT necessarily the stack top. Our filter
    // may be ABOVE it. Use IoGetAttachedDeviceReference to get the true top,
    // then walk downward to find our filter.
    let top_do = unsafe { IoGetAttachedDeviceReference(vol_do) };
    if top_do.is_null() {
        return None;
    }

    // Walk the attachment chain (top → bottom).
    unsafe {
        // top_do is already referenced by IoGetAttachedDeviceReference.
        let mut current = top_do;
        let mut depth = 0u32;
        loop {
            let ext = (*current).DeviceExtension as *const DeviceExtension;
            let kind = if !ext.is_null() {
                (*ext).kind
            } else {
                0xFFFF_FFFF
            };
            crate::vck_log!(
                "find_filter[{}]: do={:p} ext_kind=0x{:08x}",
                depth,
                current,
                kind
            );
            if !ext.is_null() && (*ext).kind == DEVICE_KIND_FILTER {
                let lower = (*ext).lower_device;
                ObfDereferenceObject(current.cast());
                crate::vck_log!(
                    "find_filter: found filter_do={:p} lower={:p}",
                    current,
                    lower
                );
                return Some((current, lower));
            }
            // Move to the next device below.
            let next = IoGetLowerDeviceObject(current);
            ObfDereferenceObject(current.cast());
            if next.is_null() {
                crate::vck_log!("find_filter: reached base (depth={})", depth);
                break;
            }
            current = next;
            depth += 1;
            if depth > 12 {
                break;
            }
        }
    }
    None
}

// Type alias kept for callers that referenced the old name.
pub type FilterDevice = *mut DEVICE_OBJECT;