Windows Kernel Mode Wait

Sometimes you have to wait, even when writing a Windows driver. Well, waiting in kernel mode is a bad idea in general but sometimes it is necessary.

Today I stumbled over a code fragment which I know from my experience does not do what the programmer might have expected. The problem is the function KeDelayExecutionThread. KeDelayExecutionThread was used in a wait function which was designed to wait for any time in micro seconds. The value of micro seconds was passed to KeDelayExecutionThread multiplied by ten to generate a wait time in steps of 100 nano seconds.


There are two problems in this approach. First is that KeDelayExecutionThread waits for an absolute time event in case of a positive number. Thus to get the requested delay in micro seconds one has to specify a negative value. The second problem here is that KeDelayExecutionThread yields the process which leads to a very inaccurate delay especially for times smaller than about 50 milli seconds.


A better kernel wait function would call KeDelayExecutionThread or KeDelayExecutionThread depending on the situaton.


Maybe like this :

wait( LONG usec )
    ULONG ulReturn = 0;
    if( usec < 50000 )
        /* KeDelayExecutionThread yields the process */
        /* Waiting times lower than 50ms are not accurate */
        /* Because of this we need to busy wait here */
        KeStallExecutionProcessor( usecĀ );
        LARGE_INTEGER waittime;
        /* specifies the wait time in steps of 100ns */
        /* Negative values specify a relative time offset */
        waittime.QuadPart = -1 * usecĀ * 10;
        if( STATUS_SUCCESS == KeDelayExecutionThread( KernelMode, TRUE, &waittime ) )
            ulReturn = 0;
            ulReturn = 1;
    return ulReturn;