/* * DoTheScreenSaver * * Check if scrensaver should be started and sends message to SAS window */ VOID FASTCALL DoTheScreenSaver(VOID) { LARGE_INTEGER TickCount; DWORD Test, TO; if (gspv.iScrSaverTimeout > 0) // Zero means Off. { KeQueryTickCount(&TickCount); Test = MsqCalculateMessageTime(&TickCount); Test = Test - LastInputTick; TO = 1000 * gspv.iScrSaverTimeout; if (Test > TO) { TRACE("Screensaver Message Start! Tick %lu Timeout %d \n", Test, gspv.iScrSaverTimeout); if (ppiScrnSaver) // We are or we are not the screensaver, prevent reentry... { if (!(ppiScrnSaver->W32PF_flags & W32PF_IDLESCREENSAVER)) { ppiScrnSaver->W32PF_flags |= W32PF_IDLESCREENSAVER; ERR("Screensaver is Idle\n"); } } else { PUSER_MESSAGE_QUEUE ForegroundQueue = IntGetFocusMessageQueue(); if (ForegroundQueue && ForegroundQueue->spwndActive) UserPostMessage(hwndSAS, WM_LOGONNOTIFY, LN_START_SCREENSAVE, 1); // lParam 1 == Secure else UserPostMessage(hwndSAS, WM_LOGONNOTIFY, LN_START_SCREENSAVE, 0); } } } }
// // How long has the system been up, in seconds. // LONGLONG Uptime() { LARGE_INTEGER Ticks; ULONG Increment = KeQueryTimeIncrement(); KeQueryTickCount(&Ticks); return (Ticks.QuadPart * Increment)/10000000L; }
//------------------------------------------------------------------------------ UINT32 target_getTickCount(void) { LARGE_INTEGER tickCount; KeQueryTickCount(&tickCount); return (UINT32)tickCount.QuadPart; }
NTSTATUS NTAPI MiCreatePebOrTeb(IN PEPROCESS Process, IN ULONG Size, OUT PULONG_PTR Base) { PETHREAD Thread = PsGetCurrentThread(); PMMVAD_LONG Vad; NTSTATUS Status; ULONG RandomCoeff; ULONG_PTR StartAddress, EndAddress; LARGE_INTEGER CurrentTime; TABLE_SEARCH_RESULT Result = TableFoundNode; PMMADDRESS_NODE Parent; /* Allocate a VAD */ Vad = ExAllocatePoolWithTag(NonPagedPool, sizeof(MMVAD_LONG), 'ldaV'); if (!Vad) return STATUS_NO_MEMORY; /* Setup the primary flags with the size, and make it commited, private, RW */ Vad->u.LongFlags = 0; Vad->u.VadFlags.CommitCharge = BYTES_TO_PAGES(Size); Vad->u.VadFlags.MemCommit = TRUE; Vad->u.VadFlags.PrivateMemory = TRUE; Vad->u.VadFlags.Protection = MM_READWRITE; Vad->u.VadFlags.NoChange = TRUE; /* Setup the secondary flags to make it a secured, writable, long VAD */ Vad->u2.LongFlags2 = 0; Vad->u2.VadFlags2.OneSecured = TRUE; Vad->u2.VadFlags2.LongVad = TRUE; Vad->u2.VadFlags2.ReadOnly = FALSE; /* Lock the process address space */ KeAcquireGuardedMutex(&Process->AddressCreationLock); /* Check if this is a PEB creation */ if (Size == sizeof(PEB)) { /* Start at the highest valid address */ StartAddress = (ULONG_PTR)MM_HIGHEST_VAD_ADDRESS + 1; /* Select the random coefficient */ KeQueryTickCount(&CurrentTime); CurrentTime.LowPart &= ((64 * _1KB) >> PAGE_SHIFT) - 1; if (CurrentTime.LowPart <= 1) CurrentTime.LowPart = 2; RandomCoeff = CurrentTime.LowPart << PAGE_SHIFT; /* Select the highest valid address minus the random coefficient */ StartAddress -= RandomCoeff; EndAddress = StartAddress + ROUND_TO_PAGES(Size) - 1; /* Try to find something below the random upper margin */ Result = MiFindEmptyAddressRangeDownTree(ROUND_TO_PAGES(Size), EndAddress, PAGE_SIZE, &Process->VadRoot, Base, &Parent); }
NTSTATUS PowerContextEndUse( _In_ PCDROM_DEVICE_EXTENSION DeviceExtension ) /*++ Routine Description: inidate that power context using is finished. Arguments: DeviceExtension - device context Return Value: NTSTATUS --*/ { NT_ASSERT(DeviceExtension->PowerContext.InUse); DeviceExtension->PowerContext.InUse = FALSE; KeQueryTickCount(&DeviceExtension->PowerContext.CompleteTime); return STATUS_SUCCESS; }
VOID LSCcbInitializeByCcb( IN PCCB OriCcb, IN PVOID pLurn, OUT PCCB Ccb ) { ASSERT(Ccb); RtlCopyMemory( Ccb, OriCcb, sizeof(CCB) ); // Stack locations RtlZeroMemory(Ccb->CcbStackLocation, (NR_MAX_CCB_STACKLOCATION) * sizeof(CCB_STACKLOCATION)); Ccb->CcbCurrentStackLocationIndex = NR_MAX_CCB_STACKLOCATION - 1; Ccb->CcbCurrentStackLocation = Ccb->CcbStackLocation + (NR_MAX_CCB_STACKLOCATION - 1); Ccb->CcbCurrentStackLocation->Lurn = pLurn; InitializeListHead(&Ccb->ListEntry); KeInitializeSpinLock(&Ccb->CcbSpinLock); KeQueryTickCount(&Ccb->CreateTime); Ccb->AssociateCount = 0; Ccb->CompletionEvent = NULL; Ccb->Flags = 0; Ccb->CcbStatusFlags = 0; }
NTSTATUS NTAPI KsecGenRandom( PVOID Buffer, SIZE_T Length) { LARGE_INTEGER TickCount; ULONG i, RandomValue; PULONG P; /* Try to generate a more random seed */ KeQueryTickCount(&TickCount); KsecRandomSeed ^= _rotl(TickCount.LowPart, (KsecRandomSeed % 23)); P = Buffer; for (i = 0; i < Length / sizeof(ULONG); i++) { P[i] = RtlRandomEx(&KsecRandomSeed); } Length &= (sizeof(ULONG) - 1); if (Length > 0) { RandomValue = RtlRandomEx(&KsecRandomSeed); RtlCopyMemory(&P[i], &RandomValue, Length); } return STATUS_SUCCESS; }
VOID DokanCheckKeepAlive(__in PDokanDCB Dcb) { LARGE_INTEGER tickCount; ULONG mounted; // DDbgPrint("==> DokanCheckKeepAlive\n"); KeEnterCriticalRegion(); KeQueryTickCount(&tickCount); ExAcquireResourceSharedLite(&Dcb->Resource, TRUE); if (Dcb->TickCount.QuadPart < tickCount.QuadPart) { mounted = Dcb->Mounted; ExReleaseResourceLite(&Dcb->Resource); DDbgPrint(" Timeout, umount\n"); if (!mounted) { // not mounted KeLeaveCriticalRegion(); return; } DokanUnmount(Dcb); } else { ExReleaseResourceLite(&Dcb->Resource); } KeLeaveCriticalRegion(); // DDbgPrint("<== DokanCheckKeepAlive\n"); }
VOID otLwfEventProcessingIndicateNewWaitTime( _In_ PMS_FILTER pFilter, _In_ ULONG waitTime ) { BOOLEAN FireUpdateEvent = TRUE; // Cancel previous timer if (ExCancelTimer(pFilter->EventHighPrecisionTimer, NULL)) { pFilter->EventTimerState = OT_EVENT_TIMER_NOT_RUNNING; } if (waitTime == (ULONG)(-1)) { // Ignore if we are already stopped if (pFilter->NextAlarmTickCount.QuadPart == 0) return; pFilter->NextAlarmTickCount.QuadPart = 0; } else { if (waitTime == 0) { #ifdef DEBUG_TIMING LogInfo(DRIVER_DEFAULT, "Event processing updating to fire timer immediately."); #endif pFilter->EventTimerState = OT_EVENT_TIMER_FIRED; pFilter->NextAlarmTickCount.QuadPart = 0; } else if (waitTime * 10000ll < (KeQueryTimeIncrement() - 30000)) { #ifdef DEBUG_TIMING LogInfo(DRIVER_DEFAULT, "Event processing starting high precision timer for %u ms.", waitTime); #endif pFilter->EventTimerState = OT_EVENT_TIMER_RUNNING; pFilter->NextAlarmTickCount.QuadPart = 0; FireUpdateEvent = FALSE; ExSetTimer(pFilter->EventHighPrecisionTimer, waitTime * -10000ll, 0, NULL); } else { ULONG TickWaitTime = (waitTime * 10000ll) / KeQueryTimeIncrement(); if (TickWaitTime == 0) TickWaitTime = 1; #ifdef DEBUG_TIMING LogInfo(DRIVER_DEFAULT, "Event processing updating wait ticks to %u.", TickWaitTime); #endif // Update the time to be 'waitTime' ms from 'now', saved in TickCounts KeQueryTickCount(&pFilter->NextAlarmTickCount); pFilter->NextAlarmTickCount.QuadPart += TickWaitTime; } } // Indicate event to worker thread to update the wait time KeSetEvent(&pFilter->EventWorkerThreadWaitTimeUpdated, 0, FALSE); }
VOID DokanUpdateTimeout( __out PLARGE_INTEGER TickCount, __in ULONG Timeout ) { KeQueryTickCount(TickCount); TickCount->QuadPart += Timeout * 1000 * 10 / KeQueryTimeIncrement(); }
VOID DokanCheckKeepAlive( PDEVICE_EXTENSION DeviceExtension) { LARGE_INTEGER tickCount; ULONG eventLength; PEVENT_CONTEXT eventContext; ULONG mounted; //DDbgPrint("==> DokanCheckKeepAlive\n"); KeQueryTickCount(&tickCount); ExAcquireResourceSharedLite(&DeviceExtension->Resource, TRUE); if ( (tickCount.QuadPart - DeviceExtension->TickCount.QuadPart) * KeQueryTimeIncrement() > DOKAN_KEEPALIVE_TIMEOUT * 10000 * 1000) { mounted = DeviceExtension->Mounted; ExReleaseResourceLite(&DeviceExtension->Resource); DDbgPrint(" Force to umount\n"); if (!mounted) { // not mounted return; } eventLength = sizeof(EVENT_CONTEXT); eventContext = ExAllocatePool(eventLength); if (eventContext == NULL) { ;//STATUS_INSUFFICIENT_RESOURCES; DokanEventRelease(DeviceExtension->DeviceObject); return; } RtlZeroMemory(eventContext, eventLength); eventContext->Length = eventLength; // set drive letter eventContext->Flags = mounted; DokanEventNotification(&DeviceExtension->Global->NotifyService, eventContext); DokanEventRelease(DeviceExtension->DeviceObject); } else { ExReleaseResourceLite(&DeviceExtension->Resource); } //DDbgPrint("<== DokanCheckKeepAlive\n"); }
/* * IntLastInputTick * * Updates or gets last input tick count */ static DWORD FASTCALL IntLastInputTick(BOOL bUpdate) { if (bUpdate) { LARGE_INTEGER TickCount; KeQueryTickCount(&TickCount); LastInputTick = MsqCalculateMessageTime(&TickCount); if (gpsi) gpsi->dwLastRITEventTickCount = LastInputTick; } return LastInputTick; }
static __inline VOID LsuCurrentTime( PLARGE_INTEGER CurrentTime ){ ULONG Tick; KeQueryTickCount(CurrentTime); Tick = KeQueryTimeIncrement(); CurrentTime->QuadPart = CurrentTime->QuadPart * Tick; }
uint64_t vcos_getmicrosecs64_internal(void) { #ifdef WIN32_KERN LARGE_INTEGER time; KeQueryTickCount(&time); return time.QuadPart; #else // QuerryPerformanceCounter if require beter accuracy return GetTickCount64(); #endif }
/*! * \see http://blogs.msdn.com/b/michael_howard/archive/2005/01/14/353379.aspx */ NTSTATUS NTAPI KsecGatherEntropyData( PKSEC_ENTROPY_DATA EntropyData) { MD4_CTX Md4Context; PTEB Teb; PPEB Peb; PWSTR String; SIZE_T ReturnLength; NTSTATUS Status; /* Query some generic values */ EntropyData->CurrentProcessId = PsGetCurrentProcessId(); EntropyData->CurrentThreadId = PsGetCurrentThreadId(); KeQueryTickCount(&EntropyData->TickCount); KeQuerySystemTime(&EntropyData->SystemTime); EntropyData->PerformanceCounter = KeQueryPerformanceCounter( &EntropyData->PerformanceFrequency); /* Check if we have a TEB/PEB for the process environment */ Teb = PsGetCurrentThread()->Tcb.Teb; if (Teb != NULL) { Peb = Teb->ProcessEnvironmentBlock; /* Initialize the MD4 context */ MD4Init(&Md4Context); _SEH2_TRY { /* Get the end of the environment */ String = Peb->ProcessParameters->Environment; while (*String) { String += wcslen(String) + 1; } /* Update the MD4 context from the environment data */ MD4Update(&Md4Context, (PUCHAR)Peb->ProcessParameters->Environment, (ULONG)((PUCHAR)String - (PUCHAR)Peb->ProcessParameters->Environment)); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { /* Simply ignore the exception */ } _SEH2_END; /* Finalize and copy the MD4 hash */ MD4Final(&Md4Context); RtlCopyMemory(&EntropyData->EnvironmentHash, Md4Context.digest, 16); }
// // get the current system clock // static __inline LARGE_INTEGER CurrentTime(VOID){ LARGE_INTEGER Time; ULONG Tick; KeQueryTickCount(&Time); Tick = KeQueryTimeIncrement(); Time.QuadPart = Time.QuadPart * Tick; return Time; }
ULONGLONG APIENTRY EngGetTickCount(VOID) { ULONG Multiplier; LARGE_INTEGER TickCount; /* Get the multiplier and current tick count */ KeQueryTickCount(&TickCount); Multiplier = SharedUserData->TickCountMultiplier; /* Convert to milliseconds and return */ return (Int64ShrlMod32(UInt32x32To64(Multiplier, TickCount.LowPart), 24) + (Multiplier * (TickCount.HighPart << 8))); }
int RTLogBackdoorPrintf1(const char *pszFormat, ...) { va_list args; LARGE_INTEGER time; KeQueryTickCount(&time); RTLogBackdoorPrintf("T=%RX64 ", time.QuadPart); va_start(args, pszFormat); RTLogFormatV(rtLogBackdoorOutput, NULL, pszFormat, args); va_end(args); return 0; }
/*----------------------------------------------------------------------------*/ int zrtp_add_system_state(zrtp_global_t* zrtp, MD_CTX *ctx) { LARGE_INTEGER li1; LARGE_INTEGER li2; ULONG ul1; ULONG ul2; ULONGLONG ull; PKTHREAD thread; static int tsc_ok = 1; /* * WARNING! * Of course it's not a real size of entropy added to the context. It's very * difficult to compute the size of real random data and estimate its quality. * This value means: size of maximum possible random data which this function can provide. */ static int entropy_length = sizeof(LARGE_INTEGER)*2 + sizeof(PKTHREAD) + sizeof(ULONG)*2 + sizeof(LARGE_INTEGER)*2 + sizeof(ULONG)*2; li2 = KeQueryPerformanceCounter(&li1); MD_Update(ctx, &li1, sizeof(LARGE_INTEGER)); MD_Update(ctx, &li2, sizeof(LARGE_INTEGER)); ull = KeQueryInterruptTime(); MD_Update(ctx, &ull, sizeof(ULONGLONG)); thread = KeGetCurrentThread(); MD_Update(ctx, &thread, sizeof(PKTHREAD)); ul2 = KeQueryRuntimeThread(thread, &ul1); MD_Update(ctx, &ul1, sizeof(ULONG)); MD_Update(ctx, &ul2, sizeof(ULONG)); KeQuerySystemTime(&li1); MD_Update(ctx, &li1, sizeof(LARGE_INTEGER)); KeQueryTickCount(&li1); MD_Update(ctx, &li1, sizeof(LARGE_INTEGER)); if (tsc_ok) { __try { ull = _RDTSC(); MD_Update(ctx, &ull, sizeof(ULONGLONG)); } __except(EXCEPTION_EXECUTE_HANDLER) { tsc_ok = 0; } } return entropy_length; }
uint32_t systime(void) { LARGE_INTEGER time; uint32_t timeIncrement100ns; uint32_t time0_1ms; uint32_t result; timeIncrement100ns = KeQueryTimeIncrement (); time0_1ms = timeIncrement100ns / 1000; KeQueryTickCount(&time); result = time.LowPart * time0_1ms; // dbgpl(NULL, "chantara systime = 0x%x \n", result); return (result); // the unit must be 0.1ms }
static __inline LARGE_INTEGER LMCurrentTime (VOID) { LARGE_INTEGER currentCount; ULONG interval; LARGE_INTEGER time; KeQueryTickCount(¤tCount); interval = KeQueryTimeIncrement(); time.QuadPart = currentCount.QuadPart * interval; return time; }
VOID LSCcbInitializeInSrb( IN PSCSI_REQUEST_BLOCK Srb, IN PVOID HwDeviceExtension, OUT PCCB *ccb ) { PCCB Ccb; Ccb = (PCCB)Srb->SrbExtension; ASSERT(Ccb); RtlZeroMemory( Ccb, sizeof(CCB) ); Ccb->Srb = Srb; ASSERT(Srb->CdbLength <= MAXIMUM_CDB_SIZE); Ccb->Type = LSSTRUC_TYPE_CCB; Ccb->Length = sizeof(CCB); Ccb->CdbLength = (UCHAR)Srb->CdbLength; RtlCopyMemory(Ccb->Cdb, Srb->Cdb, Ccb->CdbLength); Ccb->OperationCode = Srb->Function; Ccb->LurId[0] = Srb->PathId; // offset 5 Ccb->LurId[1] = Srb->TargetId; // offset 6 Ccb->LurId[2] = Srb->Lun; // offset 7 Ccb->DataBufferLength = Srb->DataTransferLength; // offset 10 Ccb->DataBuffer = Srb->DataBuffer; // offset 18 Ccb->AbortSrb = Srb->NextSrb; Ccb->HwDeviceExtension = HwDeviceExtension; Ccb->CcbCurrentStackLocationIndex = NR_MAX_CCB_STACKLOCATION - 1; Ccb->CcbCurrentStackLocation = Ccb->CcbStackLocation + (NR_MAX_CCB_STACKLOCATION - 1); Ccb->SenseBuffer = Srb->SenseInfoBuffer; Ccb->SenseDataLength = Srb->SenseInfoBufferLength; Ccb->Flags = 0; KeInitializeSpinLock(&Ccb->CcbSpinLock); InitializeListHead(&Ccb->ListEntry); KeQueryTickCount(&Ccb->CreateTime); Ccb->AssociateCount = 0; Ccb->CompletionEvent = NULL; *ccb = Ccb; }
VOID DokanCheckKeepAlive( __in PDokanDCB Dcb ) { LARGE_INTEGER tickCount; // ULONG eventLength; // PEVENT_CONTEXT eventContext; ULONG mounted; // PDokanVCB vcb = Dcb->Vcb; //DDbgPrint("==> DokanCheckKeepAlive"); KeEnterCriticalRegion(); KeQueryTickCount(&tickCount); ExAcquireResourceSharedLite(&Dcb->Resource, TRUE); if (Dcb->TickCount.QuadPart < tickCount.QuadPart) { mounted = Dcb->Mounted; ExReleaseResourceLite(&Dcb->Resource); DDbgPrint(" Timeout, force to umount"); if (!mounted) { // not mounted KeLeaveCriticalRegion(); return; } DokanUnmount(Dcb); } else { ExReleaseResourceLite(&Dcb->Resource); } KeLeaveCriticalRegion(); //DDbgPrint("<== DokanCheckKeepAlive"); }
NTSTATUS PowerContextBeginUse( _In_ PCDROM_DEVICE_EXTENSION DeviceExtension ) /*++ Routine Description: initialize fields in power context Arguments: DeviceExtension - device context Return Value: NTSTATUS --*/ { NTSTATUS status = STATUS_SUCCESS; NT_ASSERT(!DeviceExtension->PowerContext.InUse); DeviceExtension->PowerContext.InUse = TRUE; DeviceExtension->PowerContext.RetryCount = MAXIMUM_RETRIES; DeviceExtension->PowerContext.RetryIntervalIn100ns = 0; KeQueryTickCount(&DeviceExtension->PowerContext.StartTime); RtlZeroMemory(&(DeviceExtension->PowerContext.Options), sizeof(DeviceExtension->PowerContext.Options)); RtlZeroMemory(&(DeviceExtension->PowerContext.PowerChangeState), sizeof(DeviceExtension->PowerContext.PowerChangeState)); status = PowerContextReuseRequest(DeviceExtension); RequestClearSendTime(DeviceExtension->PowerContext.PowerRequest); return status; }
void rnd_reseed_now() { seed_data seed; KeQuerySystemTime(&seed.seed20); seed.seed1 = PsGetCurrentProcess(); seed.seed2 = PsGetCurrentProcessId(); seed.seed3 = KeGetCurrentThread(); seed.seed4 = PsGetCurrentThreadId(); seed.seed5 = KeGetCurrentProcessorNumber(); seed.seed6 = KeQueryInterruptTime(); seed.seed10 = KeQueryPerformanceCounter(NULL); seed.seed11 = __rdtsc(); seed.seed12 = ExGetPreviousMode(); seed.seed14 = IoGetTopLevelIrp(); seed.seed15 = MmQuerySystemSize(); seed.seed24 = KeGetCurrentIrql(); if (KeGetCurrentIrql() == PASSIVE_LEVEL) { seed.seed7 = KeQueryPriorityThread(seed.seed3); seed.seed17 = ExUuidCreate(&seed.seed18); seed.seed19 = RtlRandom(&seed.seed8); } if (KeGetCurrentIrql() <= APC_LEVEL) { seed.seed13 = IoGetInitialStack(); seed.seed16 = PsGetProcessExitTime(); IoGetStackLimits(&seed.seed22, &seed.seed23); } KeQueryTickCount(&seed.seed21); rnd_add_buff(&seed, sizeof(seed)); /* Prevent leaks */ zeroauto(&seed, sizeof(seed)); }
NTSTATUS ReleaseTimeoutPendingIrp(__in PDokanDCB Dcb) { KIRQL oldIrql; PLIST_ENTRY thisEntry, nextEntry, listHead; PIRP_ENTRY irpEntry; LARGE_INTEGER tickCount; LIST_ENTRY completeList; PIRP irp; DDbgPrint("==> ReleaseTimeoutPendingIRP\n"); InitializeListHead(&completeList); ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL); KeAcquireSpinLock(&Dcb->PendingIrp.ListLock, &oldIrql); // when IRP queue is empty, there is nothing to do if (IsListEmpty(&Dcb->PendingIrp.ListHead)) { KeReleaseSpinLock(&Dcb->PendingIrp.ListLock, oldIrql); DDbgPrint(" IrpQueue is Empty\n"); return STATUS_SUCCESS; } KeQueryTickCount(&tickCount); // search timeout IRP through pending IRP list listHead = &Dcb->PendingIrp.ListHead; for (thisEntry = listHead->Flink; thisEntry != listHead; thisEntry = nextEntry) { nextEntry = thisEntry->Flink; irpEntry = CONTAINING_RECORD(thisEntry, IRP_ENTRY, ListEntry); // this IRP is NOT timeout yet if (tickCount.QuadPart < irpEntry->TickCount.QuadPart) { break; } RemoveEntryList(thisEntry); DDbgPrint(" timeout Irp #%X\n", irpEntry->SerialNumber); irp = irpEntry->Irp; if (irp == NULL) { // this IRP has already been canceled ASSERT(irpEntry->CancelRoutineFreeMemory == FALSE); DokanFreeIrpEntry(irpEntry); continue; } // this IRP is not canceled yet if (IoSetCancelRoutine(irp, NULL) == NULL) { // Cancel routine will run as soon as we release the lock InitializeListHead(&irpEntry->ListEntry); irpEntry->CancelRoutineFreeMemory = TRUE; continue; } // IrpEntry is saved here for CancelRoutine // Clear it to prevent to be completed by CancelRoutine twice irp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_IRP_ENTRY] = NULL; InsertTailList(&completeList, &irpEntry->ListEntry); } if (IsListEmpty(&Dcb->PendingIrp.ListHead)) { KeClearEvent(&Dcb->PendingIrp.NotEmpty); } KeReleaseSpinLock(&Dcb->PendingIrp.ListLock, oldIrql); while (!IsListEmpty(&completeList)) { listHead = RemoveHeadList(&completeList); irpEntry = CONTAINING_RECORD(listHead, IRP_ENTRY, ListEntry); irp = irpEntry->Irp; DokanCompleteIrpRequest(irp, STATUS_INSUFFICIENT_RESOURCES, 0); DokanFreeIrpEntry(irpEntry); } DDbgPrint("<== ReleaseTimeoutPendingIRP\n"); return STATUS_SUCCESS; }
BOOL ShareMemKImp::InitializeShareMem(HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes, DWORD flProtect, DWORD dwMaximumSize, LPCWSTR lpName, DWORD dwDesiredAccess, ShareMemClassInit* lpInitialization, void* lpUserContext) { UninitializeShareMem(); DWORD size; size = dwMaximumSize + sizeof(ShareMemHeader); if (size < dwMaximumSize) return FALSE; UNICODE_STRING us; RtlInitUnicodeString(&us, lpName); OBJECT_ATTRIBUTES attr; InitializeObjectAttributes(&attr, &us, OBJ_OPENIF, NULL, NULL); LARGE_INTEGER li; li.QuadPart = size; NTSTATUS status; status = ZwCreateSection(&m_hMapSect, READ_CONTROL|WRITE_DAC|dwDesiredAccess, &attr, &li, flProtect, SEC_COMMIT, hFile); BOOLEAN init; init = status != STATUS_SUCCESS ? FALSE : TRUE; if (m_hMapSect) { SIZE_T v_size; v_size = 0; status = ZwMapViewOfSection(m_hMapSect, ZwCurrentProcess(), &m_hMapView, 0, size, NULL, &v_size, ViewUnmap, 0, PAGE_READWRITE); if (m_hMapView) { m_hMapSize = dwMaximumSize; ShareMemHeader* smh; smh = (ShareMemHeader*)m_hMapView; if (init) { LARGE_INTEGER tick; KeQueryTickCount(&tick); RtlStringCchPrintfW(smh->m_LockName, sizeof(smh->m_LockName), L"K-%08x-%08x-%08x", PsGetCurrentProcessId(), PsGetCurrentThreadId(), tick.LowPart); if (lpInitialization) smh->m_bResult = lpInitialization(this, lpUserContext); else smh->m_bResult = TRUE; smh->m_bInitialized = TRUE; } else while(1) if (smh->m_bInitialized) break; return smh->m_bResult; } } return FALSE; }
/*++//////////////////////////////////////////////////////////////////////////// ClassAcquireRemoveLockEx() Routine Description: This routine is called to acquire the remove lock on the device object. While the lock is held, the caller can assume that no pending pnp REMOVE requests will be completed. The lock should be acquired immediately upon entering a dispatch routine. It should also be acquired before creating any new reference to the device object if there's a chance of releasing the reference before the new one is done. This routine will return TRUE if the lock was successfully acquired or FALSE if it cannot be because the device object has already been removed. Arguments: DeviceObject - the device object to lock Tag - Used for tracking lock allocation and release. If an irp is specified when acquiring the lock then the same Tag must be used to release the lock before the Tag is completed. Return Value: The value of the IsRemoved flag in the device extension. If this is non-zero then the device object has received a Remove irp and non-cleanup IRP's should fail. If the value is REMOVE_COMPLETE, the caller should not even release the lock. --*/ ULONG NTAPI ClassAcquireRemoveLockEx( IN PDEVICE_OBJECT DeviceObject, IN OPTIONAL PVOID Tag, IN PCSTR File, IN ULONG Line ) { PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension; LONG lockValue; // // Grab the remove lock // lockValue = InterlockedIncrement(&commonExtension->RemoveLock); #if DBG DebugPrint((ClassDebugRemoveLock, "ClassAcquireRemoveLock: " "Acquired for Object %p & irp %p - count is %d\n", DeviceObject, Tag, lockValue)); ASSERTMSG("ClassAcquireRemoveLock - lock value was negative : ", (lockValue > 0)); ASSERTMSG("RemoveLock increased to meet LockHighWatermark", ((LockHighWatermark == 0) || (lockValue != LockHighWatermark))); if (commonExtension->IsRemoved != REMOVE_COMPLETE){ PREMOVE_TRACKING_BLOCK trackingBlock; trackingBlock = ExAllocatePool(NonPagedPool, sizeof(REMOVE_TRACKING_BLOCK)); if(trackingBlock == NULL) { KIRQL oldIrql; KeAcquireSpinLock(&commonExtension->RemoveTrackingSpinlock, &oldIrql); commonExtension->RemoveTrackingUntrackedCount++; DebugPrint((ClassDebugWarning, ">>>>>ClassAcquireRemoveLock: " "Cannot track Tag %p - currently %d untracked requsts\n", Tag, commonExtension->RemoveTrackingUntrackedCount)); KeReleaseSpinLock(&commonExtension->RemoveTrackingSpinlock, oldIrql); } else { PREMOVE_TRACKING_BLOCK *removeTrackingList = (PREMOVE_TRACKING_BLOCK*)&commonExtension->RemoveTrackingList; KIRQL oldIrql; trackingBlock->Tag = Tag; trackingBlock->File = File; trackingBlock->Line = Line; KeQueryTickCount((&trackingBlock->TimeLocked)); KeAcquireSpinLock(&commonExtension->RemoveTrackingSpinlock, &oldIrql); while(*removeTrackingList != NULL) { if((*removeTrackingList)->Tag > Tag) { break; } if((*removeTrackingList)->Tag == Tag) { DebugPrint((ClassDebugError, ">>>>>ClassAcquireRemoveLock: " "already tracking Tag %p\n", Tag)); DebugPrint((ClassDebugError, ">>>>>ClassAcquireRemoveLock: " "acquired in file %s on line %d\n", (*removeTrackingList)->File, (*removeTrackingList)->Line)); ASSERT(FALSE); } removeTrackingList = &((*removeTrackingList)->NextBlock); } trackingBlock->NextBlock = *removeTrackingList; *removeTrackingList = trackingBlock; KeReleaseSpinLock(&commonExtension->RemoveTrackingSpinlock, oldIrql); } } #endif return (commonExtension->IsRemoved); }
/*++//////////////////////////////////////////////////////////////////////////// ClassReleaseRemoveLock() Routine Description: This routine is called to release the remove lock on the device object. It must be called when finished using a previously locked reference to the device object. If an Tag was specified when acquiring the lock then the same Tag must be specified when releasing the lock. When the lock count reduces to zero, this routine will signal the waiting remove Tag to delete the device object. As a result the DeviceObject pointer should not be used again once the lock has been released. Arguments: DeviceObject - the device object to lock Tag - The irp (if any) specified when acquiring the lock. This is used for lock tracking purposes Return Value: none --*/ VOID NTAPI ClassReleaseRemoveLock( IN PDEVICE_OBJECT DeviceObject, IN OPTIONAL PIRP Tag ) { PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension; LONG lockValue; #if DBG PREMOVE_TRACKING_BLOCK *listEntry = (PREMOVE_TRACKING_BLOCK*)&commonExtension->RemoveTrackingList; BOOLEAN found = FALSE; LONGLONG maxCount; BOOLEAN isRemoved = (commonExtension->IsRemoved == REMOVE_COMPLETE); KIRQL oldIrql; if(isRemoved) { DBGTRAP(("ClassReleaseRemoveLock: REMOVE_COMPLETE set; this should never happen")); InterlockedDecrement(&(commonExtension->RemoveLock)); return; } // // Check the tick count and make sure this thing hasn't been locked // for more than MaxLockedMinutes. // maxCount = KeQueryTimeIncrement() * 10; // microseconds maxCount *= 1000; // milliseconds maxCount *= 1000; // seconds maxCount *= 60; // minutes maxCount *= MaxLockedMinutes; DebugPrint((ClassDebugRemoveLock, "ClassReleaseRemoveLock: " "maxCount = %0I64x\n", maxCount)); KeAcquireSpinLock(&commonExtension->RemoveTrackingSpinlock, &oldIrql); while(*listEntry != NULL) { PREMOVE_TRACKING_BLOCK block; LARGE_INTEGER difference; block = *listEntry; KeQueryTickCount((&difference)); difference.QuadPart -= block->TimeLocked.QuadPart; DebugPrint((ClassDebugRemoveLock, "ClassReleaseRemoveLock: " "Object %p (tag %p) locked for %I64d ticks\n", DeviceObject, block->Tag, difference.QuadPart)); if(difference.QuadPart >= maxCount) { DebugPrint((ClassDebugError, ">>>>>ClassReleaseRemoveLock: " "Object %p (tag %p) locked for %I64d ticks - TOO LONG\n", DeviceObject, block->Tag, difference.QuadPart)); DebugPrint((ClassDebugError, ">>>>>ClassReleaseRemoveLock: " "Lock acquired in file %s on line %d\n", block->File, block->Line)); ASSERT(FALSE); } if((found == FALSE) && ((*listEntry)->Tag == Tag)) { *listEntry = block->NextBlock; ExFreePool(block); found = TRUE; } else { listEntry = &((*listEntry)->NextBlock); } } if(!found) { if(commonExtension->RemoveTrackingUntrackedCount == 0) { DebugPrint((ClassDebugError, ">>>>>ClassReleaseRemoveLock: " "Couldn't find Tag %p in the lock tracking list\n", Tag)); ASSERT(FALSE); } else { DebugPrint((ClassDebugError, ">>>>>ClassReleaseRemoveLock: " "Couldn't find Tag %p in the lock tracking list - " "may be one of the %d untracked requests still " "outstanding\n", Tag, commonExtension->RemoveTrackingUntrackedCount)); commonExtension->RemoveTrackingUntrackedCount--; ASSERT(commonExtension->RemoveTrackingUntrackedCount >= 0); } } KeReleaseSpinLock(&commonExtension->RemoveTrackingSpinlock, oldIrql); #endif lockValue = InterlockedDecrement(&commonExtension->RemoveLock); DebugPrint((ClassDebugRemoveLock, "ClassReleaseRemoveLock: " "Released for Object %p & irp %p - count is %d\n", DeviceObject, Tag, lockValue)); ASSERT(lockValue >= 0); ASSERTMSG("RemoveLock decreased to meet LockLowWatermark", ((LockLowWatermark == 0) || !(lockValue == LockLowWatermark))); if(lockValue == 0) { ASSERT(commonExtension->IsRemoved); // // The device needs to be removed. Signal the remove event // that it's safe to go ahead. // DebugPrint((ClassDebugRemoveLock, "ClassReleaseRemoveLock: " "Release for object %p & irp %p caused lock to go to zero\n", DeviceObject, Tag)); KeSetEvent(&commonExtension->RemoveEvent, IO_NO_INCREMENT, FALSE); } return; }
/* * @implemented */ NTSTATUS NTAPI IoAcquireRemoveLockEx(IN PIO_REMOVE_LOCK RemoveLock, IN OPTIONAL PVOID Tag, IN LPCSTR File, IN ULONG Line, IN ULONG RemlockSize) { KIRQL OldIrql; LONG LockValue; PIO_REMOVE_LOCK_TRACKING_BLOCK TrackingBlock; PEXTENDED_IO_REMOVE_LOCK Lock = (PEXTENDED_IO_REMOVE_LOCK)RemoveLock; /* Increase the lock count */ LockValue = InterlockedIncrement(&(Lock->Common.IoCount)); ASSERT(LockValue > 0); if (!Lock->Common.Removed) { /* Check what kind of lock this is */ if (RemlockSize == (sizeof(IO_REMOVE_LOCK_DBG_BLOCK) + sizeof(IO_REMOVE_LOCK_COMMON_BLOCK))) { ASSERT(Lock->Dbg.HighWatermark == 0 || LockValue <= Lock->Dbg.HighWatermark); /* Allocate a tracking block */ TrackingBlock = ExAllocatePoolWithTag(NonPagedPool, sizeof(IO_REMOVE_LOCK_TRACKING_BLOCK), Lock->Dbg.AllocateTag); if (!TrackingBlock) { /* Keep count of failures for lock release and missing tags */ InterlockedIncrement(&(Lock->Dbg.LowMemoryCount)); } else { /* Initialize block */ RtlZeroMemory(TrackingBlock, sizeof(IO_REMOVE_LOCK_TRACKING_BLOCK)); TrackingBlock->Tag = Tag; TrackingBlock->File = File; TrackingBlock->Line = Line; KeQueryTickCount(&(TrackingBlock->LockMoment)); /* Queue the block */ KeAcquireSpinLock(&(Lock->Dbg.Spin), &OldIrql); TrackingBlock->Next = Lock->Dbg.Blocks; Lock->Dbg.Blocks = TrackingBlock; KeReleaseSpinLock(&(Lock->Dbg.Spin), OldIrql); } } } else { /* Otherwise, decrement the count and check if it's gone */ if (!InterlockedDecrement(&(Lock->Common.IoCount))) { /* Signal the event */ KeSetEvent(&(Lock->Common.RemoveEvent), IO_NO_INCREMENT, FALSE); } /* Return pending delete */ return STATUS_DELETE_PENDING; } /* Otherwise, return success */ return STATUS_SUCCESS; }