August 2004 - Posts
Here's an e-mail from Jamey Kirby, posted to NTDEV, on how to keep Explorer from showning a drive. I love it!
Use numbers for the drive letters. You can access the drive via
3:\yadayadayada\yadayadayada. You can even park a CMD prompt on it, but
explorer and associated APIS will not enumerate them.
Jamey
Jamey gets a Gold Star(TM) for pointing this out.
Somehow, I managed to catch a cold this weekend, and can already feel the NyQuil starting to kick in. If this post seems, well, a little druk -- that's why. The good news is that I'm having fun writing it!
Today I think I'll talk a bit about the kernel-mode stack. There are a few intersting issues in play here for kernel-mode developers.
The kernel stack is small. It is usually 3 pages or so, which means 12k on X86. Believe it or not, this is bigger than it used to be - it was 8K in NT4 and previous. My guess is that Microsoft increased the kernel stack size on Windows 2000 because of the deeper layering of drivers brought about by WDM (more on that in a sec). If you use more than 12K of stack, you'll hit a guard page, which probably means an instant double-fault bluescreen. The reason that this is a double-fault is that the CPU tries to build an exception record on the stack for transfer to the exception handler, and when it tries to push the record on to the overflowed stack, it faults again. The only thing the kernel can do at that point is die a painful death. It's worth noting that almost every time I've had a duoble-fault bluescreen, it's been a stack fault.
Why is the stack so small? Well, this was an early design decision made by the kernel team. First off, kernel stacks are generally not pageable. That means that you're gobbling up 12K of physical memory for each thread running in the system. You have to keep that stack sitting around forever, even if the thread is in user mode, until it exits. With the hundreds of threads in systems today, that memory starts to add up fast. Additionally, because kernel code can execute at raised IRQL, kernel stacks cannot take page faults on access. That means that the traditional way of automatically growing the stack cannot be implemented in the kernel. Because the OS has to just pick an amount of memory for the stack at runtime, and because stack memory is a scarce resource, 12k was the compromise the kernel team landed on.
This means a few things: first, you need to be conservative with local variables. No more 64K arrays on the stack, for one thing. Be aware of the fact that you probably exist within a driver stack, and the drivers above and below you would be greatful for some stack space that they could use for themselves, thank you very much. In addition, you shouldn't ever use recursion in your driver, unless You Know What You Are Doing. Most recursive algorithms can be expressed in iterative implementations without sacrificing too much. I know your search only goes log(n) levels deep, but don't make me stress about whether or not it's ever going to exhaust the available stack. Finally, avoid architectures with lots of deeply-nested functions. This isn't an excuse to practice bad design, but it's an encouragement to keep things relatively flatter than perhaps you otherwise would have.
Going back to the layering thing for a second, this is an area with which filter drivers often have a lot of trouble. There have been versions of popular antivirus scanners that are implemented as filter drivers, that simply cannot be installed on systems with any other filesystem filter drivers. They just use up too much stack, so stack faults are common. Don't be a Bad Filter - be conservative of stack space, and remember that users will associate any bluescreens with your driver if it's the last driver they instaled.
One final note: thre are a couple of system-supplied functions that allow you to use the stack more carefully. IoGetStackLimits() will let you check on the lower and upper bounds of the stack; IoGetInitialStack() will give you back the base address of the thread's stack; and IoGetRemainingStackSize() can be called to find out how many bytes of stack are left. These functions should be used whenever a design contomplates recursion, whenever you are passed an address on the kernel stack, or in general, whenever you're trying to hunt down a stack overflow bug.
Good news: I have finally managed to procure a real URL for this blog:
www.kernelmustard.com, active as of this morning. I'm very excited - I was getting tired of spelling out "msmvps.com" for people. You'd be surprised how easy it is to screw that up. Anyway, tell your friends, tell your colleagues, tell your co-workers - kernelmustard.com is ready for prime time!
Raymond Chen had a really interesting article on The Old New Thing today about alignment on 64-bit platforms. Worth a read if you're not used to that sort of thing. I actually posted a little preview of a marshalling discussion as well, which is relevant to kernel-mode people.
Continuing vaguely along the theme from yesterday, I thought I'd plug a book that I refer to often when I have to work on Actual Hardware:
Developing Windows NT Device Drivers: A Programmer's Handbook
by Edward N. Dekker, Joseph M. Newcomer
Addison-Wesley Publishing Co.; ISBN: 0201695901
This is an oldie but a goodie. It's written for Windows NT 4.0, but it's still quite relevant in a couple of ways. In particular, it has some of the best hardware interfacing material I've ever encountered. Some of it is old now (i.e. the Hal calls, the DMA calls, etc.), but the concepts are there, and that's what's important. Also, Ed Dekker is a walking repository of Bad Hardware Stories, some of which come through in the book.
It's not current at all when it comes to things like PnP and power management, but the rest of the concepts are still just about right-on. When you read it in the right light, it's a valuable resource. It's hardbound and printed on nice paper, with a great index - all features that make it actually usable for a practicing programmer.
Anyway, next time you feel the urge to expand your brain, put on some ben folds music, grab Developing Windows NT Device Drivers, and reminisce about the time you got your new Pentium Pro server with 48MB RAM and installed NT4 for the first time. :-)
There are a lot of basic questions asked in the various driver development
forums that basically reduce to "how should I go about developing a driver?".
Every so often, I'll post a quick discussion of one of the tools I use every
day to do driver development. Try though they might, Microsoft doesn't exactly
hammer you over the head with information like this - a lot of this know-how
really just comes from doing the job.
At the risk of starting too basic, when you sit down to build a driver, the
first tool will need is the Windows Driver Development Kit (DDK). The DDK has
changed a lot over the years, but the last couple of releases have finally
started to settle down from a consistency standpoint. The current released DDK
is the Windows Server 2003 DDK, which represents build 3790 of the OS. It also
includes full development environments for Windows XP and Windows 2000. The
DDK is (almost) free from Microsoft - go to WHDC for more information on how to
get it.
Installation of the DDK takes forever. I'll never understand why these things
take sooooo long to uncompress and copy files, but perhaps I'm just a fundamentally
impatient person. Yep, that's it. :) At any rate, do yourself a favor and install
absolutely everything in the DDK. The whole mess - all of the build environments,
all of the tools, all of the samples, all of the docs. There are a couple of reasons
for this: first, you need to have the older build environments if you're planning on
releaseing drivers for the older platforms. The "wnet" build environment isn't always
backward-compatible with the "w2k" environment, so you need both. Unless, of course,
you are one of the lucky few that don't have to support older OSes. I'm jealous.
The other reason is that the sample code is by far the best documentation in the whole
kit. You might find yourself wondering about the semantics of a particular API in a
particular situation, and it really helps to be able to grep through all of the samples for
usage examples. I recently was in a situation where I needed to get a file handle back
from a file object, so I looked at all of the samples I could find for examples of
ObOpenObjectByPointer(). There were *none* in any of the files, prompting me to
redesign the driver to not need that API. I'm better off now, in that the overall architecture
wound up being much cleaner.
The DDK includes the latest authoritative documentation from Microsoft on how
to build drivers. It includes both "design guides" and reference material.
The design guides tend to read like technical documentation, so I'd still
recommend one of a few third-party driver development books. The reference
sections provide lots of detail about every public function provided for use by
driver writers. Most of this documentation (all?) is also available online at
OSR's website www.osronline.com, which
also has tons of other resources for driver writers. For those who didn't
know, OSR is the company that hosts the NTDEV and NTFSD mailing lists.
Wherever you get it from, I'd recommend becoming very familiar with the DDK
documentation.
Also included with the DDK is an entire build environment. All of the headers,
libraries, compiler tools, and support infrastructure needed to build your
driver are included. In particular, you don't need visual studio to compile
your drivers. In fact, using visual studio directly is not supported by
Microsoft for driver development. Mark Roddy (www.hollistech.com) has a script called
DDKBUILD that can be used to integrate the DDK with Visual Studio, but unless
you're really glued to its editor (and believe me, there are better ones), there's really no reason to use it.
Finally, don't miss the array of testing and troubleshooting tools present in
the DDK. There are so many of them, and some of them are so important to doing
the job correctly, that I'll post specifically about them another time.
Lots of people lately have been trying to do kernel mode file I/O, and running
into their share of problems in the process. I was just involved in a virtual
disk project that relied heavily on file I/O in the driver, so I thought I'd
post a quick tutorial while it's fresh in my mind.
First things first, try not to do this. Someone from Microsoft made the point
on NTDEV that you really don't want to have to do file I/O from kernel mode if
you can avoid it. There are security issues to consider (e.g. opening files
that the user wouldn't have had access to), and besides that, it's just
tricky.
With that said, if kmode file I/O is what you need to do, there are two basic
ways to do it: IRP-based and function-based. The easier of the two methods is
the function-based method, which employs the use of the Zw APIs for file manipulation.
Typically, files are opened with ZwCreateFile, read written with ZwReadFile and
ZwWriteFile, perhaps queried with ZwQueryInformationFile, and closed with ZwClose. This
method of file manipulation is geared toward using handles, so the standard warnings
about kernel-mode handle use apply. If you're running on a newer OS, specifying
OBJ_KERNEL_HANDLE in your OBJECT_ATTRIBUTES is always a good idea, as it makes the handle visible in all
contexts, while at the same time making it useless from user mode. Other than some
basic API differences (i.e. OBJECT_ATTRIBUTES structures, UNICODE_STRING strings, etc.),
this should feel quite a lot like Win32 access.
The one big caveat with function-based file I/O is that it cannot be done from any
IRQL > PASSIVE_LEVEL. This, in particular, includes APC_LEVEL. If you happen to be
sitting below a filesystem driver, for example, you may find yourself called back at
APC_LEVEL, and it is incorrect to use any of the Zw* file manipulation functions at that
IRQL. The reason has to do with I/O completion, which I'll get into another day. The
right thing to do here is to post the IO to a worker thread and wait for it to complete.
By the way - if you are using PAGED_CODE() to assert IRQL at the tops of your functions -
which you should be doing, by the way - remember that this will still pass even if you
are called back at APC_LEVEL, so you will have to either do an explicit IRQL check, or
better yet, just post all I/O off to a thread.
There is some debate as to whether you should simply use system work items or create a
dedicated worker thread. If you go the latter route, remember that there is a nontrivial
cost in setting up a new thread, and you have to be careful about how you kill it off -
you don't just want to terminate it, because it won't be cleaned up properly. Instead,
you should have an event that you set when you want the thread to exit.
The other method for doing file i/o is simply to build and send IRPs down to the filesystem
drivers themselves. This is less documented but not difficult to do. Instead of handles,
here you'll need the device object of the FSD and the file object representing the opened
file. In general, the idea is that you call IoBuildAsynchronousFsdRequest() with appropriate
parameters, and then attach the file object to the next stack location. If you don't do
that latter step, you'll see very odd crashes in the FSD. I hope to have an example of
this method posted within the week; check back if you're curious.
With either method, there are serious deadlock issues. Without going into detail, if you
believe you will re-enter the FSD (as in the case of a virtual disk driver backed by a
a file), your read (and write in particular) I/O needs to be noncached, or you'll get
into a difficult race with the cache manager.
Note to self... write these posts in a decent authoring tool and *then* put
them online. A reboot just ate my first attempt at an AMD64 article, with no
recovery file. Live and learn. Now you're stuck with the 3:00AM version,
stream-of-consciousness stizz. Enjoy ;)
Last year at Driver DevCon, the folks from AMD were out in force, armed with a
dizzying array of goodies emblazoned with their logo. What were they pushing,
you ask? The AMD64 architecture, of course, and well worth it too. AMD64 is a
64-bit extension of the x86 CPU architecture (from a programming interface
standpoint, anyway; I'm sure they're nothing alike in the core). For
those who haven't been keeping score at home, Intel introduced the IA-64
architecture a couple of years ago with the Itanium chip. Itanium is a cool
hunk of silicon, but it's fundamentally incompatible with x86. AMD saw their
chance to fill a big need that Intel didn't touch, and boy, did they do a good
job. It's one year after DevCon, and it's currently possible to head down to
the local computer parts store and pick up an Athlon 64 board/chip for cheap
and drop it into an otherwise-x86 system. Opteron-based servers are gaining
huge market share compared to Itanium sales, and (as attentive Kernel Mustard
readers know) I can say from first-hand knowledge how cool my dual-Opteron test
box is. When I first started looking into 64-bit chips, I was confused about a
few things. Here are some of the points I picked up along the way, so that you
might not have to duplicate my quest for enlightenment.
So, what is AMD64? In a nutshell*, this is the name of AMD's new x86-based
64-bit CPU architecture. It was designed from the ground up to be a totally
new internal architecture, but with a mandate to change as little as possible
about the programming interface. What changes they did make are completely
obvious and intuitive if you have any understanding of x86 CPU history - the
registers have been extended from 32-bit (i.e. eax) to 64-bit ("rax"; I guess
"r" stands for ReallyExtended or something :P), and a new opcode prefix has
been added that signals the chip that a 64-bit operand is on the way. Other
than that, plus a few new general-purpose registers and some other details that
Really Don't Matter, it looks and feels just like an x86. The long`addresses
look a little weird in the debugger, but you get used to them eventually. IDA
already disassembles AMD64 binaries perfectly.
One item up for discussion at the moment is what the final name of the
architecture will be in the Geek World. AMD is partial to AMD64, of course,
and frankly, I agree - Intel got to have IA-32 and IA-64, so I don't see why it
would hurt to have an architecture named after AMD. However, Microsoft seems
to be backing away from AMD64, and (if you can believe MSDN Subscriber
Downloads), looks to favor the shorter "x64" name. Another name that gets
thrown around occasionally is "x86-64". The reason this matters at all is that
Intel announced (nine months ago!) that it will also produce an x86-based
64-bit chip. Details are still sketchy, but as usual, ArsTechnica has tons of good information.
My money is on "x64" winning out eventually, as it sounds the most like "x86".
That won't stop me from referring to it as AMD64 for now, though. I'm a slow
learner.
So why go to AMD64? Well, for starters, it's really fast today. Forget this
emulation crap - these chips run native x86/win32 apps today, and fast.
This makes the upgrade path seamless, and at the prices these chips are selling
for, it's now officially foolish to invest in additional 32-bit chips. Add to
this the fact that you get all of the benefits of other 64-bit architectures,
and you have a killer proposition.
There are two main variants of AMD64 chips currently in production, both of
which are made by AMD. They are:
- Athlon 64 - This is the main consumer chip that AMD is marketing.
Variants of this chip run on everything from notebooks to low-end home boxes to
business-class workstations. These chips seem to be labeled with AMD's
traditional performance index (Athlon-64 3700, for example). They have
versions of the chip marketed to the Celeron crowd, and even a mobile processor
based on the 64-bit core. Not even Apple, my favorite hardware company, can
manage that with a 64-bit G5 yet, after a year of shipping G5 workstations.
- Opteron - This is the high-end chip, targeted at servers and
workstations. It uses the same core and same programming interface as the
Athlon chips, but includes higher-end features like lots of cache and the
ability to run multiprocessor setups. The Opteron chips connect to one another
on a motherboard via AMD's proprietary HyperTransport bus. As I understand it,
this bus is designed to work in conjunction with the Opterons' built-in memory
controllers to reduce memory bus contention. Opterons are numbered differently,
with the base Opteron 140 at the low end. The 142, 144, 146, and so on, are
faster versions of the 140, but all 1XX chips are designed for uniprocessor
implementations only. The 240 series is identical to the 140, but can be run
with a maximum of two CPUs on a motherboard. The numbering scheme continues on
upward as speed and maximum scalability increase.
More on the AMD64 architecture can be found at
WHDC, AMD,
and of course at ArsTechnica. There is also
a previous Kernel Mustard post about my adventures with my dual Opteron 240, below.
One parting shot - There are a couple of blogs worth pointing out, in case
you're not reading them yet. One is The
Old New Thing by Raymond Chen, which covers a wide variety of topics that I almost
always find interesting (well, at least until he starts pontificating about GUIs!).
Another is what promises to be an excellent new
blog by Thomas Divine. Thomas spends a lot of time dolling out free advice
on the PCAUSA NDIS discussion list (which I also post to on occasion), and is
the leading non-Microsoft source for network driver information.
Now, back to beating my head against the Hell Of Filesystem Locks. See you
tomorrow.
* It is worth pointing out that this is a lie; I have never really been able to say anything in a nutshell.
I've posted an article
here that I've been tinkering around with for a while. It's an adaptation of RFC1925 to computer programming. Feedback welcome, of course.
Hello world. As you may know, I live in Kansas, so I'm allowed to use a title like the one this post has. Deal with it. If you don't get the reference, you're really better off.
Bad news - I just got word today that the Driver DevCon conference (redundant?) has been pushed off until Spring 2005. Bad news, yo! That was the only conference I was actually looking forward to this year. Sigh.... too bad, I'll just have to wait another six months. This conference was supposed to be the first few days of November, but that is kind of an uncomfortable time anyway, as the US General Election is that Tuesday. Still, as one of my favorite bloggers would say... NO BUZZ!
So, how many of you have ever actually used a fast mutex in your kmode code? I'm sure most people know what they are if they have written any kmode code (if for no other reason than searching the Ex functions in the DDK index window always seems to land on the Fast Mutex stuff first). Well, I was going through some old vids of Microsoft driver development conferences the other day, and David Goebel (one of the almost-original NT guys) was talking about when and why to use them.
He made a point that I'd heard before but had never really taken to heart: you should use the least impactful synchronization primitive that you can get away with, for any given situation. We all know and love the KSPIN_LOCK, and I'm sure most device-type people get away with using only these locks. However, sometimes, using a spinlock is (to quote my grandfather) like killing an ant with a sledgehammer. There are other, more friendly locks that can be used, for the sake of yourself and for the rest of the system.
To review, the way a spinlock works is as follows: a memory region (the KSPIN_LOCK object you allocated and initialized) is "spun" on by the CPU using an atomic test-and-set operation until it finds that it now owns the lock. You could imagine pseudocode like this:
VOID AcquireLock(LONG *lock)
{
while(InterlockedExchange(lock, 1));
}
VOID ReleaseLock(LONG *lock)
{
*lock = 0;
}
(Five points to the first person to point out the weakness in this code). In addition to spinning on the processor, the kernel raises the IRQL to DISPATCH_LEVEL. In fact, on a uniprocessor kernel/hal, *all* that is done during KeAcquireSpinLock() is raising the IRQL to DISPATCH_LEVEL. If you don't see why this is, keep thining about the meaning of IRQL. Maybe I'll post about it another day.
Anyway, the point here is that grabbing (or trying to grab) a spinlock is not a nice thing to do to a computer. You might be ticking along just fine at PASSIVE_LEVEL (or maybe APC_LEVEL, or even IRQL 0.5 (ask me later)), and you decide you need a lock. Now, the fair thing to do would be to get a lock at low IRQL, so that when your quantum expires, you will get context-switched and someone else can do some work. If you're at DISPATCH_LEVEL, it'll never happen - you *own* the CPU (interrupts aside) until you drop your lock. How rude! But it's actually even worse than that: while you're at DISPATCH_LEVEL, you're not just blocking context-switching - you're actually blocking all DPCs on that chip. This is even worse, as the "standard model" (to borrow Walter Oney's phrase) for interrupt processing involves queuing a DPC to do the real work. That's right - you're keeping other device drivers from doing their jobs. If you do this often enough or long enough, users will notice, and they'll associate the degraded performance with the installation of your driver ("it was fine until I installed my WhizBang 3000!").
So what's a driver writer to do? To re-state David's general principle, you should use the least amount of lock necessary to synchronize with threads at the highest IRQL you can be called at. If you are synchronizing DPCs against each other, you're going to need spinlocks, because DPCs cannot block, they can only spin. That has the effect of requiring every locker to spin, whether or not they could have blocked. This is also the situation when synchroninzing with your ISR (via KeSynchronizeExecution()). However, if you are a software-only driver of some sort and you know you won't ever be trying to grab a lock at DISPATCH_LEVEL, you don't need spinlocks at all. In these cases, you have lots of other choices, but my two favorites are FAST_MUTEXes and ERESOURCES.
Fast Mutexes are manipulated via the ExInitializeFastMutex/ExAcquireFastMutex/ExFreeFastMutex functions. They are very fast and very small. Also, since they aren't dispatcher objects, the kernel doesn't have to grab the dispatcher lock to service you. This is a Good Thing(TM), as the dispatcher lock is right up there with the cancel lock in terms of contention. Fast Mutexes do only what you think they should, as minimally as possible, and as effeciently as possible.
ERESOURCEs are sometimes known as reader/writer locks or shared/exclusive locks. If you can use them, you should, as they will generally have the effect of reducing contention and increasing concurrency in your driver. ERESOURCEs are suitable whenever you have operations that only need a lock to keep stuff from getting changed out from under them, as opposed to needing to actually make changes themselves. The Windows filesystem drivers make extensive use of ERESOURCEs.
Someone recently asked on NTDEV about dropping the IRQL after you grab a lock. I'll refer you there for the details (I believe it was Doron Holan who posted the answer), but to make a long story short, never EVER do this. You can basically only call KeLowerIrql() if you previously called KeRaiseIrql(), and even then you can lower the IRQL no lower than where it was when you called KeRaiseIrql().
A couple of other points about FAST_MUTEXes. First, they are *not* dispatcher objects. That means that you cannot call KeWaitFor***() on them, and in particular, you cannot wait for multiple objects with them. If that's what you want to do, they all have to be dispatcher objects. Also, unless you are very sure you know what you're doing, don't try to use ExAcquireFastMutexUnsafe(). Another point to remember is that acquisition of a fast mutex mutex will raise the IRQL to APC_LEVEL, which isn't bad most of the time, but does block all APCs out, so there are some things that the thread you're running in won't be able to do until you drop again. Finally, fast mutexes are not reentrant. You will deadlock if you try to acquire a fast mutex that you already own. Again, if recursive acquisition is what you need, go look at regular dispatchre MUTEXes.
All of this basically just boils down to being a good citizen and obeying the Law Of IRQL Minimization at all times. Don't lock if you don't need to, don't lock for longer than you need to, and use the right tool for the job.
By now, I assume you're sold on the notion of converting to CSQ, and waiting with baited breath for details on how to go about it. If so, this article is for you!
Implementing CSQ in your driver project is really easy to do. There are two bacsic steps:
- Implement a few callbacks to pass to the CSQ library
- Implement the queuing system in your project
CSQ Callbacks
There are six callbacks that you have to implement. In many cases, the implementations will be completely trivial - Microsoft just provided lots of knobs in order to make the library as generally useful as possible. The other nice thing about these routines is that you basically don't have to worry about synchronization at all, as they are called with the CSQ lock held when need be (but remember that queue-manipulation functions are called at DISPATCH_LEVEL!). All of these routines are documented in the DDK, but here's a quickie implementor's guide.
I like to put all of my CSQ support stuff into a sngle file. There are a couple of file-globals that I usually use: a LIST_ENTRY to point to my queue of IRPs, a KSPIN_LOCK to pass to acquire and release when CSQ tells me to, and of course an IO_CSQ struct.
By way of function implementations:
- CsqRemoveIrp - typically just RemoveEntryList. Note that you shouldn't call an interlocked operation here because you don't have to.
- CsqInsertIrp - typically just InsertTailList.
- CsqPeekNextIrp - this function returns a pointer to the next IRP in the list to be removed. This is the least straightforward function, and is worth a read of the DDK for reference. In general, you can return NULL if the list is empty, the head of the queue if no starting IRP is specified, or the IRP itself if one is specified.
- CsqAcquireLock - typically just KeAcquireSpinLock.
- CsqReleaseLock - typically just KeReleaseSpinLock.
- CsqCompleteCanceledIrp - a mini-completion routine. You may just be able to complete the IRP with STATUS_CANCELLED.
That, friends, is all that it takes. This doesn't really take more than a couple of hundred lines of code, and the best part is that once you build your CSQ support file, you can re-use it over and over for similar projects.
Using The Queuing System
Using the CSQ library for the queuing operations in your driver is really a piece of cake. The first step, of course, is to initialize the library. This is typically done during DriverEntry, but can be done wherever is convenient for you. Initialization is done by passing pointers to your callbacks to IoCsqInitialize(). Once that is done, and your LIST_ENTRY and KSPIN_LOCK are initialized, you're ready to use the queue. This is as easy as calling IoCsqInsertIrp and IoCsqRemoveNextIrp. If your queue management needs are more complex than just running the queue in FIFO fashion, other IoCsq APIs allow more control over queue operations.
Summary
This implementation guide covers the simple (and common) case of just needing a single basic FIFO queue to store IRPs during processing. More advanced scenarios are possible, of course. In particular, one of the most common IRP-queuing scenarios involves the use of the StartIo model. If your driver uses StartIo for IRP queuing, CSQ may be just what the doctor ordered for increased queue management and better overall performance. Microsoft has provided a special CSQ sample in the DDK for you; do have a look. The major tweak involves duplicating the semantics of insertion in your CsqInsertIrp callback.
I hope some of you have found this series helpful. Feel free to post questions or comments, and of course corrections. I'd be particularly interested to hear about anyone else's experience in converting to CSQ - problems encountered, performance differences, etc.
I've been told by a reader of this modest little web log that I have shirked my duties by not getting this post up before midnight (my time, which is GMT-6). Because of this oversight on my part, I have failed to make my minimum one post per day. My heartfelt apologies to all three of you who read this blog at this point; I'll try to never let it happen again. :-)
I promised you yesterday that I'd describe some of the Hell of the Cancel Race. In fact, I hope you never have to care about this stuff because you''ve taken my advice and used CSQs in your driver. With that said, the idea basically goes like this.
Say you are a driver that needs to keep a hold of IRPs as they come in. For some reason or other, you are either unable or unwilling to complete the IRPs in their original thread contexts (i.e. synchronously). Therefore, you need a place to stash them before you return to the caller (with STATUS_PENDING). Say you use a trivial linked list to queue up these IRPs for later processing (using the Tail.Overlay.ListEntry generously supplied by Microsoft). For one reason or another, your driver needs to wait a "long" time before it will finally get around to servicing these queued IRPs, so they stay queued for a while. What will happen if someoone above you decides he's tired of waiting for you? He will, of course, cancel his request.
To cancel his request, the originator of the IRP will call IoCancelIrp(). This, in turn, causes the IO manager to look inside the IRP for a CancelRoutine (look up Cancel in the DDK for details). If this routine is present, the IO manager will do some bookkeeping and call the routine. That routine is the way a driver finds out that someone above it wants to cancel that IRP. This driver would then presumably dequeue the IRP from the list and complete it (STATUS_CANCELLED) up the chain.
The problem arises because of the fact that your cancel routine can be called at essentially any time after it is set on the IRP (via IoSetCancelRoutine()). It will want to manipulate the same linked list that your dispatch routines are using to queue and dequeue IRPs normally. Furthermore, there are races with the IO manager between the calling of IoSetCancelRoutine() and enqueuing the IRP, and between dequeuing the IRP and calling IoSetCancelRoutine() to clear the cancel routine. Remember, multiple processors can be manipulating the queue simultaneously, so you could have 3 or 4 enqueue/dequeue operations going on at a time, and a couple of cancellations pending.
One detailed example: Suppose you receive an IRP that you decide to queue. If you set the cancel routine first, the IO manager might call the routine before you queue the IRP. Then your cancel routine gets called and tries to de-queue an IRP that isn't on the queue at all. On the other hand, If you queue the IRP first and then set the cancel routine, your dequeuing thread might dequeue the IRP and complete it before you get a chance to set the cancel routine. You then set a cancel routine, and the IO manager savagely rips your IRP out from under ou while you're processing it. Have fun running down that crash!
You can manage the situation appropriately with locks, but organizing your use of those locks in such a way that you won't race is exactly what is so difficult about this problem. The proper solution winds up requiring an interlocked pointer exchange with the CancelRoutine pointer in the IRP, and determining if it was previously NULL (which signals that the IO manager has called the CancelRoutine already). You also have to properly handle the BOOLEAN Cancelled flag in the IRP, which has its own semantics.
Instead of all of that work, why not just call IoAcquireCancelSpinLock() and IoReleaseCancelSpinLock()? Well, a couple of reasons. First, even *that* locking mechanism can be used incorrectly, leading to another tricky race. But even more than that, the cancel lock is a system-wide resource - it is the #1 hot lock in the entire OS. Think about it - the cancel lock has to be acquired by the IO manager every time an IRP is cancelled, at least for a little while (i.e. until the cancel routine calls IoReleaseCancelSpinLock()). Contention for this lock can become a serious bottleneck in your driver's performance. Much better to wait on a driver-owned lock, or even better, an in-stack queued spinlock (more on that another day).
This is really just a start; the only way to really wrap your brain around the cancel races is to try and code cancel logic yourself. Read the DDK docs on all of these functions mentioned here, as well as the general sections on IRP queuing and cancellation. There are other resources on the Internet as well (google for "cancel-safe queues"). Finally, once again, Walter Oney has an excellent IRP cancellation chapter in his WDM book, and (IIRC) even provides source to his queuing logic.
Next up: an example of CSQ usage.
Happy hacking!
One of the earliest things I remember discovering about the difficulties of programming in kernel mode (right after "What the @!$ is with all of these UNICODE_STRINGs?!") is how easy it is to get yourself into race conditions.
All of the standard practices about multi-threaded programming apply when writing a driver, but there's another kicker: you actually have to *care* how many CPUs you have in your system. Well, in particular, you have to care if you have more than one. As I said yesterday, you can officially assume from now on that every stupid Pentium 4-based computer from the local CompUSA is a dual-processor box, so you have to take this seriously. Add to that the subtleties of dealing with spontaneous IRQL raises, interrupts, running in arbitrary thread contexts, and so on, and life gets interesting.
One of the most common race conditions is the IRP cancellation race. It's also one of the trickiest to deal with, even if you generally know what you're doing. Cancellation has changed over the years from the original design, partly due to the change in devices themselves, and partly due to OS optimization. The original mechanism the OS provided for managing the cancel race was based on using StartIo routines, and in fact, the latest DDKs still recommend using a StartIo routine for IRP queue management. It certainly works, for what it was designed to do, but it's not optimal for a number of reasons. Software-only drivers ("virtual" drivers of various sorts, filesystems, etc.) frequently find that the StartIo model is insufficient. Besides, the cancel lock is one of the hottest locks in the system, so staying as far away from it as possible is always a good idea. Walter Oney has a good description of IRP queuing and cancellation in his WDM book, in which he details other reasons he doesn't typically use StartIo-based queuing.
With that said, rolling your own IRP queuing logic is very difficult. The races are subtle, and unless you've made a lot of these mistakes before, you're highly likely to do it wrong, no matter how much you think you have gotten it right. Trust me, I know. :-) Fortuantely, Microsoft has provided a reusable queuing framework called Cancel-Safe Queues. It is implemented in the kernel on XP+ and is available as a static library for all previous OSes. With the advent of the CSQ, there is no reason to ever write custom IRP-queuing logic again.
CSQ is easy to use, and has the distinct advantage of being massively re-used, so it's likely to be bug-free. Tomorrow I'll talk about the race conditions in more detail, and later I'll provide an example of how to use CSQ in your driver.
-sd
There seem to be technical difficulties with the feedback link, among others. I'm working with the msmvps.com staff to get this resolved. Meanwhile, if you have a burning desire to make yourself heard, whack the contact button at the top of the page.
Sorry for the inconvenience; we now return you to your regularly-scheduled blogging.
-sd
I posted on the PCAUSA NDIS Driver Discussion List (www.pcausa.com) a couple of weeks ago about my new driver-testing computer. Since then, I have gotten a couple of questions about the details of the setup. Since everyone needs one of these anyway :-) I thought I'd post some details.
I am currently running my driver tests on a home-grown dual-AMD64. Reasons I went with this setup:
- All drivers need to be extensively tested for race conditions, etc., on a 2+ processor system before foisting them on the unsuspecting public. Using a pair of Opteron 240 CPUs, I can get into a true* dual-processor system for a reasonable amount.
- Driver writers should be looking in the direction of 64-bit compatibility, starting now. Peter Viscarola from OSR pointed out in an NT Insider issue months ago that AMD64 boxes are, in fact, the coolest things since sliced bread (more on that later). Going with Opteron CPUs now should help work out any 64-bit compatibility problems.
- In my experience, MP boards tend to be higher-quality, leading to fewer mysterious hardware-based bugs than on your run-of-the-mill junk mobo. This has its downsides, though: the IWill board that I chose requres registered RAM, and only specific chips and manufacturers are listed on IWill's compatibility matrix.
- Back to that IWill board- it has all of the new toys that current motherboards have: firewire-800 (for kernel debugging, assuming I ever get it working), usb1.1 and usb2.0 ports, built in GigE on copper, plenty of RAM slots (8!), Serial ATA and standard IDE connections, on-board SATA RAID, and lots of other little bells and whistles that aren't coming to mind atm. This thing has more toys even than my wife's Mac G5, which I thought was pretty well loaded at the time.
- It is known (by me, at least!) to work with the AMD64 preview of XP
Installation was a bit of a pain - I finally had to use an IDE disk as primary/master to get it working with our version of Ghost (although our IT staff tells me that the new Ghost should support my SATA controller).
Once the hardware configuration was ironed out, installation of the 64-bit os went perfectly. I started with a release mode version, just to see if it was fast. It is. :-D It is the fastest Windows computer I've ever had a console on, in terms of app responsiveness. IO is lightning fast. The best part is that VMWare already has native amd64 support. That, plus all of the standard development environment (psdk, ddk, cygwin/vim/cvs/grep/blah/blah), yields a fully-useful dev box.
For testing, VMWare is sufficient for 32-bit SP OSes, but that wasn't really the point of all this, was it? Ghosts of the 64-bit checked OSes will round out the system nicely, once I get around to building them, and since I don't really use the release side for development anyway, that is perfect for testing on a release build.
Anyone who wants more details on the parts that went into this box is welcome to contact me, and I'll be glad to send along part names/numbers, etc.
Happy Hacking.
-sd
* Intel Pentium 4 CPUs do something called "hyper-threading". This basically presents a dual-processor interface to the OS, resulting in the same sorts of race conditions that you get on boxes with two+ real chips. This is a VERY GOOD REASON to test every driver on a 2-proc+ chip, as every stupid computer sold at BestBuy/CompUSA/etc., is now a multiprocessor box.
Welcome to the Grand Opening of Kernel Mustard, my new blog (loosely) centered around Windows kernel-mode development. In the coming days, I will be posting occasional articles about kmode-related topics, and software development in general, some of which might actually be a little bit interesting! Who knows.
I'm also happy to take submissions, if you're in a mood to share. Questions, complaints, comments, etc., can be directed to the contact link at the top of the screen. OK, not complaints, actually. :)