Skip to content

Commit

Permalink
Windows Driver: Optimize spinlock usage in CompleteIrpWorkItemRoutine
Browse files Browse the repository at this point in the history
Reduce the critical section protected by spinlock to only cover the list manipulation operation. Move the ActiveWorkItems counter decrement outside the spinlock using InterlockedDecrement, and separate event signaling from the locked section.
This change minimizes time spent at raised IRQL (DISPATCH_LEVEL) and reduces potential for lock contention.
  • Loading branch information
idrassi committed Nov 22, 2024
1 parent 9490336 commit 5a85c54
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions src/Driver/EncryptedIoQueue.c
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ static VOID CompleteIrpWorkItemRoutine(PDEVICE_OBJECT DeviceObject, PVOID Contex
PCOMPLETE_IRP_WORK_ITEM workItem = (PCOMPLETE_IRP_WORK_ITEM)Context;
EncryptedIoQueueItem* item = (EncryptedIoQueueItem * ) workItem->Item;
EncryptedIoQueue* queue = item->Queue;
KIRQL oldIrql;
UNREFERENCED_PARAMETER(DeviceObject);

__try
Expand All @@ -283,19 +284,14 @@ static VOID CompleteIrpWorkItemRoutine(PDEVICE_OBJECT DeviceObject, PVOID Contex
}
__finally
{
// Return the work item to the free list
KIRQL oldIrql;
KeAcquireSpinLock(&queue->WorkItemLock, &oldIrql);

// Decrement ActiveWorkItems
LONG activeWorkItems = InterlockedDecrement(&queue->ActiveWorkItems);

// If no active work items remain, signal the event
if (activeWorkItems == 0)
if (InterlockedDecrement(&queue->ActiveWorkItems) == 0)
{
KeSetEvent(&queue->NoActiveWorkItemsEvent, IO_NO_INCREMENT, FALSE);
}

// Return the work item to the free list
KeAcquireSpinLock(&queue->WorkItemLock, &oldIrql);
InsertTailList(&queue->FreeWorkItemsList, &workItem->ListEntry);
KeReleaseSpinLock(&queue->WorkItemLock, oldIrql);

Expand Down

0 comments on commit 5a85c54

Please sign in to comment.