-reorder InsertXscendingOrder macro argument order and update uses
-start to macrofy list enums in ntoskrnl using LIST_FOR_EACH macros
-use IsListEmpty some places instead of manual coding
-profile.c:KeStartProfile() zero correct buffer in (and not the NULL ptr;-)
-improve LIST_FOR_EACH macros so that the iterator is set to NULL at end of enum
-kthread.c:KiServiceCheck() set the shadowtable before calling the win32k proc/thread init funcs
-apc.c:KiInsertQueueApc() insert special apcs in correct fifo order 
-apc.c:KeFlushQueueApc() simplify 
-timer.c:KiExpireTimers() calling RemoveEntryList on a possibly empty list is not ok
Modified: trunk/reactos/include/reactos/helper.h
Modified: trunk/reactos/ntoskrnl/io/device.c
Modified: trunk/reactos/ntoskrnl/io/driver.c
Modified: trunk/reactos/ntoskrnl/io/file.c
Modified: trunk/reactos/ntoskrnl/io/fs.c
Modified: trunk/reactos/ntoskrnl/io/irp.c
Modified: trunk/reactos/ntoskrnl/io/pnpnotify.c
Modified: trunk/reactos/ntoskrnl/io/pnproot.c
Modified: trunk/reactos/ntoskrnl/ke/apc.c
Modified: trunk/reactos/ntoskrnl/ke/bug.c
Modified: trunk/reactos/ntoskrnl/ke/kqueue.c
Modified: trunk/reactos/ntoskrnl/ke/kthread.c
Modified: trunk/reactos/ntoskrnl/ke/profile.c
Modified: trunk/reactos/ntoskrnl/ke/queue.c
Modified: trunk/reactos/ntoskrnl/ke/timer.c
Modified: trunk/reactos/subsys/system/usetup/partlist.c
Modified: trunk/reactos/subsys/win32k/ntuser/class.c

Modified: trunk/reactos/include/reactos/helper.h
--- trunk/reactos/include/reactos/helper.h	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/include/reactos/helper.h	2005-09-26 22:57:48 UTC (rev 18113)
@@ -18,17 +18,21 @@
 #define EXPORTED __declspec(dllexport)
 #define IMPORTED __declspec(dllimport)
 
-/* iterate through the list using a list entry */
+/* iterate through the list using a list entry. 
+ * elem is set to NULL if the list is run thru without breaking out or if list is empty.
+ */
 #define LIST_FOR_EACH(elem, list, type, field) \
     for ((elem) = CONTAINING_RECORD((list)->Flink, type, field); \
-         &(elem)->field != (list); \
+         &(elem)->field != (list) || (elem = NULL); \
          (elem) = CONTAINING_RECORD((elem)->field.Flink, type, field))
          
-/* iterate through the list using a list entry, with safety against removal */
+/* iterate through the list using a list entry, with safety against removal 
+ * elem is set to NULL if the list is run thru without breaking out or if list is empty.
+ */
 #define LIST_FOR_EACH_SAFE(cursor, cursor2, list, type, field) \
     for ((cursor) = CONTAINING_RECORD((list)->Flink, type, field), \
          (cursor2) = CONTAINING_RECORD((cursor)->field.Flink, type, field); \
-         &(cursor)->field != (list); \
+         &(cursor)->field != (list) || (cursor = NULL); \
          (cursor) = (cursor2), \
          (cursor2) = CONTAINING_RECORD((cursor)->field.Flink, type, field))
          
@@ -55,7 +59,7 @@
 #define HOURS_TO_100NS(hours) (((LONGLONG)(hours)) * MINUTES_TO_100NS(60))
 #define UNICODIZE1(x) L##x
 #define UNICODIZE(x) UNICODIZE1(x)
-#define InsertAscendingListFIFO(ListHead, Type, ListEntryField, NewEntry, SortField)\
+#define InsertAscendingListFIFO(ListHead, NewEntry, Type, ListEntryField, SortField)\
 {\
   PLIST_ENTRY current;\
 \
@@ -73,7 +77,7 @@
   InsertTailList(current, &((NewEntry)->ListEntryField));\
 }
 
-#define InsertDescendingListFIFO(ListHead, Type, ListEntryField, NewEntry, SortField)\
+#define InsertDescendingListFIFO(ListHead, NewEntry, Type, ListEntryField, SortField)\
 {\
   PLIST_ENTRY current;\
 \
@@ -91,7 +95,7 @@
   InsertTailList(current, &((NewEntry)->ListEntryField));\
 }
 
-#define InsertAscendingList(ListHead, Type, ListEntryField, NewEntry, SortField)\
+#define InsertAscendingList(ListHead, NewEntry, Type, ListEntryField, SortField)\
 {\
   PLIST_ENTRY current;\
 \
@@ -109,7 +113,7 @@
   InsertTailList(current, &((NewEntry)->ListEntryField));\
 }
 
-#define InsertDescendingList(ListHead, Type, ListEntryField, NewEntry, SortField)\
+#define InsertDescendingList(ListHead, NewEntry, Type, ListEntryField, SortField)\
 {\
   PLIST_ENTRY current;\
 \

Modified: trunk/reactos/ntoskrnl/io/device.c
--- trunk/reactos/ntoskrnl/io/device.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/io/device.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -33,17 +33,13 @@
 IoShutdownRegisteredDevices(VOID)
 {
    PSHUTDOWN_ENTRY ShutdownEntry;
-   PLIST_ENTRY Entry;
    IO_STATUS_BLOCK StatusBlock;
    PIRP Irp;
    KEVENT Event;
    NTSTATUS Status;
 
-   Entry = ShutdownListHead.Flink;
-   while (Entry != &ShutdownListHead)
+   LIST_FOR_EACH(ShutdownEntry, &ShutdownListHead, SHUTDOWN_ENTRY, ShutdownList)
      {
-	ShutdownEntry = CONTAINING_RECORD(Entry, SHUTDOWN_ENTRY, ShutdownList);
-
 	KeInitializeEvent (&Event,
 	                   NotificationEvent,
 	                   FALSE);
@@ -66,8 +62,6 @@
 		                       FALSE,
 		                       NULL);
 	}
-
-	Entry = Entry->Flink;
      }
 }
 
@@ -1082,27 +1076,24 @@
 STDCALL
 IoUnregisterShutdownNotification(PDEVICE_OBJECT DeviceObject)
 {
-   PSHUTDOWN_ENTRY ShutdownEntry;
-   PLIST_ENTRY Entry;
+   PSHUTDOWN_ENTRY ShutdownEntry, tmp;
    KIRQL oldlvl;
 
-   Entry = ShutdownListHead.Flink;
-   while (Entry != &ShutdownListHead)
+   LIST_FOR_EACH_SAFE(ShutdownEntry, tmp, &ShutdownListHead, SHUTDOWN_ENTRY, ShutdownList) 
      {
-	ShutdownEntry = CONTAINING_RECORD(Entry, SHUTDOWN_ENTRY, ShutdownList);
+
 	if (ShutdownEntry->DeviceObject == DeviceObject)
 	  {
 	    DeviceObject->Flags &= ~DO_SHUTDOWN_REGISTERED;
 
 	    KeAcquireSpinLock(&ShutdownListLock,&oldlvl);
-	    RemoveEntryList(Entry);
+       RemoveEntryList(&ShutdownEntry->ShutdownList);
 	    KeReleaseSpinLock(&ShutdownListLock,oldlvl);
 
-	    ExFreePool(Entry);
+       ExFreePool(ShutdownEntry);
 	    return;
 	  }
 
-	Entry = Entry->Flink;
      }
 }
 

Modified: trunk/reactos/ntoskrnl/io/driver.c
--- trunk/reactos/ntoskrnl/io/driver.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/io/driver.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -1118,44 +1118,32 @@
 NTSTATUS INIT_FUNCTION
 IoDestroyDriverList(VOID)
 {
-  PLIST_ENTRY GroupEntry;
-  PLIST_ENTRY ServiceEntry;
-  PSERVICE_GROUP CurrentGroup;
-  PSERVICE CurrentService;
+  PSERVICE_GROUP CurrentGroup, tmp1;
+  PSERVICE CurrentService, tmp2;
 
   DPRINT("IoDestroyDriverList() called\n");
 
   /* Destroy group list */
-  GroupEntry = GroupListHead.Flink;
-  while (GroupEntry != &GroupListHead)
+  LIST_FOR_EACH_SAFE(CurrentGroup, tmp1, &GroupListHead, SERVICE_GROUP, GroupListEntry)
     {
-      CurrentGroup = CONTAINING_RECORD(GroupEntry, SERVICE_GROUP, GroupListEntry);
-
       ExFreePool(CurrentGroup->GroupName.Buffer);
-      RemoveEntryList(GroupEntry);
+      RemoveEntryList(&CurrentGroup->GroupListEntry);
       if (CurrentGroup->TagArray)
         {
 	  ExFreePool(CurrentGroup->TagArray);
 	}
       ExFreePool(CurrentGroup);
-
-      GroupEntry = GroupListHead.Flink;
     }
 
   /* Destroy service list */
-  ServiceEntry = ServiceListHead.Flink;
-  while (ServiceEntry != &ServiceListHead)
+  LIST_FOR_EACH_SAFE(CurrentService, tmp2, &ServiceListHead, SERVICE, ServiceListEntry)
     {
-      CurrentService = CONTAINING_RECORD(ServiceEntry, SERVICE, ServiceListEntry);
-
       ExFreePool(CurrentService->ServiceName.Buffer);
       ExFreePool(CurrentService->RegistryPath.Buffer);
       ExFreePool(CurrentService->ServiceGroup.Buffer);
       ExFreePool(CurrentService->ImagePath.Buffer);
-      RemoveEntryList(ServiceEntry);
+      RemoveEntryList(&CurrentService->ServiceListEntry);
       ExFreePool(CurrentService);
-
-      ServiceEntry = ServiceListHead.Flink;
     }
 
   DPRINT("IoDestroyDriverList() done\n");
@@ -1423,8 +1411,6 @@
 VOID FASTCALL
 IopInitializeSystemDrivers(VOID)
 {
-   PLIST_ENTRY GroupEntry;
-   PLIST_ENTRY ServiceEntry;
    PSERVICE_GROUP CurrentGroup;
    PSERVICE CurrentService;
    NTSTATUS Status;
@@ -1432,21 +1418,15 @@
 
    DPRINT("IopInitializeSystemDrivers()\n");
 
-   GroupEntry = GroupListHead.Flink;
-   while (GroupEntry != &GroupListHead)
+   LIST_FOR_EACH(CurrentGroup, &GroupListHead, SERVICE_GROUP, GroupListEntry)
    {
-      CurrentGroup = CONTAINING_RECORD(GroupEntry, SERVICE_GROUP, GroupListEntry);
-
       DPRINT("Group: %wZ\n", &CurrentGroup->GroupName);
 
       /* Load all drivers with a valid tag */
       for (i = 0; i < CurrentGroup->TagCount; i++)
       {
-         ServiceEntry = ServiceListHead.Flink;
-         while (ServiceEntry != &ServiceListHead)
+         LIST_FOR_EACH(CurrentService, &ServiceListHead, SERVICE, ServiceListEntry)
          {
-            CurrentService = CONTAINING_RECORD(ServiceEntry, SERVICE, ServiceListEntry);
-
             if ((RtlCompareUnicodeString(&CurrentGroup->GroupName,
                                          &CurrentService->ServiceGroup, TRUE) == 0) &&
 	        (CurrentService->Start == 1 /*SERVICE_SYSTEM_START*/) &&
@@ -1455,15 +1435,12 @@
 	       DPRINT("  Path: %wZ\n", &CurrentService->RegistryPath);
                Status = IopLoadDriver(CurrentService);
  	    }
-            ServiceEntry = ServiceEntry->Flink;
          }
       }
 
       /* Load all drivers without a tag or with an invalid tag */
-      ServiceEntry = ServiceListHead.Flink;
-      while (ServiceEntry != &ServiceListHead)
+      LIST_FOR_EACH(CurrentService, &ServiceListHead, SERVICE, ServiceListEntry)
       {
-         CurrentService = CONTAINING_RECORD(ServiceEntry, SERVICE, ServiceListEntry);
          if ((RtlCompareUnicodeString(&CurrentGroup->GroupName,
                                       &CurrentService->ServiceGroup, TRUE) == 0) &&
 	     (CurrentService->Start == 1 /*SERVICE_SYSTEM_START*/))
@@ -1481,10 +1458,8 @@
                Status = IopLoadDriver(CurrentService);
  	    }
 	 }
-         ServiceEntry = ServiceEntry->Flink;
       }
 
-      GroupEntry = GroupEntry->Flink;
    }
 
    DPRINT("IopInitializeSystemDrivers() done\n");

Modified: trunk/reactos/ntoskrnl/io/file.c
--- trunk/reactos/ntoskrnl/io/file.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/io/file.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -1383,7 +1383,6 @@
    NTSTATUS Status;
    PFILE_OBJECT FileObject;
    PETHREAD Thread;
-   PLIST_ENTRY IrpEntry;
    PIRP Irp;
    KIRQL OldIrql;
    BOOLEAN OurIrpsInList = FALSE;
@@ -1408,11 +1407,9 @@
     */
 
    Thread = PsGetCurrentThread();
-   for (IrpEntry = Thread->IrpList.Flink;
-        IrpEntry != &Thread->IrpList;
-        IrpEntry = IrpEntry->Flink)
+
+   LIST_FOR_EACH(Irp, &Thread->IrpList, IRP, ThreadListEntry)
    {
-      Irp = CONTAINING_RECORD(IrpEntry, IRP, ThreadListEntry);
       if (Irp->Tail.Overlay.OriginalFileObject == FileObject)
       {
          IoCancelIrp(Irp);
@@ -1440,11 +1437,8 @@
        * forever.
        */
 
-      for (IrpEntry = Thread->IrpList.Flink;
-           IrpEntry != &Thread->IrpList;
-           IrpEntry = IrpEntry->Flink)
+      LIST_FOR_EACH(Irp, &Thread->IrpList, IRP, ThreadListEntry)           
       {
-         Irp = CONTAINING_RECORD(IrpEntry, IRP, ThreadListEntry);
          if (Irp->Tail.Overlay.OriginalFileObject == FileObject)
          {
             OurIrpsInList = TRUE;

Modified: trunk/reactos/ntoskrnl/io/fs.c
--- trunk/reactos/ntoskrnl/io/fs.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/io/fs.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -72,7 +72,6 @@
 VOID
 IoShutdownRegisteredFileSystems(VOID)
 {
-  PLIST_ENTRY current_entry;
   FILE_SYSTEM_OBJECT* current;
   PIRP Irp;
   KEVENT Event;
@@ -87,11 +86,8 @@
 		    NotificationEvent,
 		    FALSE);
 
-  current_entry = FileSystemListHead.Flink;
-  while (current_entry!=(&FileSystemListHead))
+  LIST_FOR_EACH(current, &FileSystemListHead, FILE_SYSTEM_OBJECT,Entry)
     {
-      current = CONTAINING_RECORD(current_entry,FILE_SYSTEM_OBJECT,Entry);
-
       /* send IRP_MJ_SHUTDOWN */
       Irp = IoBuildSynchronousFsdRequest(IRP_MJ_SHUTDOWN,
 					 current->DeviceObject,
@@ -110,8 +106,6 @@
 				FALSE,
 				NULL);
 	}
-
-      current_entry = current_entry->Flink;
     }
 
   ExReleaseResourceLite(&FileSystemListLock);
@@ -224,8 +218,7 @@
  * RETURNS: Status
  */
 {
-  PLIST_ENTRY current_entry;
-  FILE_SYSTEM_OBJECT* current;
+  PFILE_SYSTEM_OBJECT current;
   NTSTATUS Status;
   DEVICE_TYPE MatchingDeviceType;
   PDEVICE_OBJECT DevObject;
@@ -262,13 +255,12 @@
 
   KeEnterCriticalRegion();
   ExAcquireResourceSharedLite(&FileSystemListLock,TRUE);
-  current_entry = FileSystemListHead.Flink;
-  while (current_entry!=(&FileSystemListHead))
+
+restart:
+  LIST_FOR_EACH(current,&FileSystemListHead, FILE_SYSTEM_OBJECT, Entry)
     {
-      current = CONTAINING_RECORD(current_entry,FILE_SYSTEM_OBJECT,Entry);
       if (current->DeviceObject->DeviceType != MatchingDeviceType)
 	{
-	  current_entry = current_entry->Flink;
 	  continue;
 	}
       /* If we are not allowed to mount this volume as a raw filesystem volume
@@ -294,8 +286,7 @@
 		return(Status);
 	      }
 	    ExAcquireResourceSharedLite(&FileSystemListLock,TRUE);
-	    current_entry = FileSystemListHead.Flink;
-	    continue;
+	    goto restart;
 
 	  case STATUS_SUCCESS:
 	    DeviceObject->Vpb->Flags = DeviceObject->Vpb->Flags |
@@ -306,7 +297,8 @@
 
 	  case STATUS_UNRECOGNIZED_VOLUME:
 	  default:
-	    current_entry = current_entry->Flink;
+       /* do nothing */
+       break;
 	}
     }
   ExReleaseResourceLite(&FileSystemListLock);
@@ -504,28 +496,26 @@
 VOID STDCALL
 IoUnregisterFileSystem(IN PDEVICE_OBJECT DeviceObject)
 {
-  PLIST_ENTRY current_entry;
   PFILE_SYSTEM_OBJECT current;
 
   DPRINT("IoUnregisterFileSystem(DeviceObject 0x%p)\n", DeviceObject);
 
   KeEnterCriticalRegion();
   ExAcquireResourceExclusiveLite(&FileSystemListLock, TRUE);
-  current_entry = FileSystemListHead.Flink;
-  while (current_entry!=(&FileSystemListHead))
+
+  LIST_FOR_EACH(current,&FileSystemListHead, FILE_SYSTEM_OBJECT,Entry)
     {
-      current = CONTAINING_RECORD(current_entry,FILE_SYSTEM_OBJECT,Entry);
       if (current->DeviceObject == DeviceObject)
 	{
-	  RemoveEntryList(current_entry);
+     RemoveEntryList(&current->Entry);
 	  ExFreePoolWithTag(current, TAG_FILE_SYSTEM);
 	  ExReleaseResourceLite(&FileSystemListLock);
 	  KeLeaveCriticalRegion();
 	  IopNotifyFileSystemChange(DeviceObject, FALSE);
 	  return;
 	}
-      current_entry = current_entry->Flink;
     }
+    
   ExReleaseResourceLite(&FileSystemListLock);
   KeLeaveCriticalRegion();
 }
@@ -595,17 +585,11 @@
 			  BOOLEAN DriverActive)
 {
   PFS_CHANGE_NOTIFY_ENTRY ChangeEntry;
-  PLIST_ENTRY Entry;
 
   KeAcquireGuardedMutex(&FsChangeNotifyListLock);
-  Entry = FsChangeNotifyListHead.Flink;
-  while (Entry != &FsChangeNotifyListHead)
+  LIST_FOR_EACH(ChangeEntry, &FsChangeNotifyListHead,FS_CHANGE_NOTIFY_ENTRY, FsChangeNotifyList) 
     {
-      ChangeEntry = CONTAINING_RECORD(Entry, FS_CHANGE_NOTIFY_ENTRY, FsChangeNotifyList);
-
       (ChangeEntry->FSDNotificationProc)(DeviceObject, DriverActive);
-
-      Entry = Entry->Flink;
     }
   KeReleaseGuardedMutex(&FsChangeNotifyListLock);
 }
@@ -646,24 +630,20 @@
 				 IN PDRIVER_FS_NOTIFICATION FSDNotificationProc)
 {
   PFS_CHANGE_NOTIFY_ENTRY ChangeEntry;
-  PLIST_ENTRY Entry;
 
-  Entry = FsChangeNotifyListHead.Flink;
-  while (Entry != &FsChangeNotifyListHead)
+  LIST_FOR_EACH(ChangeEntry, &FsChangeNotifyListHead, FS_CHANGE_NOTIFY_ENTRY, FsChangeNotifyList)
     {
-      ChangeEntry = CONTAINING_RECORD(Entry, FS_CHANGE_NOTIFY_ENTRY, FsChangeNotifyList);
       if (ChangeEntry->DriverObject == DriverObject &&
 	  ChangeEntry->FSDNotificationProc == FSDNotificationProc)
 	{
 	  KeAcquireGuardedMutex(&FsChangeNotifyListLock);
-	  RemoveEntryList(Entry);
+     RemoveEntryList(&ChangeEntry->FsChangeNotifyList);
 	  KeReleaseGuardedMutex(&FsChangeNotifyListLock);
 
-	  ExFreePoolWithTag(Entry, TAG_FS_CHANGE_NOTIFY);
+     ExFreePoolWithTag(ChangeEntry, TAG_FS_CHANGE_NOTIFY);
 	  return;
 	}
 
-      Entry = Entry->Flink;
     }
 }
 

Modified: trunk/reactos/ntoskrnl/io/irp.c
--- trunk/reactos/ntoskrnl/io/irp.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/io/irp.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -962,7 +962,6 @@
 STDCALL
 IoCancelThreadIo(PETHREAD Thread)
 {
-    PLIST_ENTRY IrpEntry;
     PIRP Irp;
     KIRQL OldIrql;
     ULONG Retries = 3000;
@@ -972,13 +971,8 @@
     OldIrql = KfRaiseIrql(APC_LEVEL);
 
     /* Start by cancelling all the IRPs in the current thread queue. */
-    for (IrpEntry = Thread->IrpList.Flink;
-        IrpEntry != &Thread->IrpList;
-        IrpEntry = IrpEntry->Flink)
+    LIST_FOR_EACH(Irp, &Thread->IrpList, IRP, ThreadListEntry)
     {
-       /* Get the IRP */
-        Irp = CONTAINING_RECORD(IrpEntry, IRP, ThreadListEntry);
-        
         /* Cancel it */
         IoCancelIrp(Irp);
     }

Modified: trunk/reactos/ntoskrnl/io/pnpnotify.c
--- trunk/reactos/ntoskrnl/io/pnpnotify.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/io/pnpnotify.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -184,7 +184,6 @@
 	IN PVOID EventCategoryData2)
 {
 	PPNP_NOTIFY_ENTRY ChangeEntry;
-	PLIST_ENTRY Entry;
 	PVOID NotificationStructure;
 	BOOLEAN CallCurrentEntry;
 
@@ -249,10 +248,8 @@
 	 * list to find those that meet some criteria.
 	 */
 
-	Entry = PnpNotifyListHead.Flink;
-	while (Entry != &PnpNotifyListHead)
+   LIST_FOR_EACH(ChangeEntry,&PnpNotifyListHead, PNP_NOTIFY_ENTRY, PnpNotifyList)
 	{
-		ChangeEntry = CONTAINING_RECORD(Entry, PNP_NOTIFY_ENTRY, PnpNotifyList);
 		CallCurrentEntry = FALSE;
 
 		switch (EventCategory)
@@ -294,7 +291,6 @@
 				ChangeEntry->Context);
 		}
 
-		Entry = Entry->Flink;
 	}
 	KeReleaseGuardedMutex(&PnpNotifyListLock);
 	ExFreePoolWithTag(NotificationStructure, TAG_PNP_NOTIFY);

Modified: trunk/reactos/ntoskrnl/io/pnproot.c
--- trunk/reactos/ntoskrnl/io/pnproot.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/io/pnproot.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -766,7 +766,6 @@
   PPNPROOT_PDO_DEVICE_EXTENSION PdoDeviceExtension;
   PPNPROOT_FDO_DEVICE_EXTENSION DeviceExtension;
   PDEVICE_RELATIONS Relations;
-  PLIST_ENTRY CurrentEntry;
   PPNPROOT_DEVICE Device;
   NTSTATUS Status;
   ULONG Size;
@@ -796,11 +795,8 @@
   Relations->Count = DeviceExtension->DeviceListCount;
 
   i = 0;
-  CurrentEntry = DeviceExtension->DeviceListHead.Flink;
-  while (CurrentEntry != &DeviceExtension->DeviceListHead)
+  LIST_FOR_EACH(Device,&DeviceExtension->DeviceListHead,PNPROOT_DEVICE, ListEntry) 
   {
-    Device = CONTAINING_RECORD(CurrentEntry, PNPROOT_DEVICE, ListEntry);
-
     if (!Device->Pdo)
     {
       /* Create a physical device object for the
@@ -894,8 +890,6 @@
     Relations->Objects[i] = Device->Pdo;
 
     i++;
-
-    CurrentEntry = CurrentEntry->Flink;
   }
 
   if (NT_SUCCESS(Status))

Modified: trunk/reactos/ntoskrnl/ke/apc.c
--- trunk/reactos/ntoskrnl/ke/apc.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/ke/apc.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -254,8 +254,6 @@
                  KPRIORITY PriorityBoost)
 {
     PKTHREAD Thread = Apc->Thread;
-    PLIST_ENTRY ApcListEntry;
-    PKAPC QueuedApc;
 
     KeAcquireSpinLockAtDpcLevel(&Thread->ApcQueueLock);
 
@@ -282,18 +280,15 @@
 
         DPRINT("Inserting Special APC %x for '%.16s' into the Queue\n", Apc, ((PETHREAD)Thread)->ThreadsProcess->ImageFileName);
 
-        for (ApcListEntry = Thread->ApcStatePointer[(int)Apc->ApcStateIndex]->ApcListHead[(int)Apc->ApcMode].Flink;
-             ApcListEntry != &Thread->ApcStatePointer[(int)Apc->ApcStateIndex]->ApcListHead[(int)Apc->ApcMode];
-             ApcListEntry = ApcListEntry->Flink) {
+        /* insert special apc before normal apcs (if any) but after the last special apc (fifo) */
+        InsertAscendingListFIFO(
+           &Thread->ApcStatePointer[(int)Apc->ApcStateIndex]->ApcListHead[(int)Apc->ApcMode], 
+           Apc,
+           KAPC, 
+           ApcListEntry, 
+           NormalRoutine /* sort field */
+           );
 
-            QueuedApc = CONTAINING_RECORD(ApcListEntry, KAPC, ApcListEntry);
-            if (Apc->NormalRoutine != NULL) break;
-        }
-
-        /* We found the first "Normal" APC, so write right before it */
-        ApcListEntry = ApcListEntry->Blink;
-        InsertHeadList(ApcListEntry, &Apc->ApcListEntry);
-
     } else {
 
         DPRINT("Inserting Normal APC %x for '%.16s' into the %x Queue\n", Apc, ((PETHREAD)Thread)->ThreadsProcess->ImageFileName, Apc->ApcMode);
@@ -469,25 +464,23 @@
 {
     KIRQL OldIrql;
     PKAPC Apc;
-    PLIST_ENTRY FirstEntry, CurrentEntry;
+    PLIST_ENTRY FirstEntry = NULL;
 
     /* Lock the Dispatcher Database and APC Queue */
     OldIrql = KeAcquireDispatcherDatabaseLock();
     KeAcquireSpinLockAtDpcLevel(&Thread->ApcQueueLock);
 
-    if (IsListEmpty(&Thread->ApcState.ApcListHead[PreviousMode])) {
-        FirstEntry = NULL;
-    } else {
+    /* mark all apcs as not-inserted */
+    LIST_FOR_EACH(Apc, &Thread->ApcState.ApcListHead[PreviousMode], KAPC, ApcListEntry) {
+       Apc->Inserted = FALSE;
+    }
+    
+    if (!IsListEmpty(&Thread->ApcState.ApcListHead[PreviousMode])) {
         FirstEntry = Thread->ApcState.ApcListHead[PreviousMode].Flink;
+        /* unlink list head from the rest of the list */
         RemoveEntryList(&Thread->ApcState.ApcListHead[PreviousMode]);
-        CurrentEntry = FirstEntry;
-        do {
-            Apc = CONTAINING_RECORD(CurrentEntry, KAPC, ApcListEntry);
-            Apc->Inserted = FALSE;
-            CurrentEntry = CurrentEntry->Flink;
-        } while (CurrentEntry != FirstEntry);
     }
-
+    
     /* Release the locks */
     KeReleaseSpinLockFromDpcLevel(&Thread->ApcQueueLock);
     KeReleaseDispatcherDatabaseLock(OldIrql);

Modified: trunk/reactos/ntoskrnl/ke/bug.c
--- trunk/reactos/ntoskrnl/ke/bug.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/ke/bug.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -252,7 +252,6 @@
 {
     PKBUGCHECK_CALLBACK_RECORD CurrentRecord;
     PLIST_ENTRY ListHead;
-    PLIST_ENTRY NextEntry;
 
     /* FIXME: Check Checksum and add support for WithReason Callbacks */
 
@@ -261,14 +260,8 @@
     if (ListHead->Flink && ListHead->Blink) {
 
         /* Loop the list */
-        NextEntry = ListHead->Flink;
-        while (NextEntry != ListHead) {
-
-            /* Get the Callback Record */
-            CurrentRecord = CONTAINING_RECORD(NextEntry,
-                                              KBUGCHECK_CALLBACK_RECORD,
-                                              Entry);
-
+        LIST_FOR_EACH(CurrentRecord, ListHead, KBUGCHECK_CALLBACK_RECORD, Entry)
+        {
             /* Make sure it's inserted */
             if (CurrentRecord->State == BufferInserted) {
 
@@ -278,9 +271,6 @@
                                                  CurrentRecord->Length);
                 CurrentRecord->State = BufferFinished;
             }
-
-            /* Move to next Entry */
-            NextEntry = NextEntry->Flink;
         }
     }
 }
@@ -297,7 +287,6 @@
     KIRQL OldIrql;
     BOOLEAN GotExtendedCrashInfo = FALSE;
     PVOID Address = 0;
-    PLIST_ENTRY CurrentEntry;
     PLDR_DATA_TABLE_ENTRY CurrentModule = NULL;
     extern LIST_ENTRY ModuleListHead;
 #if 0
@@ -322,14 +311,8 @@
         Address = (PVOID)Tf->Eip;
 
         /* Try to get information on the module */
-        CurrentEntry = ModuleListHead.Flink;
-        while (CurrentEntry != &ModuleListHead) 
+        LIST_FOR_EACH(CurrentModule, &ModuleListHead, LDR_DATA_TABLE_ENTRY, InLoadOrderModuleList)
         {
-            /* Get the current Section */
-            CurrentModule = CONTAINING_RECORD(CurrentEntry,
-                                              LDR_DATA_TABLE_ENTRY,
-                                              InLoadOrderModuleList);
-
             /* Check if this is the right one */
             if ((Address != NULL && (Address >= (PVOID)CurrentModule->DllBase &&
                  Address < (PVOID)((ULONG_PTR)CurrentModule->DllBase + CurrentModule->SizeOfImage)))) 
@@ -338,9 +321,6 @@
                 GotExtendedCrashInfo = TRUE;
                 break;
             }
-
-            /* Loop again */
-            CurrentEntry = CurrentEntry->Flink;
         }
     }
 

Modified: trunk/reactos/ntoskrnl/ke/kqueue.c
--- trunk/reactos/ntoskrnl/ke/kqueue.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/ke/kqueue.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -118,9 +118,9 @@
 
         /* Insert new entry after the last entry with SortKey less or equal to passed-in SortKey */
         InsertAscendingListFIFO(&DeviceQueue->DeviceListHead,
+                                DeviceQueueEntry,
                                 KDEVICE_QUEUE_ENTRY,
                                 DeviceListEntry,
-                                DeviceQueueEntry,
                                 SortKey);
         Inserted = TRUE;
     }
@@ -204,35 +204,26 @@
    } else {
 
         /* Find entry with SortKey greater than or equal to the passed-in SortKey */
-        ListEntry = DeviceQueue->DeviceListHead.Flink;
-        while (ListEntry != &DeviceQueue->DeviceListHead) {
-
-            /* Get Entry */
-            ReturnEntry = CONTAINING_RECORD(ListEntry,
-                                            KDEVICE_QUEUE_ENTRY,
-                                            DeviceListEntry);
-
+        LIST_FOR_EACH(ReturnEntry, &DeviceQueue->DeviceListHead, KDEVICE_QUEUE_ENTRY, DeviceListEntry) 
+        {
             /* Check if keys match */
-            if (ReturnEntry->SortKey >= SortKey) break;
-
-            /* Move to next item */
-            ListEntry = ListEntry->Flink;
+            if (ReturnEntry->SortKey >= SortKey) {
+               /* We found it, so just remove it */
+               RemoveEntryList(&ReturnEntry->DeviceListEntry);
+               break;
+            }
         }
 
         /* Check if we found something */
-        if (ListEntry == &DeviceQueue->DeviceListHead) {
+        if (!ReturnEntry) {
 
             /*  Not found, return the first entry */
             ListEntry = RemoveHeadList(&DeviceQueue->DeviceListHead);
             ReturnEntry = CONTAINING_RECORD(ListEntry,
                                             KDEVICE_QUEUE_ENTRY,
                                             DeviceListEntry);
-        } else {
+        } 
 
-            /* We found it, so just remove it */
-            RemoveEntryList(&ReturnEntry->DeviceListEntry);
-        }
-
         /* Set it as non-inserted */
         ReturnEntry->Inserted = FALSE;
     }

Modified: trunk/reactos/ntoskrnl/ke/kthread.c
--- trunk/reactos/ntoskrnl/ke/kthread.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/ke/kthread.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -76,7 +76,6 @@
 KiScanThreadList(KPRIORITY Priority,
                  KAFFINITY Affinity)
 {
-    PLIST_ENTRY current_entry;
     PKTHREAD current;
     ULONG Mask;
 
@@ -84,12 +83,8 @@
 
     if (PriorityListMask & Mask) {
 
-        current_entry = PriorityListHead[Priority].Flink;
+        LIST_FOR_EACH(current, &PriorityListHead[Priority], KTHREAD, WaitListEntry) {
 
-        while (current_entry != &PriorityListHead[Priority]) {
-
-            current = CONTAINING_RECORD(current_entry, KTHREAD, WaitListEntry);
-
             if (current->State != Ready) {
 
                 DPRINT1("%d/%d\n", &current, current->State);
@@ -102,8 +97,6 @@
                 KiRemoveFromThreadList(current);
                 return(current);
             }
-
-            current_entry = current_entry->Flink;
         }
     }
 
@@ -548,7 +541,6 @@
 KeFreezeAllThreads(PKPROCESS Process)
 {
     KIRQL OldIrql;
-    PLIST_ENTRY CurrentEntry;
     PKTHREAD Current;
     PKTHREAD CurrentThread = KeGetCurrentThread();
 
@@ -556,12 +548,8 @@
     OldIrql = KeAcquireDispatcherDatabaseLock();
 
     /* Loop the Process's Threads */
-    CurrentEntry = Process->ThreadListHead.Flink;
-    while (CurrentEntry != &Process->ThreadListHead)
+    LIST_FOR_EACH(Current, &Process->ThreadListHead, KTHREAD, ThreadListEntry)
     {
-        /* Get the Thread */
-        Current = CONTAINING_RECORD(CurrentEntry, KTHREAD, ThreadListEntry);
-
         /* Make sure it's not ours */
         if (Current == CurrentThread) continue;
 
@@ -575,8 +563,6 @@
                 Current->SuspendSemaphore.Header.SignalState--;
             }
         }
-
-        CurrentEntry = CurrentEntry->Flink;
     }
 
     /* Release the lock */
@@ -1456,8 +1442,8 @@
     if (Thread->ServiceTable != KeServiceDescriptorTableShadow) {
 
         /* We do. Initialize it and save the new table */
-        PsInitWin32Thread((PETHREAD)Thread);
         Thread->ServiceTable = KeServiceDescriptorTableShadow;
+        PsInitWin32Thread((PETHREAD)Thread);
     }
 }
 

Modified: trunk/reactos/ntoskrnl/ke/profile.c
--- trunk/reactos/ntoskrnl/ke/profile.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/ke/profile.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -53,17 +53,15 @@
 {
     KIRQL OldIrql;
     PKPROFILE_SOURCE_OBJECT SourceBuffer;
-    PKPROFILE_SOURCE_OBJECT Source = NULL;
     PKPROFILE_SOURCE_OBJECT CurrentSource;
     BOOLEAN FreeBuffer = TRUE;
     PKPROCESS ProfileProcess;
-    PLIST_ENTRY ListEntry;
 
     /* Allocate a buffer first, before we raise IRQL */
     SourceBuffer = ExAllocatePoolWithTag(NonPagedPool,
                                           sizeof(KPROFILE_SOURCE_OBJECT),
                                           TAG('P', 'r', 'o', 'f'));
-    RtlZeroMemory(Source, sizeof(KPROFILE_SOURCE_OBJECT));
+    RtlZeroMemory(SourceBuffer, sizeof(KPROFILE_SOURCE_OBJECT));
 
     /* Raise to PROFILE_LEVEL */
     KeRaiseIrql(PROFILE_LEVEL, &OldIrql);
@@ -90,32 +88,23 @@
         }
 
         /* Check if this type of profile (source) is already running */
-        for (ListEntry = KiProfileSourceListHead.Flink;
-             ListEntry != &KiProfileSourceListHead;
-             ListEntry = ListEntry->Flink) {
-
-            /* Get the Source Object */
-            CurrentSource = CONTAINING_RECORD(ListEntry,
-                                              KPROFILE_SOURCE_OBJECT,
-                                              ListEntry);
-
+        LIST_FOR_EACH(CurrentSource, &KiProfileSourceListHead, KPROFILE_SOURCE_OBJECT, ListEntry)
+        {
             /* Check if it's the same as the one being requested now */
             if (CurrentSource->Source == Profile->Source) {
-
-                Source = CurrentSource;
                 break;
             }
         }
 
         /* See if the loop found something */
-        if (!Source) {
+        if (!CurrentSource) {
 
             /* Nothing found, use our allocated buffer */
-            Source = SourceBuffer;
+            CurrentSource = SourceBuffer;
 
             /* Set up the Source Object */
-            Source->Source = Profile->Source;
-            InsertHeadList(&KiProfileSourceListHead, &Source->ListEntry);
+            CurrentSource->Source = Profile->Source;
+            InsertHeadList(&KiProfileSourceListHead, &CurrentSource->ListEntry);
 
             /* Don't free the pool later on */
             FreeBuffer = FALSE;
@@ -138,7 +127,6 @@
 KeStopProfile(PKPROFILE Profile)
 {
     KIRQL OldIrql;
-    PLIST_ENTRY ListEntry;
     PKPROFILE_SOURCE_OBJECT CurrentSource = NULL;
 
     /* Raise to PROFILE_LEVEL and acquire spinlock */
@@ -153,18 +141,15 @@
         Profile->Active = FALSE;
 
         /* Find the Source Object */
-        for (ListEntry = KiProfileSourceListHead.Flink;
-             CurrentSource->Source != Profile->Source;
-             ListEntry = ListEntry->Flink) {
-
-            /* Get the Source Object */
-            CurrentSource = CONTAINING_RECORD(ListEntry,
-                                              KPROFILE_SOURCE_OBJECT,
-                                              ListEntry);
+        LIST_FOR_EACH(CurrentSource, &KiProfileSourceListHead, KPROFILE_SOURCE_OBJECT, ListEntry) 
+        {
+            if (CurrentSource->Source == Profile->Source) {
+                /* Remove it */
+                RemoveEntryList(&CurrentSource->ListEntry);
+                break;   
+            }
         }
 
-        /* Remove it */
-        RemoveEntryList(&CurrentSource->ListEntry);
     }
 
     /* Lower IRQL */
@@ -240,14 +225,10 @@
 {
     PULONG BucketValue;
     PKPROFILE Profile;
-    PLIST_ENTRY NextEntry;
 
     /* Loop the List */
-    for (NextEntry = ListHead->Flink; NextEntry != ListHead; NextEntry = NextEntry->Flink) {
-
-        /* Get the Current Profile in the List */
-        Profile = CONTAINING_RECORD(NextEntry, KPROFILE, ListEntry);
-
+    LIST_FOR_EACH(Profile, ListHead, KPROFILE, ListEntry)
+    {
         /* Check if the source is good, and if it's within the range */
         if ((Profile->Source != Source) ||
             (TrapFrame->Eip < (ULONG_PTR)Profile->RegionStart) ||

Modified: trunk/reactos/ntoskrnl/ke/queue.c
--- trunk/reactos/ntoskrnl/ke/queue.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/ke/queue.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -182,17 +182,14 @@
     /* Loop until the queue is processed */
     while (TRUE) {
 
-        /* Get the Entry */
-        ListEntry = Queue->EntryListHead.Flink;
-
         /* Check if the counts are valid and if there is still a queued entry */
         if ((Queue->CurrentCount < Queue->MaximumCount) &&
-             (ListEntry != &Queue->EntryListHead)) {
+             !IsListEmpty(&Queue->EntryListHead)) {
 
             /* Remove the Entry and Save it */
             DPRINT("Removing Queue Entry. CurrentCount: %d, Maximum Count: %d\n",
                     Queue->CurrentCount, Queue->MaximumCount);
-            ListEntry = RemoveHeadList(&Queue->EntryListHead);
+            ListEntry = Queue->EntryListHead.Flink;
 
             /* Decrease the number of entries */
             Queue->Header.SignalState--;
@@ -328,7 +325,7 @@
 KeRundownQueue(IN PKQUEUE Queue)
 {
     PLIST_ENTRY EnumEntry;
-    PLIST_ENTRY FirstEntry;
+    PLIST_ENTRY FirstEntry = NULL;
     PKTHREAD Thread;
     KIRQL OldIrql;
 
@@ -337,19 +334,11 @@
     /* Get the Dispatcher Lock */
     OldIrql = KeAcquireDispatcherDatabaseLock();
 
-    /* Get the First Empty Entry */
-    FirstEntry = Queue->EntryListHead.Flink;
-
     /* Make sure the list is not empty */
-    if (FirstEntry == &Queue->EntryListHead) {
-
-        /* It is, so don't return anything */
-        FirstEntry = NULL;
-
-    } else {
-
+    if (!IsListEmpty(&Queue->EntryListHead)) 
+    {
         /* Remove it */
-        RemoveEntryList(&Queue->EntryListHead);
+        FirstEntry = RemoveHeadList(&Queue->EntryListHead);
     }
 
     /* Unlink threads and clear their Thread->Queue */

Modified: trunk/reactos/ntoskrnl/ke/timer.c
--- trunk/reactos/ntoskrnl/ke/timer.c	2005-09-26 22:06:31 UTC (rev 18112)
+++ trunk/reactos/ntoskrnl/ke/timer.c	2005-09-26 22:57:48 UTC (rev 18113)
@@ -217,7 +217,7 @@
                PVOID SystemArgument1,
                PVOID SystemArgument2)
[truncated at 1000 lines; 128 more skipped]