NTSTATUS MntInitializeMountMgr( __in PDRIVER_OBJECT DriverObject ) { NTSTATUS Status; UNICODE_STRING DevDirName; OBJECT_ATTRIBUTES ObjAttrib; HANDLE DevObjHandle; KeInitializeMutex(&MntGeneralMountLock,0); InitializeListHead(&MntDiskList); RtlInitUnicodeString(&DevDirName,VFD_ROOT_DIR_DEV); InitializeObjectAttributes(&ObjAttrib,&DevDirName,OBJ_OPENIF,NULL,NULL); Status = ZwCreateDirectoryObject(&DevObjHandle, DIRECTORY_ALL_ACCESS, &ObjAttrib); if (!NT_SUCCESS(Status)) return Status; MntDriverObject = DriverObject; return STATUS_SUCCESS; }
/** * 初始化文件日志。4个参数 * 在使用该日志模块时在写日志之前要调用该函数进行初始化,在中间任何地方都可以对日志文件进行写入日志信息,当写完日志后,不再调用该函数写日志,那么要调用LogUninitialize进行清理。 */ void LogInitialize(ULONG loglevel,WCHAR* logfilename,LONGLONG filesize,USHORT strategy) { size_t flength; NTSTATUS ntStatus = RtlStringCchLengthW(logfilename,(MAX_PATH-2),&flength); if(!NT_SUCCESS(ntStatus) ) { KdPrint( ("Filename too long!\n") ); return; } KdPrint( ("Filename length:%d\n",flength) ); //将文件名记录在g_LogFileName中,注意Unicode_String不是以0为结束,以Length作为计算标准 g_logFileName.Buffer = (PWSTR)ExAllocatePool(NonPagedPool,MAX_PATH*sizeof(WCHAR));//申请双倍内存 RtlZeroMemory(g_logFileName.Buffer,MAX_PATH*sizeof(WCHAR));//清0,为了下面的操作顺利 g_logFileName.MaximumLength = MAX_PATH*sizeof(WCHAR); RtlCopyMemory(g_logFileName.Buffer,logfilename,flength*sizeof(WCHAR)); g_logFileName.Length = flength*sizeof(WCHAR); KdPrint( ("Filename:%wZ\n",&g_logFileName) ); g_logLevel = loglevel; g_logFileMaxSize = filesize; g_logWriteTime = 0; g_logStrategy = strategy; //初始化处理互斥体 KeInitializeMutex(&g_logMutex,0); KdPrint( ("Log Init Sucsess!\n") ); }
NTSTATUS ScanCache_Init () { UINT nSize ; TRACE ; ASSERT (!g_data.bInitialized) ; g_data.nEntriesMax = CACHE_LENGTH ; g_data.nEntries = 0 ; g_data.iNextEntry = 0 ; g_data.nNextIdentifier = 0 ; nSize = g_data.nEntriesMax*sizeof(SCANCACHEENTRY) ; g_data.pEntries = MALLOC(nSize) ; if( g_data.pEntries == NULL ) { TRACE_ERROR (TEXT("Failed to allocate scan cache buffer (%n bytes)\n"), nSize) ; return STATUS_INSUFFICIENT_RESOURCES ; } KeInitializeMutex (&g_data.mutex, 0) ; KeInitializeEvent (&g_data.event, NotificationEvent, FALSE) ; g_data.bInitialized = TRUE ; return STATUS_SUCCESS ; }
/*--------------------------------------------------------- 函数名称: HashInitialize 函数描述: 初始化新的Hash表 输入参数: dpHashTable 保存Hash表数据 ulMaximumPointNumber 最大Hash值范围 输出参数: dpHashTable Hash表数据 返回值: TRUE为成功 FALSE失败 其他: 更新维护: 2011.4.2 最初版本 2011.7.16 将自旋锁改为了互斥体 ---------------------------------------------------------*/ BOOLEAN HashInitialize( PHASH_TABLE_DESCRIPTOR * dpHashTable, ULONG ulMaximumPointNumber ) { //传入参数一定正确 ASSERT( dpHashTable ); ASSERT( ulMaximumPointNumber ); // //分别申请两块内存,分别是表内存和表描述结构, //如果失败则返回,否则填充结构,数据置零然后返回 // PHASH_TABLE_DESCRIPTOR pHashTable; pHashTable = (PHASH_TABLE_DESCRIPTOR)ExAllocatePoolWithTag( NonPagedPool , sizeof(HASH_TABLE_DESCRIPTOR), MEM_HASH_TAG ); if( !pHashTable ) { return FALSE; } pHashTable -> ulHashTableBaseAddress = (ULONG)ExAllocatePoolWithTag( NonPagedPool , HASH_POINT_SIZE * ulMaximumPointNumber, MEM_HASH_TAG ); if( !pHashTable ) { ExFreePool( pHashTable ); return FALSE; } RtlZeroMemory( (PVOID)pHashTable -> ulHashTableBaseAddress , HASH_POINT_SIZE * ulMaximumPointNumber ); // //初始化互斥体 保存信息 // KeInitializeMutex( &pHashTable -> irmMutex , 0 ); pHashTable -> ulMaximumPointNumber = ulMaximumPointNumber; // //返回 // *dpHashTable = pHashTable; return TRUE; }
int rnd_init_prng() { if ( (rnd_key = mm_alloc(sizeof(aes256_key), MEM_SECURE)) == NULL ) { return ST_NOMEM; } KeInitializeMutex(&rnd_mutex, 0); rnd_reseed_now(); return ST_OK; }
//-------------------------------------------------------------------------------------- void DbgInit(void) { #if defined(DBGPIPE) || defined(DBGLOGFILE) KeInitializeMutex(&DbgMutex, NULL); #endif // DBGPIPE/DBGLOGFILE }
/* * DriverInitialize * * Purpose: * * Driver main. * */ NTSTATUS DriverInitialize( _In_ struct _DRIVER_OBJECT *DriverObject, _In_ PUNICODE_STRING RegistryPath ) { NTSTATUS status; UNICODE_STRING SymLink, DevName; PDEVICE_OBJECT devobj; ULONG t; //RegistryPath is unused UNREFERENCED_PARAMETER(RegistryPath); g_NotifySet = FALSE; g_VBoxDD.Chains = NULL; g_VBoxDD.ChainsLength = 0; KeInitializeMutex(&g_VBoxDD.Lock, 0); RtlInitUnicodeString(&DevName, TSUGUMI_DEV_OBJECT); status = IoCreateDevice(DriverObject, 0, &DevName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, TRUE, &devobj); if (!NT_SUCCESS(status)) { return status; } RtlInitUnicodeString(&SymLink, TSUGUMI_SYM_LINK); status = IoCreateSymbolicLink(&SymLink, &DevName); if (!NT_SUCCESS(status)) { IoDeleteDevice(devobj); return status; } devobj->Flags |= DO_BUFFERED_IO; for (t = 0; t <= IRP_MJ_MAXIMUM_FUNCTION; t++) DriverObject->MajorFunction[t] = &UnsupportedDispatch; DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = &DevioctlDispatch; DriverObject->MajorFunction[IRP_MJ_CREATE] = &CreateCloseDispatch; DriverObject->MajorFunction[IRP_MJ_CLOSE] = &CreateCloseDispatch; #ifndef _SIGNED_BUILD DriverObject->DriverUnload = NULL; devobj->Flags &= ~DO_DEVICE_INITIALIZING; #else DriverObject->DriverUnload = &DriverUnload; status = TsmiLoadParameters(); if (NT_SUCCESS(status)) { status = PsSetLoadImageNotifyRoutine(TsmiPsImageHandler); if (NT_SUCCESS(status)) { g_NotifySet = TRUE; } } #endif return STATUS_SUCCESS; }
PGPdiskMutex::PGPdiskMutex(PGPUInt32 level) { mMutexPointer = new KMUTEX; if (NULL==(int)(mMutexPointer)) mInitErr = DualErr(kPGDMinorError_OutOfMemory); if (mInitErr.IsntError()) { KeInitializeMutex(mMutexPointer, level); } }
BOOL ShareLockKImp::InitializeShareMutex(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName) { UninitializeShareLock(); m_LockType = LockTypeMutex; KeInitializeMutex(&m_LockObject.m_Mutex.m_Mutex, 0); return TRUE; }
NTSTATUS DrvFilter_Init () { TRACE ; ASSERT (!g_data.bInitialized) ; KeInitializeMutex (&g_data.mutex, 0) ; g_data.hFilterSet = NULL ; g_data.bInitialized = TRUE ; return STATUS_SUCCESS ; }
NTSTATUS STDCALL DriverEntry(PDRIVER_OBJECT driverObject, PUNICODE_STRING registryPath) { NTSTATUS status = STATUS_SUCCESS; PDEVICE_OBJECT deviceObject = NULL; DbgPrint("Load\n"); driverObject->DriverUnload = my_unload; UNICODE_STRING deviceName; RtlInitUnicodeString(&deviceName, DEVICE_PATH); status = IoCreateDevice(driverObject, sizeof(device_context_t), &deviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &deviceObject); if (status != STATUS_SUCCESS) { DbgPrint("Cannot create device\n"); goto cleanup; } // Initialize the context device_context_t* context = (device_context_t*) deviceObject->DeviceExtension; KeInitializeMutex(&(context->mutex), 0); context->stack = NULL; for (int i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) { driverObject->MajorFunction[i] = my_unsuported_function; } driverObject->MajorFunction[IRP_MJ_CREATE] = my_create; driverObject->MajorFunction[IRP_MJ_CLOSE] = my_close; driverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = my_ioctl; deviceObject->Flags |= DO_BUFFERED_IO; deviceObject->Flags &= (~DO_DEVICE_INITIALIZING); UNICODE_STRING dosDeviceName; RtlInitUnicodeString(&dosDeviceName, DOSDEVICE_PATH); IoCreateSymbolicLink(&dosDeviceName, &deviceName); cleanup: if (status != STATUS_SUCCESS) { if (deviceObject) { IoDeleteDevice(deviceObject); } } return status; }
NTSTATUS WatchObjs_Init () { TRACE ; KeInitializeMutex (&g_data.mutex, 0) ; g_data.pFirst = NULL ; g_data.pLast = NULL ; g_data.nNodeCount = 0 ; g_data.bInitialized = TRUE ; return STATUS_SUCCESS ; }
void MuInitializeGlobalData ( PMU_GLOBAL_DATA GlobalData ) { RtlZeroMemory(GlobalData, sizeof(MU_GLOBAL_DATA)); KeInitializeSpinLock(&GlobalData->GlobalLock); KeInitializeSpinLock(&GlobalData->ThreadRecordLock); ExInitializeFastMutex(&GlobalData->UserStorageMutex); ExInitializeFastMutex(&GlobalData->ImpersonationPathMutex); KeInitializeMutex(&GlobalData->NsdLibraryMutex, 0); }
NTSTATUS DriverEntry(__in PDRIVER_OBJECT pDriverObject, __in PUNICODE_STRING pRegistryPath) { NTSTATUS status = STATUS_SUCCESS; UNICODE_STRING usDriverName; PDEVICE_OBJECT pDeviceObject; ULONG i; Dbg("Driver entry\n"); Resolve_FunctionsAddr(); RtlInitUnicodeString(&usDriverName, L"\\Device\\" DRIVER_NAME); RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\" DRIVER_NAME); status = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &pDeviceObject); if(!NT_SUCCESS(status)) return status; status = IoCreateSymbolicLink(&usDosDeviceName, &usDriverName); if(!NT_SUCCESS(status)) return status; pDeviceObject->Flags |= DO_BUFFERED_IO; pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING); for(i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++) pDriverObject->MajorFunction[i] = Ioctl_NotSupported; pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = Ioctl_DeviceControl; status = Init_LinkedLists(); if(!NT_SUCCESS(status)) return status; status = InitMinifilter(pDriverObject); if(!NT_SUCCESS(status)) return status; KeInitializeMutex(&mutex, 0); HookSSDT(); status = PsSetLoadImageNotifyRoutine(imageCallback); if(!NT_SUCCESS(status)) return status; pDriverObject->DriverUnload = Unload; return status; }
//-------------------------------------------------------------------------------------- NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { DbgMsg(__FILE__, __LINE__, __FUNCTION__"()\n"); DriverObject->DriverUnload = DriverUnload; m_Self = (PLDR_DATA_TABLE_ENTRY)DriverObject->DriverSection; KeInitializeMutex(&m_GlobalMutex, NULL); // save registry path if (AllocUnicodeString(&m_RegistryPath, RegistryPath->Length)) { RtlCopyUnicodeString(&m_RegistryPath, RegistryPath); DbgMsg(__FILE__, __LINE__, "Service registry path is '%wZ'\n", &m_RegistryPath); } else { return STATUS_UNSUCCESSFUL; } NTSTATUS ns = PsSetLoadImageNotifyRoutine(LoadImageNotify); if (!NT_SUCCESS(ns)) { DbgMsg(__FILE__, __LINE__, "PsSetLoadImageNotifyRoutine() fails; status: 0x%.8x\n", ns); return STATUS_UNSUCCESSFUL; } PIMAGE_NT_HEADERS32 pHeaders = (PIMAGE_NT_HEADERS32)((PUCHAR)m_Self->DllBase + ((PIMAGE_DOS_HEADER)m_Self->DllBase)->e_lfanew); PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER) (pHeaders->FileHeader.SizeOfOptionalHeader + (PUCHAR)&pHeaders->OptionalHeader); // copy sections for (ULONG i = 0; i < pHeaders->FileHeader.NumberOfSections; i++) { // erase discardable flag from our driver sections pSection->Characteristics &= ~IMAGE_SCN_MEM_DISCARDABLE; pSection += 1; } m_RequiredSize = pHeaders->OptionalHeader.SizeOfImage; return STATUS_SUCCESS; }
void _rtw_rwlock_init(_rwlock *prwlock) { #ifdef PLATFORM_LINUX init_MUTEX(prwlock); #endif #ifdef PLATFORM_OS_XP KeInitializeMutex(prwlock, 0); #endif #ifdef PLATFORM_OS_CE *prwlock = CreateMutex( NULL, _FALSE, NULL); #endif }
co_rc_t co_os_mutex_create(co_os_mutex_t *mutex_out) { co_os_mutex_t mutex; *mutex_out = NULL; mutex = co_os_malloc(sizeof(*mutex)); if (mutex == NULL) return CO_RC(OUT_OF_MEMORY); KeInitializeMutex(&mutex->mutex, 0); *mutex_out = mutex; return CO_RC(OK); }
PKSTREAM KStreamAllocate(VOID) { PKSTREAM pStream = ExAllocatePoolWithTag(NonPagedPool, sizeof(KSTREAM), TAG_KSTREAM); if (pStream) { pStream->Position = 0; pStream->Length = 0; InitializeListHead(&pStream->BuffersListHead); KeInitializeEvent(&pStream->DataReadyEvent, NotificationEvent, FALSE); KeInitializeMutex(&pStream->Lock, 0); ExInitializeNPagedLookasideList(&pStream->Buffers, NULL, NULL, 0, (sizeof(LBUFFER) + KSTREAM_BUFFER_SIZE), TAG_KSTREAM, 0); #if DBG pStream->Magic = KSTREAM_MAGIC; #endif } return(pStream); }
RTDECL(int) RTSemMutexCreateEx(PRTSEMMUTEX phMutexSem, uint32_t fFlags, RTLOCKVALCLASS hClass, uint32_t uSubClass, const char *pszNameFmt, ...) { AssertReturn(!(fFlags & ~RTSEMMUTEX_FLAGS_NO_LOCK_VAL), VERR_INVALID_PARAMETER); AssertCompile(sizeof(RTSEMMUTEXINTERNAL) > sizeof(void *)); PRTSEMMUTEXINTERNAL pThis = (PRTSEMMUTEXINTERNAL)RTMemAlloc(sizeof(*pThis)); if (!pThis) return VERR_NO_MEMORY; pThis->u32Magic = RTSEMMUTEX_MAGIC; #ifdef RT_USE_FAST_MUTEX ExInitializeFastMutex(&pThis->Mutex); #else KeInitializeMutex(&pThis->Mutex, 0); #endif *phMutexSem = pThis; return VINF_SUCCESS; }
/** * Check if this cpu supports Intel VT Technology. */ NTSTATUS NTAPI hvm_init(struct arch_phy* parch) { BOOLEAN ArchIsOK = FALSE; arch = parch; // [TODO] Need refactoring to support SVM Hvm = &Vmx; ArchIsOK = Hvm->ArchIsHvmImplemented (); if (!ArchIsOK) { return STATUS_NOT_SUPPORTED; } else { print("HvmInit():Intel VT-x Supported\n"); arch->hvm.architecture |= ARCH_VMX; Hvm->ArchRegisterFeatures(arch); } KeInitializeMutex (&g_HvmMutex, 0); return STATUS_SUCCESS; }
void _rtw_mutex_init(_mutex *pmutex) { #ifdef PLATFORM_LINUX #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,37)) mutex_init(pmutex); #else init_MUTEX(pmutex); #endif #endif #ifdef PLATFORM_OS_XP KeInitializeMutex(pmutex, 0); #endif #ifdef PLATFORM_OS_CE *pmutex = CreateMutex( NULL, _FALSE, NULL); #endif }
VOID InitializeDeviceExtension( PPORT_CONFIGURATION_INFORMATION ConfigInfo ) { PDCAM_EXTENSION pDevExt; PAGED_CODE(); pDevExt = (PDCAM_EXTENSION) ConfigInfo->HwDeviceExtension; pDevExt->SharedDeviceObject = ConfigInfo->ClassDeviceObject; pDevExt->BusDeviceObject = ConfigInfo->PhysicalDeviceObject; // Used in IoCallDriver() pDevExt->PhysicalDeviceObject = ConfigInfo->RealPhysicalDeviceObject; // Used in PnP API // In case sonydcam is used with old stream.sys, // which has not implemented RealPhysicalDeviceObject. if(!pDevExt->PhysicalDeviceObject) pDevExt->PhysicalDeviceObject = pDevExt->BusDeviceObject; ASSERT(pDevExt->PhysicalDeviceObject != 0); pDevExt->BaseRegister = 0; pDevExt->FrameRate = DEFAULT_FRAME_RATE; InitializeListHead(&pDevExt->IsochDescriptorList); KeInitializeSpinLock(&pDevExt->IsochDescriptorLock); pDevExt->bNeedToListen = FALSE; pDevExt->hResource = NULL; pDevExt->hBandwidth = NULL; pDevExt->IsochChannel = ISOCH_ANY_CHANNEL; pDevExt->PendingReadCount = 0; pDevExt->pStrmEx = 0; pDevExt->bDevRemoved = FALSE; pDevExt->PendingWorkItemCount = 0; // Initialize to signal state and is set to unsignalled state if there is a pending work item KeInitializeEvent( &pDevExt->PendingWorkItemEvent, NotificationEvent , TRUE ); pDevExt->CurrentPowerState = PowerDeviceD0; // full power state. KeInitializeMutex( &pDevExt->hMutexProperty, 0); // Level 0 and in Signal state }
NTSTATUS PspLdtInitialize ( VOID ) /*++ Routine Description: This routine initializes the LDT support for the x86 Arguments: None Return Value: NTSTATUS. --*/ { KeInitializeMutex (&LdtMutex, 0); return STATUS_SUCCESS; }
/******************************************************************************* * * 函 数 名 : InitlizedDeviceExtension * 功能描述 : 初始化DeviceExtension中一些SSDT函数索引,系统结构体偏移值 * 参数列表 : pde -- PDEVICE_EXTENSION 结构体 * 说 明 : * 返回结果 : 函数成功返回true,失败返回false * *******************************************************************************/ bool InitlizedDeviceExtension(PDEVICE_EXTENSION pde) { RTL_OSVERSIONINFOW osi ={0} ; osi.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOW) ; RtlGetVersion(&osi) ; if (NULL == pde) { return false ; } KeInitializeMutex(&pde->DeviceIoControlMutex, 0) ; KeInitializeMutex(&pde->MyThreadMutex, 0) ; // 判断系统版本,填充相应的值 switch(osi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: { switch(osi.dwMajorVersion) { case 0: case 1: case 2: case 3: case 4: // 这里的话是Windows NT系统 // 添加相应的代码 { } break ; // 2k xp 2003 case 5: { switch(osi.dwMinorVersion) { // 2000的系统 case 0: { pde->uNtQuerySystemInformationIndex = 151 ; pde->uNtOpenProcessIndex = 106 ; } break ; // xp的系统 case 1: { pde->uNtQuerySystemInformationIndex = 173 ; pde->uNtOpenProcessIndex = 122 ; pde->uActiveProcessLinksOffset = 0x88 ; pde->UniqueProcessIdOffset = 0x84 ; } break ; // 2003的系统 case 2: { pde->uNtQuerySystemInformationIndex = 181 ; pde->uNtOpenProcessIndex = 128 ; pde->uActiveProcessLinksOffset = 152 ; pde->UniqueProcessIdOffset = 148 ; } break ; }// end of switch(osi.dwMinorVersion) } // end of case 5 break ; // vista 2008 win 7 case 6: { switch(osi.dwMinorVersion) { // vista 2008 case 0: { pde->uNtQuerySystemInformationIndex = 248 ; pde->uNtOpenProcessIndex = 194 ; } break ; // win 7 2008 r2 case 1: { pde->uNtQuerySystemInformationIndex = 260 ; pde->uNtOpenProcessIndex = 189 ; pde->uActiveProcessLinksOffset = 0xb8 ; pde->UniqueProcessIdOffset = 0xb4 ; } break ; } } break ; default: break ; } } break ; } return true ; }
NTSTATUS DiskInitFdo( IN PDEVICE_OBJECT Fdo ) /*++ Routine Description: This routine is called to do one-time initialization of new device objects Arguments: Fdo - a pointer to the functional device object for this device Return Value: status --*/ { PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension; PDISK_DATA diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData; ULONG srbFlags = 0; ULONG timeOut = 0; ULONG bytesPerSector; PULONG dmSkew; NTSTATUS status = STATUS_SUCCESS; PAGED_CODE(); // // Build the lookaside list for srb's for the physical disk. Should only // need a couple. If this fails then we don't have an emergency SRB so // fail the call to initialize. // ClassInitializeSrbLookasideList((PCOMMON_DEVICE_EXTENSION) fdoExtension, PARTITION0_LIST_SIZE); if (fdoExtension->DeviceDescriptor->RemovableMedia) { SET_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA); } // // Initialize the srb flags. // // // Because all requests share a common sense buffer, it is possible // for the buffer to be overwritten if the port driver completes // multiple failed requests that require a request sense before the // class driver's completion routine can consume the data in the buffer. // To prevent this, we allow the port driver to allocate a unique sense // buffer each time it needs one. We are responsible for freeing this // buffer. This also allows the adapter to be configured to support // additional sense data beyond the minimum 18 bytes. // SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE); if (fdoExtension->DeviceDescriptor->CommandQueueing && fdoExtension->AdapterDescriptor->CommandQueueing) { SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_QUEUE_ACTION_ENABLE); } // // Look for controllers that require special flags. // ClassScanForSpecial(fdoExtension, DiskBadControllers, DiskSetSpecialHacks); // // Clear buffer for drive geometry. // RtlZeroMemory(&(fdoExtension->DiskGeometry), sizeof(DISK_GEOMETRY)); // // Allocate request sense buffer. // fdoExtension->SenseData = ExAllocatePoolWithTag(NonPagedPoolNxCacheAligned, SENSE_BUFFER_SIZE_EX, DISK_TAG_START); if (fdoExtension->SenseData == NULL) { // // The buffer can not be allocated. // TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_PNP, "DiskInitFdo: Can not allocate request sense buffer\n")); status = STATUS_INSUFFICIENT_RESOURCES; return status; } // // Set the buffer size of SenseData // fdoExtension->SenseDataLength = SENSE_BUFFER_SIZE_EX; // // Physical device object will describe the entire // device, starting at byte offset 0. // fdoExtension->CommonExtension.StartingOffset.QuadPart = (LONGLONG)(0); // // Set timeout value in seconds. // if ( (fdoExtension->MiniportDescriptor != NULL) && (fdoExtension->MiniportDescriptor->IoTimeoutValue > 0) ) { // // use the value set by Storport miniport driver // fdoExtension->TimeOutValue = fdoExtension->MiniportDescriptor->IoTimeoutValue; } else { // // get timeout value from registry // timeOut = ClassQueryTimeOutRegistryValue(Fdo); if (timeOut) { fdoExtension->TimeOutValue = timeOut; } else { fdoExtension->TimeOutValue = SCSI_DISK_TIMEOUT; } } // // If this is a removable drive, build an entry in devicemap\scsi // indicating it's physicaldriveN name, set up the appropriate // update partitions routine and set the flags correctly. // note: only do this after the timeout value is set, above. // if (TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) { ClassUpdateInformationInRegistry( Fdo, "PhysicalDrive", fdoExtension->DeviceNumber, NULL, 0); // // Enable media change notification for removable disks // ClassInitializeMediaChangeDetection(fdoExtension, (PUCHAR)"Disk"); } else { SET_FLAG(fdoExtension->DeviceFlags, DEV_SAFE_START_UNIT); SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE); } // // The commands we send during the init could cause the flags to change // in case of any error. Save the SRB flags locally and restore it at // the end of this function, so that the class driver can get it. // srbFlags = fdoExtension->SrbFlags; // // Read the drive capacity. Don't use the disk version of the routine here // since we don't know the disk signature yet - the disk version will // attempt to determine the BIOS reported geometry. // (VOID)ClassReadDriveCapacity(Fdo); // // Set up sector size fields. // // Stack variables will be used to update // the partition device extensions. // // The device extension field SectorShift is // used to calculate sectors in I/O transfers. // // The DiskGeometry structure is used to service // IOCTls used by the format utility. // bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector; // // Make sure sector size is not zero. // if (bytesPerSector == 0) { // // Default sector size for disk is 512. // bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector = 512; fdoExtension->SectorShift = 9; } // // Determine is DM Driver is loaded on an IDE drive that is // under control of Atapi - this could be either a crashdump or // an Atapi device is sharing the controller with an IDE disk. // HalExamineMBR(fdoExtension->CommonExtension.DeviceObject, fdoExtension->DiskGeometry.BytesPerSector, (ULONG)0x54, &dmSkew); if (dmSkew) { // // Update the device extension, so that the call to IoReadPartitionTable // will get the correct information. Any I/O to this disk will have // to be skewed by *dmSkew sectors aka DMByteSkew. // fdoExtension->DMSkew = *dmSkew; fdoExtension->DMActive = TRUE; fdoExtension->DMByteSkew = fdoExtension->DMSkew * bytesPerSector; FREE_POOL(dmSkew); } #if defined(_X86_) || defined(_AMD64_) // // Try to read the signature off the disk and determine the correct drive // geometry based on that. This requires rereading the disk size to get // the cylinder count updated correctly. // if(!TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) { DiskReadSignature(Fdo); DiskReadDriveCapacity(Fdo); if (diskData->GeometrySource == DiskGeometryUnknown) { // // Neither the BIOS nor the port driver could provide us with a reliable // geometry. Before we use the default, look to see if it was partitioned // under Windows NT4 [or earlier] and apply the one that was used back then // if (DiskIsNT4Geometry(fdoExtension)) { diskData->RealGeometry = fdoExtension->DiskGeometry; diskData->RealGeometry.SectorsPerTrack = 0x20; diskData->RealGeometry.TracksPerCylinder = 0x40; fdoExtension->DiskGeometry = diskData->RealGeometry; diskData->GeometrySource = DiskGeometryFromNT4; } } } #endif DiskCreateSymbolicLinks(Fdo); // // Get the SCSI address if it's available for use with SMART ioctls. // SMART ioctls are used for failure prediction, so we need to get // the SCSI address before initializing failure prediction. // { PIRP irp; KEVENT event; IO_STATUS_BLOCK statusBlock = { 0 }; KeInitializeEvent(&event, SynchronizationEvent, FALSE); irp = IoBuildDeviceIoControlRequest(IOCTL_SCSI_GET_ADDRESS, fdoExtension->CommonExtension.LowerDeviceObject, NULL, 0L, &(diskData->ScsiAddress), sizeof(SCSI_ADDRESS), FALSE, &event, &statusBlock); status = STATUS_UNSUCCESSFUL; if(irp != NULL) { status = IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, irp); if(status == STATUS_PENDING) { KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL); status = statusBlock.Status; } } } // // Determine the type of disk and enable failure prediction in the hardware // and enable failure prediction polling. // if (*InitSafeBootMode == 0) { DiskDetectFailurePrediction(fdoExtension, &diskData->FailurePredictionCapability, NT_SUCCESS(status)); if (diskData->FailurePredictionCapability != FailurePredictionNone) { // // Cool, we've got some sort of failure prediction, enable it // at the hardware and then enable polling for it // // // By default we allow performance to be degradeded if failure // prediction is enabled. // diskData->AllowFPPerfHit = TRUE; // // Enable polling only after Atapi and SBP2 add support for the new // SRB flag that indicates that the request should not reset the // drive spin down idle timer. // status = DiskEnableDisableFailurePredictPolling(fdoExtension, TRUE, DISK_DEFAULT_FAILURE_POLLING_PERIOD); TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_PNP, "DiskInitFdo: Failure Prediction Poll enabled as " "%d for device %p, Status = %lx\n", diskData->FailurePredictionCapability, Fdo, status)); } } else { // // In safe boot mode we do not enable failure prediction, as perhaps // it is the reason why normal boot does not work // diskData->FailurePredictionCapability = FailurePredictionNone; } // // Initialize the verify mutex // KeInitializeMutex(&diskData->VerifyMutex, MAX_SECTORS_PER_VERIFY); // // Initialize the flush group context // RtlZeroMemory(&diskData->FlushContext, sizeof(DISK_GROUP_CONTEXT)); InitializeListHead(&diskData->FlushContext.CurrList); InitializeListHead(&diskData->FlushContext.NextList); KeInitializeSpinLock(&diskData->FlushContext.Spinlock); KeInitializeEvent(&diskData->FlushContext.Event, SynchronizationEvent, FALSE); // // Restore the saved value // fdoExtension->SrbFlags = srbFlags; return STATUS_SUCCESS; } // end DiskInitFdo()
void KMutexInit(KMUTEX * mutex) { KeInitializeMutex(mutex, 0); }
/***************************************************************************** * InitializeCriticalSection() ***************************************************************************** * In kernel mode, we use a KMUTEX to implement our critical section. * Initialize the KMUTEX. */ VOID InitializeCriticalSection(LPCRITICAL_SECTION CritSect) { KeInitializeMutex((PKMUTEX)CritSect, 1); }
NTSTATUS EncryptedIoQueueStart (EncryptedIoQueue *queue) { NTSTATUS status; EncryptedIoQueueBuffer *buffer; int i; queue->StartPending = TRUE; queue->ThreadExitRequested = FALSE; queue->OutstandingIoCount = 0; queue->IoThreadPendingRequestCount = 0; queue->FirstPoolBuffer = NULL; KeInitializeMutex (&queue->BufferPoolMutex, 0); KeInitializeEvent (&queue->NoOutstandingIoEvent, SynchronizationEvent, FALSE); KeInitializeEvent (&queue->PoolBufferFreeEvent, SynchronizationEvent, FALSE); KeInitializeEvent (&queue->QueueResumedEvent, SynchronizationEvent, FALSE); queue->FragmentBufferA = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); if (!queue->FragmentBufferA) goto noMemory; queue->FragmentBufferB = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); if (!queue->FragmentBufferB) goto noMemory; KeInitializeEvent (&queue->FragmentBufferAFreeEvent, SynchronizationEvent, TRUE); KeInitializeEvent (&queue->FragmentBufferBFreeEvent, SynchronizationEvent, TRUE); queue->ReadAheadBufferValid = FALSE; queue->ReadAheadBuffer = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); if (!queue->ReadAheadBuffer) goto noMemory; // Preallocate buffers for (i = 0; i < TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_COUNT; ++i) { if (i < TC_ENC_IO_QUEUE_PREALLOCATED_ITEM_COUNT && !GetPoolBuffer (queue, sizeof (EncryptedIoQueueItem))) goto noMemory; if (!GetPoolBuffer (queue, sizeof (EncryptedIoRequest))) goto noMemory; } for (buffer = queue->FirstPoolBuffer; buffer != NULL; buffer = buffer->NextBuffer) { buffer->InUse = FALSE; } // Main thread InitializeListHead (&queue->MainThreadQueue); KeInitializeSpinLock (&queue->MainThreadQueueLock); KeInitializeEvent (&queue->MainThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); status = TCStartThread (MainThreadProc, queue, &queue->MainThread); if (!NT_SUCCESS (status)) goto err; // IO thread InitializeListHead (&queue->IoThreadQueue); KeInitializeSpinLock (&queue->IoThreadQueueLock); KeInitializeEvent (&queue->IoThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); status = TCStartThread (IoThreadProc, queue, &queue->IoThread); if (!NT_SUCCESS (status)) { queue->ThreadExitRequested = TRUE; TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); goto err; } // Completion thread InitializeListHead (&queue->CompletionThreadQueue); KeInitializeSpinLock (&queue->CompletionThreadQueueLock); KeInitializeEvent (&queue->CompletionThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); status = TCStartThread (CompletionThreadProc, queue, &queue->CompletionThread); if (!NT_SUCCESS (status)) { queue->ThreadExitRequested = TRUE; TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); TCStopThread (queue->IoThread, &queue->IoThreadQueueNotEmptyEvent); goto err; } #ifdef TC_TRACE_IO_QUEUE GetElapsedTimeInit (&queue->LastPerformanceCounter); #endif queue->StopPending = FALSE; queue->StartPending = FALSE; Dump ("Queue started\n"); return STATUS_SUCCESS; noMemory: status = STATUS_INSUFFICIENT_RESOURCES; err: if (queue->FragmentBufferA) TCfree (queue->FragmentBufferA); if (queue->FragmentBufferB) TCfree (queue->FragmentBufferB); if (queue->ReadAheadBuffer) TCfree (queue->ReadAheadBuffer); FreePoolBuffers (queue); queue->StartPending = FALSE; return status; }
NTSTATUS NTAPI DiskInitFdo( IN PDEVICE_OBJECT Fdo ) /*++ Routine Description: This routine is called to do one-time initialization of new device objects Arguments: Fdo - a pointer to the functional device object for this device Return Value: status --*/ { PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension; PDISK_DATA diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData; //ULONG srbFlags = 0; ULONG timeOut = 0; ULONG bytesPerSector; //UCHAR sectorShift; //BOOLEAN dmActive = FALSE; PULONG dmSkew; //ULONG dmByteSkew; NTSTATUS status; PAGED_CODE(); // // Build the lookaside list for srb's for the physical disk. Should only // need a couple. If this fails then we don't have an emergency SRB so // fail the call to initialize. // ClassInitializeSrbLookasideList((PCOMMON_DEVICE_EXTENSION) fdoExtension, PARTITION0_LIST_SIZE); // // Because all requests share a common sense buffer, it is possible // for the buffer to be overwritten if the port driver completes // multiple failed requests that require a request sense before the // class driver's completion routine can consume the data in the buffer. // To prevent this, we allow the port driver to allocate a unique sense // buffer each time it needs one. We are responsible for freeing this // buffer. This also allows the adapter to be configured to support // additional sense data beyond the minimum 18 bytes. // fdoExtension->SrbFlags = SRB_FLAGS_PORT_DRIVER_ALLOCSENSE; // // Initialize the srb flags. // if (fdoExtension->DeviceDescriptor->CommandQueueing && fdoExtension->AdapterDescriptor->CommandQueueing) { fdoExtension->SrbFlags = SRB_FLAGS_QUEUE_ACTION_ENABLE; } if (!TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) { SET_FLAG(fdoExtension->DeviceFlags, DEV_SAFE_START_UNIT); } // // Look for controllers that require special flags. // ClassScanForSpecial(fdoExtension, DiskBadControllers, DiskSetSpecialHacks); // // Look into the registry to see if this device // requires special attention - [ like a hack ] // DiskScanRegistryForSpecial(fdoExtension); //srbFlags = fdoExtension->SrbFlags; // // Clear buffer for drive geometry. // RtlZeroMemory(&(fdoExtension->DiskGeometry), sizeof(DISK_GEOMETRY)); // // Allocate request sense buffer. // fdoExtension->SenseData = ExAllocatePoolWithTag(NonPagedPoolCacheAligned, SENSE_BUFFER_SIZE, DISK_TAG_START); if (fdoExtension->SenseData == NULL) { // // The buffer can not be allocated. // DebugPrint((1, "DiskInitFdo: Can not allocate request sense buffer\n")); status = STATUS_INSUFFICIENT_RESOURCES; return status; } // // Physical device object will describe the entire // device, starting at byte offset 0. // fdoExtension->CommonExtension.StartingOffset.QuadPart = (LONGLONG)(0); // // Set timeout value in seconds. // timeOut = ClassQueryTimeOutRegistryValue(Fdo); if (timeOut) { fdoExtension->TimeOutValue = timeOut; } else { fdoExtension->TimeOutValue = SCSI_DISK_TIMEOUT; } // // If this is a removable drive, build an entry in devicemap\scsi // indicating it's physicaldriveN name, set up the appropriate // update partitions routine and set the flags correctly. // note: only do this after the timeout value is set, above. // if (fdoExtension->DeviceDescriptor->RemovableMedia) { ClassUpdateInformationInRegistry( Fdo, "PhysicalDrive", fdoExtension->DeviceNumber, NULL, 0); // // Enable media change notification for removable disks // ClassInitializeMediaChangeDetection(fdoExtension, "Disk"); SET_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA); diskData->UpdatePartitionRoutine = DiskUpdateRemovablePartitions; } else { SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE); diskData->UpdatePartitionRoutine = DiskUpdatePartitions; } // // Read the drive capacity. Don't use the disk version of the routine here // since we don't know the disk signature yet - the disk version will // attempt to determine the BIOS reported geometry. // status = ClassReadDriveCapacity(Fdo); // // If the read capcity failed then just return, unless this is a // removable disk where a device object partition needs to be created. // if (!NT_SUCCESS(status) && !(Fdo->Characteristics & FILE_REMOVABLE_MEDIA)) { DebugPrint((1, "DiskInitFdo: Can't read capacity for device %p\n", Fdo)); if (fdoExtension->DeviceDescriptor->RemovableMedia) { fdoExtension->DiskGeometry.MediaType = RemovableMedia; Fdo->Flags &= ~DO_VERIFY_VOLUME; } else { fdoExtension->DiskGeometry.MediaType = FixedMedia; } status = STATUS_SUCCESS; } // // Set up sector size fields. // // Stack variables will be used to update // the partition device extensions. // // The device extension field SectorShift is // used to calculate sectors in I/O transfers. // // The DiskGeometry structure is used to service // IOCTls used by the format utility. // bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector; // // Make sure sector size is not zero. // if (bytesPerSector == 0) { // // Default sector size for disk is 512. // bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector = 512; } //sectorShift = fdoExtension->SectorShift; // // Determine is DM Driver is loaded on an IDE drive that is // under control of Atapi - this could be either a crashdump or // an Atapi device is sharing the controller with an IDE disk. // HalExamineMBR(fdoExtension->CommonExtension.DeviceObject, fdoExtension->DiskGeometry.BytesPerSector, (ULONG)0x54, (PVOID*)&dmSkew); if (dmSkew) { // // Update the device extension, so that the call to IoReadPartitionTable // will get the correct information. Any I/O to this disk will have // to be skewed by *dmSkew sectors aka DMByteSkew. // fdoExtension->DMSkew = *dmSkew; fdoExtension->DMActive = TRUE; fdoExtension->DMByteSkew = fdoExtension->DMSkew * bytesPerSector; // // Save away the infomation that we need, since this deviceExtension will soon be // blown away. // //dmActive = TRUE; //dmByteSkew = fdoExtension->DMByteSkew; } #if defined(_X86_) // // Try to read the signature off the disk and determine the correct drive // geometry based on that. This requires rereading the disk size to get // the cylinder count updated correctly. // if(fdoExtension->DeviceDescriptor->RemovableMedia == FALSE) { DiskReadSignature(Fdo); DiskReadDriveCapacity(Fdo); } #endif // // Register interfaces for this device // { UNICODE_STRING interfaceName; RtlInitUnicodeString(&interfaceName, NULL); status = IoRegisterDeviceInterface(fdoExtension->LowerPdo, (LPGUID) &DiskClassGuid, NULL, &interfaceName); if(NT_SUCCESS(status)) { diskData->DiskInterfaceString = interfaceName; status = IoSetDeviceInterfaceState(&interfaceName, TRUE); } else { interfaceName.Buffer = NULL; } if(!NT_SUCCESS(status)) { DebugPrint((1, "DiskInitFdo: Unable to register or set disk DCA " "for fdo %p [%lx]\n", Fdo, status)); RtlFreeUnicodeString(&interfaceName); RtlInitUnicodeString(&(diskData->DiskInterfaceString), NULL); } } DiskCreateSymbolicLinks(Fdo); // // Determine the type of disk and enable failure preiction in the hardware // and enable failure prediction polling. // if (InitSafeBootMode == 0) { DiskDetectFailurePrediction(fdoExtension, &diskData->FailurePredictionCapability); if (diskData->FailurePredictionCapability != FailurePredictionNone) { // // Cool, we've got some sort of failure prediction, enable it // at the hardware and then enable polling for it // // // By default we allow performance to be degradeded if failure // prediction is enabled. // // TODO: Make a registry entry ? // diskData->AllowFPPerfHit = TRUE; // // Enable polling only after Atapi and SBP2 add support for the new // SRB flag that indicates that the request should not reset the // drive spin down idle timer. // status = DiskEnableDisableFailurePredictPolling(fdoExtension, TRUE, DISK_DEFAULT_FAILURE_POLLING_PERIOD); DebugPrint((3, "DiskInitFdo: Failure Prediction Poll enabled as " "%d for device %p\n", diskData->FailurePredictionCapability, Fdo)); } } else { // // In safe boot mode we do not enable failure prediction, as perhaps // it is the reason why normal boot does not work // diskData->FailurePredictionCapability = FailurePredictionNone; } // // Initialize the verify mutex // KeInitializeMutex(&diskData->VerifyMutex, MAX_SECTORS_PER_VERIFY); return(STATUS_SUCCESS); } // end DiskInitFdo()
/****************************************************************************** *** == == == == == => The driver entry point <= == == == == == *** ******************************************************************************/ NTSTATUS DDKAPI DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { NTSTATUS status; PDEVICE_OBJECT DeviceObject; UNICODE_STRING DeviceNameW; UNICODE_STRING SymbolicLinkNameW; ANSI_STRING DeviceNameA; ANSI_STRING SymbolicLinkNameA; DbgPrint("DriverEntry called\r\n"); // support for service stopping DriverObject->DriverUnload = my_unload; // create support DriverObject->MajorFunction[IRP_MJ_CREATE] = my_dispatch_create; // IOCTL support DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = my_dispatch_device_control; KeInitializeMutex(&mutex, 0); //KeReleaseMutex(&mutex, FALSE); for (DWORD i = 0; i < ENT_CNT; ++i) { g_proc_table[i].pid = 0; g_proc_table[i].sl_pid = 0; } /* initialize counted unicode strings * If I want to use normal string combining logic in my_names.h, * need to mess with ANSI vs. Unicode */ RtlInitString(&DeviceNameA, MY_DEVICE_NAME); RtlAnsiStringToUnicodeString(&DeviceNameW, &DeviceNameA, TRUE); RtlInitString(&SymbolicLinkNameA, MY_DOSDEVICE_NAME); RtlAnsiStringToUnicodeString(&SymbolicLinkNameW, &SymbolicLinkNameA, TRUE); // create device object status = IoCreateDevice(DriverObject, 0, &DeviceNameW, FILE_DEVICE_UNKNOWN, 0, FALSE, &DeviceObject); if (NT_SUCCESS(status)) { /* Clear a flag, set by IoCreateDevice. * This is not mandatory within DriverEntry, * but it *is* mandatory if used anywhere else. */ DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; // create user-visible name for the device status = IoCreateSymbolicLink(&SymbolicLinkNameW, &DeviceNameW); } // Initializing process creation/load handlers if (NT_SUCCESS(status)) status = PsSetCreateProcessNotifyRoutine(create_process_watcher, FALSE); if (NT_SUCCESS(status)) status = PsSetLoadImageNotifyRoutine(load_image_watcher); if (!NT_SUCCESS(status)) return status; return STATUS_SUCCESS; }