Search code examples
windowswinapidriverwdfplug-and-play

How to stop a Plug-and-Play filter driver on demand?


I am developing a filter driver under Windows. The driver is PnP-aware to receive device notifications and it also creates a control device to communicate with an accompanying usermode service via IOCTLs.

As far as I understand, driver's lifetime is controlled by PnP-manager. The driver is unloaded after processing next device notification given that by that time no device objects are owned by the driver.

What I need to do is to stop the driver on demand, not when the next device arrives/departures. So far I do not think that's the way it's supposed to work, on the other hand I do not see any logic that forbids unloading filter drivers on demand. I researched sending STOP control and I do not see how that can be handled in a PnP driver (works only for legacy drivers).

Right now I'm thinking of adding special IOCTL handler, that would close all device objects. But that's not enough, driver's lifetime is managed by PnP-manager so I need to somehow "bring attention" of the manager to my driver. Any help is appreciated!

If you are wondering, I need the driver to be stoppable so that deinstallation does not require a reboot.


Solution

  • WDM Filter driver always attach own device to device stack. after this some another device can attach yourself to this stack - so it will be attached to your device. after this driver already can not be unloaded at all.

    driver can be unloaded only if no more references to it DRIVER_OBJECT for this you need detach from device stack and destroy all your DEVICE_OBJECTs. only one correct way for WDM filter driver do this - when you handle IRP_MN_REMOVE_DEVICE - read Removing a Device in a Filter Driver or as alternative you can register FAST_IO_DISPATCH with FastIoDetachDevice in driver - as result FastIoDetachDevice will be called when will be called IoDeleteDevice for DeviceObject to which you attached (this is also during IRP_MN_REMOVE_DEVICE process). at this moment you need call IoDetachDevice and IoDeleteDevice - only after this your driver can be unloaded and PnP-manager auto do this if no more DeviceObjects or other references to your Driver.

    so only one option for unload WDM driver - full destroy device stack - not all stacks is can be stopped at runtime. but some can - by call CM_Request_Device_Eject - prepares a local device instance for safe removal, if the device is removable. If the device can be physically ejected, it will be.