Thursday, 10 July 2014 10:26

Windows Kernel Mode Wait

Written by 
Rate this item
(0 votes)

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( ULONG usec )
{
    ULONG ulReturn = 0;
    if( u_sec < 50000 )
    {
        /* KeDelayExecutionThread yields the process */
        /* Waiting times lower than 50ms are not accurate */
        /* Because of this we need to busy wait here */
        KeStallExecutionProcessor( usec );
    }
    else
    {
        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;
        else
            ulReturn = 1;
    }
    return ulReturn;
}

 

Read 3126 times Last modified on Friday, 26 June 2015 12:24

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.