KD System Rewrite:
[reactos.git] / reactos / ntoskrnl / ke / timer.c
index 333f169..49504f9 100644 (file)
-/* $Id: timer.c,v 1.39 2001/02/18 19:43:15 phreak Exp $
- *
- * COPYRIGHT:      See COPYING in the top level directory
- * PROJECT:        ReactOS kernel
- * FILE:           ntoskrnl/ke/timer.c
- * PURPOSE:        Handle timers
- * PROGRAMMER:     David Welch (welch@mcmail.com)
- * UPDATE HISTORY:
- *                 28/05/98: Created
- *                 12/3/99:  Phillip Susi: enabled the timers, fixed spin lock
- */
-
-/* NOTES ******************************************************************/
 /*
- * System time units are 100-nanosecond intervals
+ * COPYRIGHT:       See COPYING in the top level directory
+ * PROJECT:         ReactOS kernel
+ * FILE:            ntoskrnl/ke/timer.c
+ * PURPOSE:         Handle Kernel Timers (Kernel-part of Executive Timers)
+ * 
+ * PROGRAMMERS:     Alex Ionescu (alex@relsoft.net) - Reimplemented some parts, fixed many bugs.
+ *                  David Welch (welch@mcmail.com) &  Phillip Susi - Original Implementation.
  */
 
 /* INCLUDES ***************************************************************/
 
-#include <limits.h>
-#include <ddk/ntddk.h>
-#include <internal/ke.h>
-#include <internal/id.h>
-#include <internal/ps.h>
+#include <ntoskrnl.h>
 
 #define NDEBUG
 #include <internal/debug.h>
 
-/* TYPES *****************************************************************/
-
-#define TIMER_IRQ 0
-
 /* GLOBALS ****************************************************************/
 
-#define IDMAP_BASE         (0xd0000000)
-
-/*
- * Return a linear address which can be used to access the physical memory
- * starting at x 
- */
-unsigned int physical_to_linear(unsigned int x)
-{
-        return(x+IDMAP_BASE);
-}
-
-unsigned int linear_to_physical(unsigned int x)
-{
-        return(x-IDMAP_BASE);
-}
-
-/*
- * Current time
- */
-static unsigned long long boot_time = 0;
-static unsigned long long system_time = 0;
-
-/*
- * Number of timer interrupts since initialisation
- */
-volatile ULONGLONG KiTimerTicks;
-volatile ULONG KiRawTicks = 0;
-
-/*
- * The increment in the system clock every timer tick (in system time units)
- * 
- * = (1/18.2)*10^9 
- * 
- * RJJ was 54945055
- */
-#define CLOCK_INCREMENT (100000)
-
-/*
- * PURPOSE: List of timers
- */
-static LIST_ENTRY TimerListHead;
-static KSPIN_LOCK TimerListLock;
-static KDPC ExpireTimerDpc;
-
-/* must raise IRQL to HIGH_LEVEL and grab spin lock there, to sync with ISR */
+LIST_ENTRY KiTimerListHead;
 
-extern ULONG PiNrRunnableThreads;
-
-#define MICROSECONDS_PER_TICK (10000)
-#define TICKS_TO_CALIBRATE (1)
-#define CALIBRATE_PERIOD (MICROSECONDS_PER_TICK * TICKS_TO_CALIBRATE)
 #define SYSTEM_TIME_UNITS_PER_MSEC (10000)
 
-static BOOLEAN TimerInitDone = FALSE;
-
 /* FUNCTIONS **************************************************************/
 
+BOOLEAN STDCALL KiInsertTimer(PKTIMER Timer, LARGE_INTEGER DueTime);
+VOID STDCALL KiHandleExpiredTimer(PKTIMER Timer);
 
-NTSTATUS STDCALL NtQueryTimerResolution(OUT    PULONG  MinimumResolution,
-                                       OUT     PULONG  MaximumResolution, 
-                                       OUT     PULONG  ActualResolution)
-{
-       UNIMPLEMENTED;
-}
-
-
-NTSTATUS STDCALL NtSetTimerResolution(IN       ULONG   RequestedResolution,
-                                     IN        BOOL    SetOrUnset,
-                                     OUT       PULONG  ActualResolution)
-{
-       UNIMPLEMENTED;
-}
-
-
-NTSTATUS STDCALL NtQueryPerformanceCounter (IN PLARGE_INTEGER  Counter,
-                                           IN  PLARGE_INTEGER  Frequency)
-{
-       UNIMPLEMENTED;
-}
-
-
-NTSTATUS KeAddThreadTimeout(PKTHREAD Thread, PLARGE_INTEGER Interval)
-{
-   assert(Thread != NULL);
-   assert(Interval != NULL);
-
-   DPRINT("KeAddThreadTimeout(Thread %x, Interval %x)\n",Thread,Interval);
-   
-   KeInitializeTimer(&Thread->Timer);
-   KeSetTimer(&Thread->Timer, *Interval, &Thread->TimerDpc);
-
-   DPRINT("Thread->Timer.entry.Flink %x\n",
-           Thread->Timer.TimerListEntry.Flink);
-   
-   return STATUS_SUCCESS;
-}
-
-
-NTSTATUS STDCALL NtDelayExecution(IN ULONG Alertable,
-                                 IN TIME* Interval)
-{
-   NTSTATUS Status;
-   LARGE_INTEGER Timeout;
-   
-   Timeout = *((PLARGE_INTEGER)Interval);
-   DPRINT("NtDelayExecution(Alertable %d, Internal %x) IntervalP %x\n",
-         Alertable, Internal, Timeout);
-   
-   DPRINT("Execution delay is %d/%d\n", 
-         Timeout.u.Highpart, Timeout.u.LowPart);
-   Status = KeDelayExecutionThread(UserMode, Alertable, &Timeout);
-   return(Status);
-}
-
-
-NTSTATUS STDCALL
-KeDelayExecutionThread (KPROCESSOR_MODE        WaitMode,
-                       BOOLEAN         Alertable,
-                       PLARGE_INTEGER  Interval)
 /*
- * FUNCTION: Puts the current thread into an alertable or nonalertable 
- * wait state for a given internal
+ * @implemented
+ *
+ * FUNCTION: Removes a timer from the system timer list
  * ARGUMENTS:
- *          WaitMode = Processor mode in which the caller is waiting
- *          Altertable = Specifies if the wait is alertable
- *          Interval = Specifies the interval to wait
- * RETURNS: Status
+ *       Timer = timer to cancel
+ * RETURNS: True if the timer was running
+ *          False otherwise
  */
+BOOLEAN 
+STDCALL
+KeCancelTimer(PKTIMER Timer)
 {
-   PKTHREAD CurrentThread = KeGetCurrentThread();
-   KeAddThreadTimeout(CurrentThread, Interval);
-   return (KeWaitForSingleObject(&CurrentThread->Timer,
-                                Executive,
-                                UserMode,
-                                Alertable,
-                                NULL));
+    KIRQL OldIrql;
+    BOOLEAN Inserted = FALSE;
+   
+    DPRINT("KeCancelTimer(Timer %x)\n",Timer);
+
+    /* Lock the Database and Raise IRQL */
+    OldIrql = KeAcquireDispatcherDatabaseLock();
+
+    /* Check if it's inserted, and remove it if it is */
+    if ((Inserted = Timer->Header.Inserted)) {
+        
+        /* Remove from list */
+        DPRINT("Timer was inserted, removing\n");
+        RemoveEntryList(&Timer->TimerListEntry);
+        Timer->Header.Inserted = FALSE;
+        
+    } else {
+    
+        DPRINT("Timer was not inserted\n");
+    }
+
+    /* Release Dispatcher Lock */
+    KeReleaseDispatcherDatabaseLock(OldIrql);
+
+    /* Return the old state */
+    DPRINT("Old State: %d\n", Inserted);
+    return(Inserted);
 }
 
-ULONG STDCALL
-KeQueryTimeIncrement (VOID)
 /*
- * FUNCTION: Gets the increment (in 100-nanosecond units) that is added to 
- * the system clock every time the clock interrupts
- * RETURNS: The increment
+ * @implemented
+ *
+ * FUNCTION: Initalizes a kernel timer object
+ * ARGUMENTS:
+ *          Timer = caller supplied storage for the timer
+ * NOTE: This function initializes a notification timer
  */
+VOID 
+STDCALL
+KeInitializeTimer (PKTIMER Timer)
+
 {
-   return(CLOCK_INCREMENT);
+    /* Call the New Function */
+    KeInitializeTimerEx(Timer, NotificationTimer);
 }
 
-VOID STDCALL
-KeQuerySystemTime (PLARGE_INTEGER      CurrentTime)
 /*
- * FUNCTION: Gets the current system time
+ * @implemented
+ *
+ * FUNCTION: Initializes a kernel timer object
  * ARGUMENTS:
- *          CurrentTime (OUT) = The routine stores the current time here
- * NOTE: The time is the number of 100-nanosecond intervals since the
- * 1st of January, 1601.
+ *          Timer = caller supplied storage for the timer
+ *          Type = the type of timer (notification or synchronization)
+ * NOTE: When a notification type expires all waiting threads are released
+ * and the timer remains signalled until it is explicitly reset. When a 
+ * syncrhonization timer expires its state is set to signalled until a
+ * single waiting thread is released and then the timer is reset.
  */
+VOID 
+STDCALL
+KeInitializeTimerEx (PKTIMER Timer,
+                     TIMER_TYPE Type)
 {
-  CurrentTime->QuadPart = system_time;
+
+    DPRINT("KeInitializeTimerEx(%x, %d)\n", Timer, Type);
+    
+    /* Initialize the Dispatch Header */
+    KeInitializeDispatcherHeader(&Timer->Header,
+                                 TimerNotificationObject + Type,
+                                 sizeof(KTIMER) / sizeof(ULONG),
+                                 FALSE);
+   
+    /* Initalize the Other data */
+    Timer->DueTime.QuadPart = 0;
+    Timer->Period = 0;
 }
 
 
-NTSTATUS STDCALL
-NtGetTickCount (PULONG UpTime)
+/*
+ * @implemented
+ */
+BOOLEAN 
+STDCALL
+KeReadStateTimer (PKTIMER Timer)
 {
-       LARGE_INTEGER TickCount;
-       if ( UpTime == NULL )
-               return(STATUS_INVALID_PARAMETER);
-       KeQueryTickCount(&TickCount);
-       *UpTime = TickCount.u.LowPart;
-       return (STATUS_SUCCESS);
+    /* Return the Signal State */
+    return (BOOLEAN)Timer->Header.SignalState;
 }
 
-
-BOOLEAN STDCALL
-KeSetTimer (PKTIMER            Timer,
-           LARGE_INTEGER       DueTime,
-           PKDPC               Dpc)
 /*
+ * @implemented
+ *
  * FUNCTION: Sets the absolute or relative interval at which a timer object
  * is to be set to the signaled state and optionally supplies a 
  * CustomTimerDpc to be executed when the timer expires.
@@ -223,16 +142,19 @@ KeSetTimer (PKTIMER               Timer,
  * RETURNS: True if the timer was already in the system timer queue
  *          False otherwise
  */
+BOOLEAN 
+STDCALL
+KeSetTimer (PKTIMER Timer,
+            LARGE_INTEGER DueTime,
+            PKDPC Dpc)
 {
-   return(KeSetTimerEx(Timer, DueTime, 0, Dpc));
+    /* Call the newer function and supply a period of 0 */
+    return KeSetTimerEx(Timer, DueTime, 0, Dpc);
 }
 
-BOOLEAN STDCALL
-KeSetTimerEx (PKTIMER          Timer,
-             LARGE_INTEGER     DueTime,
-             LONG              Period,
-             PKDPC             Dpc)
 /*
+ * @implemented
+ *
  * FUNCTION: Sets the absolute or relative interval at which a timer object
  * is to be set to the signaled state and optionally supplies a 
  * CustomTimerDpc to be executed when the timer expires.
@@ -244,277 +166,218 @@ KeSetTimerEx (PKTIMER           Timer,
  * RETURNS: True if the timer was already in the system timer queue
  *          False otherwise
  */
+BOOLEAN 
+STDCALL
+KeSetTimerEx (PKTIMER Timer,
+              LARGE_INTEGER DueTime,
+              LONG Period,
+              PKDPC Dpc)
 {
-   KIRQL oldlvl;
-   
-   DPRINT("KeSetTimerEx(Timer %x), DueTime: \n",Timer);
-   KeAcquireSpinLock( &TimerListLock, &oldlvl );
-   
-   Timer->Dpc = Dpc;
-   if (DueTime.QuadPart < 0)
-     {
-       Timer->DueTime.QuadPart = system_time - DueTime.QuadPart;
-     }
-   else
-     {
-       Timer->DueTime.QuadPart = DueTime.QuadPart;
-     }
-   Timer->Period = Period;
-   Timer->Header.SignalState = FALSE;
-   if (Timer->TimerListEntry.Flink != NULL)
-     {
-       KeReleaseSpinLock(&TimerListLock, oldlvl);
-       return(TRUE);
-     }
-   InsertTailList(&TimerListHead,&Timer->TimerListEntry);
-   KeReleaseSpinLock(&TimerListLock, oldlvl);
-   
-   return FALSE;
+    KIRQL OldIrql;
+    BOOLEAN Inserted;
+
+    DPRINT("KeSetTimerEx(Timer %x, DueTime %I64d, Period %d, Dpc %x)\n", Timer, DueTime.QuadPart, Period, Dpc);
+    ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+
+    /* Lock the Database and Raise IRQL */
+    OldIrql = KeAcquireDispatcherDatabaseLock();
+
+    /* Check if it's inserted, and remove it if it is */
+    if ((Inserted = Timer->Header.Inserted)) {
+        
+        /* Remove from list */
+        DPRINT("Timer was already inserted\n");
+        RemoveEntryList(&Timer->TimerListEntry);
+        Timer->Header.Inserted = FALSE;        
+    }
+    
+    /* Set Default Timer Data */ 
+    Timer->Dpc = Dpc;
+    Timer->Period = Period;
+    Timer->Header.SignalState = FALSE;
+    
+    /* Insert it */
+    if (!KiInsertTimer(Timer, DueTime)) {
+
+       KiHandleExpiredTimer(Timer);
+    };
+
+    /* Release Dispatcher Lock */
+    KeReleaseDispatcherDatabaseLock(OldIrql);
+
+    /* Return old state */
+    DPRINT("Old State: %d\n", Inserted);
+    return Inserted;
 }
 
-BOOLEAN STDCALL
-KeCancelTimer (PKTIMER Timer)
-/*
- * FUNCTION: Removes a timer from the system timer list
- * ARGUMENTS:
- *       Timer = timer to cancel
- * RETURNS: True if the timer was running
- *          False otherwise
- */
-{
-   KIRQL oldlvl;
-   
-   DPRINT("KeCancelTimer(Timer %x)\n",Timer);
-   
-   KeRaiseIrql( HIGH_LEVEL, &oldlvl );
-   KeAcquireSpinLockAtDpcLevel( &TimerListLock );
-                    
-   if (Timer->TimerListEntry.Flink == NULL)
-     {
-       KeReleaseSpinLock(&TimerListLock, oldlvl);
-       return(FALSE);
-     }
-   RemoveEntryList(&Timer->TimerListEntry);
-   Timer->TimerListEntry.Flink = Timer->TimerListEntry.Blink = NULL;
-   KeReleaseSpinLock(&TimerListLock, oldlvl);
-
-   return(TRUE);
-}
-
-BOOLEAN STDCALL
-KeReadStateTimer (PKTIMER      Timer)
-{
-   return(Timer->Header.SignalState);
-}
-
-VOID STDCALL
-KeInitializeTimer (PKTIMER     Timer)
-/*
- * FUNCTION: Initalizes a kernel timer object
- * ARGUMENTS:
- *          Timer = caller supplied storage for the timer
- * NOTE: This function initializes a notification timer
- */
-{
-   KeInitializeTimerEx(Timer,NotificationTimer);
-}
-
-VOID STDCALL
-KeInitializeTimerEx (PKTIMER           Timer,
-                    TIMER_TYPE Type)
-/*
- * FUNCTION: Initializes a kernel timer object
- * ARGUMENTS:
- *          Timer = caller supplied storage for the timer
- *          Type = the type of timer (notification or synchronization)
- * NOTE: When a notification type expires all waiting threads are released
- * and the timer remains signalled until it is explicitly reset. When a 
- * syncrhonization timer expires its state is set to signalled until a
- * single waiting thread is released and then the timer is reset.
- */
+VOID
+STDCALL
+KiExpireTimers(PKDPC Dpc,
+               PVOID DeferredContext,
+               PVOID SystemArgument1,
+               PVOID SystemArgument2)
 {
-   ULONG IType;
-   
-   if (Type == NotificationTimer)
-     {
-       IType = InternalNotificationTimer;
-     }
-   else if (Type == SynchronizationTimer)
-     {
-       IType = InternalSynchronizationTimer;
-     }
-   else
-     {
-       assert(FALSE);
-       return;
-     }
-   
-   KeInitializeDispatcherHeader(&Timer->Header,
-                               IType,
-                               sizeof(KTIMER) / sizeof(ULONG),
-                               FALSE);
-   Timer->TimerListEntry.Flink = Timer->TimerListEntry.Blink = NULL;
+    PKTIMER Timer;
+    ULONGLONG InterruptTime;
+    LIST_ENTRY ExpiredTimerList;
+    PLIST_ENTRY CurrentEntry = NULL;
+    KIRQL OldIrql;
+
+    DPRINT("KiExpireTimers(Dpc: %x)\n", Dpc);
+    
+    /* Initialize the Expired Timer List */
+    InitializeListHead(&ExpiredTimerList);
+
+    /* Lock the Database and Raise IRQL */
+    OldIrql = KeAcquireDispatcherDatabaseLock();
+    
+    /* Query Interrupt Times */ 
+    InterruptTime = KeQueryInterruptTime();
+
+    /* Loop through the Timer List and remove Expired Timers. Insert them into the Expired Listhead */
+    CurrentEntry = KiTimerListHead.Flink;
+    while (CurrentEntry != &KiTimerListHead) {
+    
+        /* Get the Current Timer */
+        Timer = CONTAINING_RECORD(CurrentEntry, KTIMER, TimerListEntry);
+        DPRINT("Looping for Timer: %x. Duetime: %I64d. InterruptTime %I64d \n", Timer, Timer->DueTime.QuadPart, InterruptTime);
+        
+        /* Check if we have to Expire it */
+        if (InterruptTime < Timer->DueTime.QuadPart) break;
+        
+        CurrentEntry = CurrentEntry->Flink;
+       
+        /* Remove it from the Timer List, add it to the Expired List */
+        RemoveEntryList(&Timer->TimerListEntry);
+        InsertTailList(&ExpiredTimerList, &Timer->TimerListEntry);
+    }
+    
+    /* Expire the Timers */
+    while ((CurrentEntry = RemoveHeadList(&ExpiredTimerList)) != &ExpiredTimerList) {
+        
+        /* Get the Timer */
+        Timer = CONTAINING_RECORD(CurrentEntry, KTIMER, TimerListEntry);
+        DPRINT("Expiring Timer: %x\n", Timer);
+        
+        /* Expire it */
+        KiHandleExpiredTimer(Timer);
+    }
+
+    DPRINT("Timers expired\n");
+
+    /* Release Dispatcher Lock */
+    KeReleaseDispatcherDatabaseLock(OldIrql);
 }
 
-VOID STDCALL
-KeQueryTickCount (PLARGE_INTEGER       TickCount)
 /*
- * FUNCTION: Returns the number of ticks since the system was booted
- * ARGUMENTS:
- *         TickCount (OUT) = Points to storage for the number of ticks
+ * We enter this function at IRQL DISPATCH_LEVEL, and with the
+ * Dispatcher Lock held!
  */
+VOID 
+STDCALL
+KiHandleExpiredTimer(PKTIMER Timer)
 {
-  TickCount->QuadPart = KiTimerTicks;
-}
 
-static void HandleExpiredTimer(PKTIMER current)
-{
-   DPRINT("HandleExpiredTime(current %x)\n",current);
-   if (current->Dpc != NULL)
-     {
-       DPRINT("current->Dpc %x current->Dpc->DeferredRoutine %x\n",
-              current->Dpc, current->Dpc->DeferredRoutine);
-       KeInsertQueueDpc(current->Dpc,
-                        NULL,
-                        NULL);
-       DPRINT("Finished dpc routine\n");
-     }
-   KeAcquireDispatcherDatabaseLock( FALSE );
-   current->Header.SignalState = TRUE;
-   KeDispatcherObjectWake( &current->Header );
-   KeReleaseDispatcherDatabaseLock( FALSE );
-   if (current->Period != 0)
-     {
-       current->DueTime.QuadPart += 
-         current->Period * SYSTEM_TIME_UNITS_PER_MSEC;
-     }
-   else
-     {
-       RemoveEntryList(&current->TimerListEntry);
-       current->TimerListEntry.Flink = current->TimerListEntry.Blink = NULL;
-     }
+    LARGE_INTEGER DueTime;
+    DPRINT("HandleExpiredTime(Timer %x)\n", Timer);
+    
+    if(Timer->Header.Inserted) {
+
+       /* First of all, remove the Timer */
+       Timer->Header.Inserted = FALSE;
+       RemoveEntryList(&Timer->TimerListEntry);
+    }
+    
+    /* Set it as Signaled */
+    DPRINT("Setting Timer as Signaled\n");
+    Timer->Header.SignalState = TRUE;
+    KiWaitTest(&Timer->Header, IO_NO_INCREMENT);   
+
+    /* If the Timer is periodic, reinsert the timer with the new due time */
+    if (Timer->Period) {
+        
+        /* Reinsert the Timer */
+        DueTime.QuadPart = Timer->Period * -SYSTEM_TIME_UNITS_PER_MSEC;
+        if (!KiInsertTimer(Timer, DueTime)) {
+
+           /* FIXME: I will think about how to handle this and fix it ASAP -- Alex */
+           DPRINT("CRITICAL UNHANDLED CASE: TIMER ALREADY EXPIRED!!!\n");
+        };
+    }
+    
+    /* Check if the Timer has a DPC */
+    if (Timer->Dpc) {
+
+        DPRINT("Timer->Dpc %x Timer->Dpc->DeferredRoutine %x\n", Timer->Dpc, Timer->Dpc->DeferredRoutine);
+        
+        /* Insert the DPC */
+        KeInsertQueueDpc(Timer->Dpc,
+                         NULL,
+                         NULL);
+        
+        DPRINT("Finished dpc routine\n");
+    }
 }
 
-VOID KeExpireTimers( PKDPC Dpc,
-                    PVOID Context1,
-                    PVOID Arg1,
-                    PVOID Arg2 )
-{
-   PLIST_ENTRY current_entry = NULL;
-   PKTIMER current = NULL;
-
-   DPRINT("KeExpireTimers()\n");
-   
-   current_entry = TimerListHead.Flink;
-   
-   KeAcquireSpinLockAtDpcLevel(&TimerListLock);
-   
-   while (current_entry!=(&TimerListHead))
-     {
-       current = CONTAINING_RECORD(current_entry, KTIMER, TimerListEntry);
-       
-       current_entry = current_entry->Flink;
-       
-       if (system_time >= current->DueTime.QuadPart)
-         {
-            HandleExpiredTimer(current);
-         }      
-     }
-   
-   KeReleaseSpinLockFromDpcLevel( &TimerListLock );
-}
-
-
-VOID KiUpdateSystemTime (VOID)
-/*
- * FUNCTION: Handles a timer interrupt
- */
-{
-   char str[36];
-   char* vidmem=(char *)physical_to_linear(0xb8000 + 160 - 36);
-   int i;
-   int x,y;
-//   extern ULONG EiNrUsedBlocks;
-   extern unsigned int EiFreeNonPagedPool;
-   extern unsigned int EiUsedNonPagedPool;
-   //   extern ULONG PiNrThreads;
-//   extern ULONG MiNrFreePages;
-   
-   KiRawTicks++;
-   
-   if (TimerInitDone == FALSE)
-     {
-       return;
-     }
-   /*
-    * Increment the number of timers ticks 
-    */
-   KiTimerTicks++;
-   system_time = system_time + CLOCK_INCREMENT;
-   
-   /*
-    * Display the tick count in the top left of the screen as a debugging
-    * aid
-    */
-//   sprintf(str,"%.8u %.8u",nr_used_blocks,ticks);
-   if ((EiFreeNonPagedPool + EiUsedNonPagedPool) == 0)
-     {
-       x = y = 0;
-     }
-   else
-     {
-       x = (EiFreeNonPagedPool * 100) / 
-         (EiFreeNonPagedPool + EiUsedNonPagedPool);
-       y = (EiUsedNonPagedPool * 100) / 
-         (EiFreeNonPagedPool + EiUsedNonPagedPool);
-     }
-   memset(str, 0, sizeof(str));
-//   sprintf(str,"%.8u %.8u",(unsigned int)EiNrUsedBlocks,
-//        (unsigned int)EiFreeNonPagedPool);
-//   sprintf(str,"%.8u %.8u",EiFreeNonPagedPool,EiUsedNonPagedPool);
-//   sprintf(str,"%.8u %.8u",(unsigned int)PiNrRunnableThreads,
-//        (unsigned int)PiNrThreads);
-//   sprintf(str,"%.8u %.8u", (unsigned int)PiNrRunnableThreads,
-//        (unsigned int)MiNrFreePages);
-   sprintf(str,"%.8u %.8u",EiFreeNonPagedPool,(unsigned int)KiTimerTicks);
-
-   for (i=0;i<17;i++)
-     {
-       *vidmem=str[i];
-       vidmem++;
-       *vidmem=0x7;
-       vidmem++;
-     }
-   KeInsertQueueDpc( &ExpireTimerDpc, 0, 0 );
-}
-
-
-VOID KeInitializeTimerImpl(VOID)
 /*
- * FUNCTION: Initializes timer irq handling
- * NOTE: This is only called once from main()
+ * Note: This function is called with the Dispatcher Lock held.
  */
+BOOLEAN
+STDCALL
+KiInsertTimer(PKTIMER Timer,
+              LARGE_INTEGER DueTime)
 {
-   TIME_FIELDS TimeFields;
-   LARGE_INTEGER SystemBootTime;
-   extern VOID HalpCalibrateStallExecution (VOID);
-   
-   DPRINT("KeInitializeTimerImpl()\n");
-   
-   HalpCalibrateStallExecution ();
-   
-   InitializeListHead(&TimerListHead);
-   KeInitializeSpinLock(&TimerListLock);
-   KeInitializeDpc( &ExpireTimerDpc, KeExpireTimers, 0 );
-   TimerInitDone = TRUE;
-   
-   /*
-    * Calculate the starting time for the system clock
-    */
-   HalQueryRealTimeClock(&TimeFields);
-   RtlTimeFieldsToTime(&TimeFields, &SystemBootTime);
-   boot_time=SystemBootTime.QuadPart;
-   system_time=boot_time;
-   
-   DPRINT("Finished KeInitializeTimerImpl()\n");
+    LARGE_INTEGER SystemTime;
+    LARGE_INTEGER DifferenceTime;
+    ULONGLONG InterruptTime;
+    
+    DPRINT("KiInsertTimer(Timer %x DueTime %I64d)\n", Timer, DueTime.QuadPart);
+    
+    /* Set default data */
+    Timer->Header.Inserted = TRUE;
+    Timer->Header.Absolute = FALSE;
+    if (!Timer->Period) Timer->Header.SignalState = FALSE;
+    
+    /* Convert to relative time if needed */
+    if (DueTime.u.HighPart >= 0) {
+        
+        /* Get System Time */
+        KeQuerySystemTime(&SystemTime);
+        
+        /* Do the conversion */
+        DifferenceTime.QuadPart = SystemTime.QuadPart - DueTime.QuadPart;
+        DPRINT("Time Difference is: %I64d\n", DifferenceTime.QuadPart);
+        
+        /* Make sure it hasn't already expired */
+        if (DifferenceTime.u.HighPart >= 0) {
+        
+            /* Cancel everything */
+            DPRINT("Timer already expired: %d\n", DifferenceTime.u.HighPart);
+            Timer->Header.SignalState = TRUE;
+            Timer->Header.Inserted = FALSE;
+            return FALSE;
+        }
+        
+        /* Set the time as Absolute */
+        Timer->Header.Absolute = TRUE;
+        DueTime = DifferenceTime;
+    }
+    
+    /* Get the Interrupt Time */
+    InterruptTime = KeQueryInterruptTime();
+    
+    /* Set the Final Due Time */
+    Timer->DueTime.QuadPart = InterruptTime - DueTime.QuadPart;
+    DPRINT("Final Due Time is: %I64d\n", Timer->DueTime.QuadPart);
+    
+    /* Now insert it into the Timer List */    
+    DPRINT("Inserting Timer into list\n");
+    InsertAscendingList(&KiTimerListHead, 
+                        KTIMER,
+                        TimerListEntry, 
+                        Timer,
+                        DueTime.QuadPart);
+    
+    return TRUE;
 }
+/* EOF */