I have trouble believing that we’re actually having this discussion in a group of what I assume are senior, experienced, kernel-mode developers.
OF COURSE it’s OK to release Spin Locks in an arbitrary order. As I say in class when I explain this (quoting Tony Mason, in fact) “Nobody has ever deadlocked as a result of a RELEASE operation.” The only constraint in Windows is the one that Mr. Roddy cited: You must keep the IRQLs straight. Duh.
OF COURSE it can be useful to do this. As I said previously, and as Mr. Roddy clarified, if you acquire Lock1 and then Lock2, and if Lock1 is HOT, and you need to do significantly more processing that requires just Lock2… you should absolutely release Lock1 before you release Lock2. However…
HOWEVER, as I also said previously and to the point Mr M M noted, this code tends to “look” wrong when you read it casually. So, there’s a maintenance cost involved. You have an obligation to “comment the shit out of this code” so that those who come after you understand what you’re doing.
So, in general, it’s easier to “go with the flow” and release locks in the inverse order in which they were acquired. In fact, the WDF Spin Lock functions require this.
And, let’s state for the record: There is absolutely no requirement to avoid the use of WDM function calls in a general-purpose KMDF driver. C’mon, people! How many of you call ExAllocatePool instead of WdfMemoryCreate? Get a block of device memory, and want to map it into kernel virtual address space? What do you call from your KMDF driver? You call MmMapIoSpace. There isn’t a WDF equivalent. In fact, one of the primary the ADVANTAGES of having access to WDM functions, is that the WDF team doesn’t have to create meaningless abstractions for every single WDM function that could be useful. Are we seriously supposed to live without reader/writer locks, and just use WDFSPINLOCK and WDFWAITLOCK? OF COURSE NOT.
Let’s first acknowledge that “strict alternation” is a specific algorithm in CS. And, frankly, I have no idea how it applies here. Spin Locks, by the very nature, achieve “strict alternation.”
Let’s further state that given the above interpretation of “strict alternation”, we could never have nested spin locks This is, of course, blatantly incorrect.
So, either our interpretation of “strict alternation” is incorrect, or the cited rule is incorrect. To me, it doesn’t really matter.
Finally, let me again state that if there’s anything in the docs, or in the static analysis tools, that requires you ONLY release spin locks in the inverse order in which they were acquired, that documentation or tool is WRONG. Plain and simple. This has never, not ever, been a requirement in Windows (because the idea of *requiring* the locks to be released in any given order is plainly silly).
Peter
OSR
@OSRDrivers