Diagnosing why driver unload fails

I have a virtual storport miniport. The HwStorFreeAdapterResources frees everything and there are no inverted calls. devcon is used to install/uninstall. But sometimes uninstalling does not unload the driver and a system restart is required. Other times it works. The outcome seems random and unpredictable. Is there a way to diagnose what is causing driver unload to fail?

I would try tracking handles and objects your driver is using. Driver Verifier on your driver might catch it. Also I would try Code Analysis compilation. In case those won’t help there are additional ways but this is as tier 1 triage.

Of course I always run verifier on very stringent settings; detects nothing. I am also pretty sure the driver frees all resources perfectly and consistently as I described. So what I really need to understand is for what reason Windows decided not to unload it. Right now all I have to go in is sometimes it does, sometimes it doesn’t. Are there any log files, events, something to trigger on in the debugger, anything like that? I understand this might be more difficult than a typical driver since storport is the one managing the device objects.

First thing I would do is check C:\windows\inf\setupapi.dev.log and see if there’s anything interesting there.

It seems that your device reference count is not zero. I would try to make memory bp to track ref count and see what increments and does not decrement. Also on the error case you can try use process explorer look for open handles for your device.

Here is the setupapi.dev.log output:

">>> [Delete Device - ROOT\SCSIADAPTER\0001]
">>> Section start 2019/10/29 20:24:20.473
" cmd: devcon remove root\memex
"! dvi: Setting needs reboot
"! dvi: Query-and-Remove failed: 0x13: CR_FAILURE.
"<<< Section end 2019/10/29 20:24:21.348
"<<< [Exit status: SUCCESS]