Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1378 lines
39 KiB

  1. /*++
  2. Copyright (C) Microsoft Corporation, 1991 - 1999
  3. Module Name:
  4. pnp.c
  5. Abstract:
  6. SCSI disk class driver
  7. Environment:
  8. kernel mode only
  9. Notes:
  10. Revision History:
  11. --*/
  12. #include "disk.h"
  13. extern PULONG InitSafeBootMode;
  14. ULONG diskDeviceSequenceNumber = 0;
  15. #ifdef ALLOC_PRAGMA
  16. #pragma alloc_text(PAGE, DiskAddDevice)
  17. #pragma alloc_text(PAGE, DiskInitFdo)
  18. #pragma alloc_text(PAGE, DiskInitPdo)
  19. #pragma alloc_text(PAGE, DiskStartFdo)
  20. #pragma alloc_text(PAGE, DiskStartPdo)
  21. #pragma alloc_text(PAGE, DiskQueryId)
  22. #pragma alloc_text(PAGE, DiskGenerateDeviceName)
  23. #pragma alloc_text(PAGE, DiskCreateSymbolicLinks)
  24. #pragma alloc_text(PAGE, DiskDeleteSymbolicLinks)
  25. #pragma alloc_text(PAGE, DiskRemoveDevice)
  26. #endif
  27. NTSTATUS
  28. DiskAddDevice(
  29. IN PDRIVER_OBJECT DriverObject,
  30. IN PDEVICE_OBJECT PhysicalDeviceObject
  31. )
  32. /*++
  33. Routine Description:
  34. This routine gets a port drivers capabilities, obtains the
  35. inquiry data, searches the SCSI bus for the port driver and creates
  36. the device objects for the disks found.
  37. Arguments:
  38. DriverObject - Pointer to driver object created by system.
  39. Pdo - Device object use to send requests to port driver.
  40. Return Value:
  41. True is returned if one disk was found and successfully created.
  42. --*/
  43. {
  44. ULONG rootPartitionMountable = FALSE;
  45. PCONFIGURATION_INFORMATION configurationInformation;
  46. ULONG diskCount;
  47. NTSTATUS status;
  48. PAGED_CODE();
  49. //
  50. // See if we should be allowing file systems to mount on partition zero.
  51. //
  52. TRY {
  53. HANDLE deviceKey;
  54. UNICODE_STRING diskKeyName;
  55. OBJECT_ATTRIBUTES objectAttributes = {0};
  56. HANDLE diskKey;
  57. RTL_QUERY_REGISTRY_TABLE queryTable[2] = { 0 };
  58. status = IoOpenDeviceRegistryKey(PhysicalDeviceObject,
  59. PLUGPLAY_REGKEY_DEVICE,
  60. KEY_READ,
  61. &deviceKey);
  62. if(!NT_SUCCESS(status)) {
  63. DebugPrint((1, "DiskAddDevice: Error %#08lx opening device key "
  64. "for pdo %#08lx\n",
  65. status, PhysicalDeviceObject));
  66. LEAVE;
  67. }
  68. RtlInitUnicodeString(&diskKeyName, L"Disk");
  69. InitializeObjectAttributes(&objectAttributes,
  70. &diskKeyName,
  71. OBJ_CASE_INSENSITIVE,
  72. deviceKey,
  73. NULL);
  74. status = ZwOpenKey(&diskKey, KEY_READ, &objectAttributes);
  75. ZwClose(deviceKey);
  76. if(!NT_SUCCESS(status)) {
  77. DebugPrint((1, "DiskAddDevice: Error %#08lx opening disk key "
  78. "for pdo %#08lx device key %#x\n",
  79. status, PhysicalDeviceObject, deviceKey));
  80. LEAVE;
  81. }
  82. queryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
  83. queryTable[0].Name = L"RootPartitionMountable";
  84. queryTable[0].EntryContext = &(rootPartitionMountable);
  85. status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE,
  86. diskKey,
  87. queryTable,
  88. NULL,
  89. NULL);
  90. if(!NT_SUCCESS(status)) {
  91. DebugPrint((1, "DiskAddDevice: Error %#08lx reading value from "
  92. "disk key %#x for pdo %#08lx\n",
  93. status, diskKey, PhysicalDeviceObject));
  94. }
  95. ZwClose(diskKey);
  96. } FINALLY {
  97. //
  98. // Do nothing.
  99. //
  100. if(!NT_SUCCESS(status)) {
  101. DebugPrint((1, "DiskAddDevice: Will %sallow file system to mount on "
  102. "partition zero of disk %#08lx\n",
  103. (rootPartitionMountable ? "" : "not "),
  104. PhysicalDeviceObject));
  105. }
  106. }
  107. //
  108. // Create device objects for disk
  109. //
  110. diskCount = 0;
  111. status = DiskCreateFdo(
  112. DriverObject,
  113. PhysicalDeviceObject,
  114. &diskCount,
  115. (BOOLEAN) !rootPartitionMountable
  116. );
  117. //
  118. // Get the number of disks already initialized.
  119. //
  120. configurationInformation = IoGetConfigurationInformation();
  121. if (NT_SUCCESS(status)) {
  122. //
  123. // Increment system disk device count.
  124. //
  125. configurationInformation->DiskCount++;
  126. }
  127. return status;
  128. } // end DiskAddDevice()
  129. NTSTATUS
  130. DiskInitFdo(
  131. IN PDEVICE_OBJECT Fdo
  132. )
  133. /*++
  134. Routine Description:
  135. This routine is called to do one-time initialization of new device objects
  136. Arguments:
  137. Fdo - a pointer to the functional device object for this device
  138. Return Value:
  139. status
  140. --*/
  141. {
  142. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  143. PDISK_DATA diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData;
  144. ULONG srbFlags = 0;
  145. ULONG timeOut = 0;
  146. ULONG bytesPerSector;
  147. PULONG dmSkew;
  148. NTSTATUS status = STATUS_SUCCESS;
  149. PAGED_CODE();
  150. //
  151. // Build the lookaside list for srb's for the physical disk. Should only
  152. // need a couple. If this fails then we don't have an emergency SRB so
  153. // fail the call to initialize.
  154. //
  155. ClassInitializeSrbLookasideList((PCOMMON_DEVICE_EXTENSION) fdoExtension,
  156. PARTITION0_LIST_SIZE);
  157. if (fdoExtension->DeviceDescriptor->RemovableMedia)
  158. {
  159. SET_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA);
  160. }
  161. //
  162. // Initialize the srb flags.
  163. //
  164. //
  165. // Because all requests share a common sense buffer, it is possible
  166. // for the buffer to be overwritten if the port driver completes
  167. // multiple failed requests that require a request sense before the
  168. // class driver's completion routine can consume the data in the buffer.
  169. // To prevent this, we allow the port driver to allocate a unique sense
  170. // buffer each time it needs one. We are responsible for freeing this
  171. // buffer. This also allows the adapter to be configured to support
  172. // additional sense data beyond the minimum 18 bytes.
  173. //
  174. SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE);
  175. if (fdoExtension->DeviceDescriptor->CommandQueueing &&
  176. fdoExtension->AdapterDescriptor->CommandQueueing) {
  177. SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_QUEUE_ACTION_ENABLE);
  178. }
  179. //
  180. // Look for controllers that require special flags.
  181. //
  182. ClassScanForSpecial(fdoExtension, DiskBadControllers, DiskSetSpecialHacks);
  183. srbFlags = fdoExtension->SrbFlags;
  184. //
  185. // Clear buffer for drive geometry.
  186. //
  187. RtlZeroMemory(&(fdoExtension->DiskGeometry),
  188. sizeof(DISK_GEOMETRY));
  189. //
  190. // Allocate request sense buffer.
  191. //
  192. fdoExtension->SenseData = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
  193. SENSE_BUFFER_SIZE,
  194. DISK_TAG_START);
  195. if (fdoExtension->SenseData == NULL) {
  196. //
  197. // The buffer can not be allocated.
  198. //
  199. DebugPrint((1, "DiskInitFdo: Can not allocate request sense buffer\n"));
  200. status = STATUS_INSUFFICIENT_RESOURCES;
  201. return status;
  202. }
  203. //
  204. // Physical device object will describe the entire
  205. // device, starting at byte offset 0.
  206. //
  207. fdoExtension->CommonExtension.StartingOffset.QuadPart = (LONGLONG)(0);
  208. //
  209. // Set timeout value in seconds.
  210. //
  211. timeOut = ClassQueryTimeOutRegistryValue(Fdo);
  212. if (timeOut) {
  213. fdoExtension->TimeOutValue = timeOut;
  214. } else {
  215. fdoExtension->TimeOutValue = SCSI_DISK_TIMEOUT;
  216. }
  217. //
  218. // If this is a removable drive, build an entry in devicemap\scsi
  219. // indicating it's physicaldriveN name, set up the appropriate
  220. // update partitions routine and set the flags correctly.
  221. // note: only do this after the timeout value is set, above.
  222. //
  223. if (TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) {
  224. ClassUpdateInformationInRegistry( Fdo,
  225. "PhysicalDrive",
  226. fdoExtension->DeviceNumber,
  227. NULL,
  228. 0);
  229. //
  230. // Enable media change notification for removable disks
  231. //
  232. ClassInitializeMediaChangeDetection(fdoExtension,
  233. "Disk");
  234. diskData->UpdatePartitionRoutine = DiskUpdateRemovablePartitions;
  235. } else {
  236. SET_FLAG(fdoExtension->DeviceFlags, DEV_SAFE_START_UNIT);
  237. SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE);
  238. diskData->UpdatePartitionRoutine = DiskUpdatePartitions;
  239. }
  240. //
  241. // Read the drive capacity. Don't use the disk version of the routine here
  242. // since we don't know the disk signature yet - the disk version will
  243. // attempt to determine the BIOS reported geometry.
  244. //
  245. ClassReadDriveCapacity(Fdo);
  246. //
  247. // Set up sector size fields.
  248. //
  249. // Stack variables will be used to update
  250. // the partition device extensions.
  251. //
  252. // The device extension field SectorShift is
  253. // used to calculate sectors in I/O transfers.
  254. //
  255. // The DiskGeometry structure is used to service
  256. // IOCTls used by the format utility.
  257. //
  258. bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector;
  259. //
  260. // Make sure sector size is not zero.
  261. //
  262. if (bytesPerSector == 0) {
  263. //
  264. // Default sector size for disk is 512.
  265. //
  266. bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector = 512;
  267. fdoExtension->SectorShift = 9;
  268. }
  269. //
  270. // Determine is DM Driver is loaded on an IDE drive that is
  271. // under control of Atapi - this could be either a crashdump or
  272. // an Atapi device is sharing the controller with an IDE disk.
  273. //
  274. HalExamineMBR(fdoExtension->CommonExtension.DeviceObject,
  275. fdoExtension->DiskGeometry.BytesPerSector,
  276. (ULONG)0x54,
  277. &dmSkew);
  278. if (dmSkew) {
  279. //
  280. // Update the device extension, so that the call to IoReadPartitionTable
  281. // will get the correct information. Any I/O to this disk will have
  282. // to be skewed by *dmSkew sectors aka DMByteSkew.
  283. //
  284. fdoExtension->DMSkew = *dmSkew;
  285. fdoExtension->DMActive = TRUE;
  286. fdoExtension->DMByteSkew = fdoExtension->DMSkew * bytesPerSector;
  287. ExFreePool(dmSkew);
  288. }
  289. #if defined(_X86_)
  290. //
  291. // Try to read the signature off the disk and determine the correct drive
  292. // geometry based on that. This requires rereading the disk size to get
  293. // the cylinder count updated correctly.
  294. //
  295. if(!TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) {
  296. DiskReadSignature(Fdo);
  297. DiskReadDriveCapacity(Fdo);
  298. if (diskData->GeometrySource == DiskGeometryUnknown)
  299. {
  300. //
  301. // Neither the BIOS nor the port driver could provide us with a reliable
  302. // geometry. Before we use the default, look to see if it was partitioned
  303. // under Windows NT4 [or earlier] and apply the one that was used back then
  304. //
  305. if (DiskIsNT4Geometry(fdoExtension))
  306. {
  307. diskData->RealGeometry = fdoExtension->DiskGeometry;
  308. diskData->RealGeometry.SectorsPerTrack = 0x20;
  309. diskData->RealGeometry.TracksPerCylinder = 0x40;
  310. fdoExtension->DiskGeometry = diskData->RealGeometry;
  311. diskData->GeometrySource = DiskGeometryFromNT4;
  312. }
  313. }
  314. }
  315. #endif
  316. //
  317. // Register interfaces for this device
  318. //
  319. {
  320. UNICODE_STRING interfaceName;
  321. RtlInitUnicodeString(&interfaceName, NULL);
  322. status = IoRegisterDeviceInterface(fdoExtension->LowerPdo,
  323. (LPGUID) &DiskClassGuid,
  324. NULL,
  325. &interfaceName);
  326. if(NT_SUCCESS(status)) {
  327. diskData->DiskInterfaceString = interfaceName;
  328. status = IoSetDeviceInterfaceState(&interfaceName, TRUE);
  329. } else {
  330. interfaceName.Buffer = NULL;
  331. }
  332. if(!NT_SUCCESS(status)) {
  333. DebugPrint((1, "DiskInitFdo: Unable to register or set disk DCA "
  334. "for fdo %p [%lx]\n", Fdo, status));
  335. RtlFreeUnicodeString(&interfaceName);
  336. RtlInitUnicodeString(&(diskData->DiskInterfaceString), NULL);
  337. }
  338. }
  339. DiskCreateSymbolicLinks(Fdo);
  340. //
  341. // Determine the type of disk and enable failure preiction in the hardware
  342. // and enable failure prediction polling.
  343. //
  344. if (*InitSafeBootMode == 0)
  345. {
  346. DiskDetectFailurePrediction(fdoExtension,
  347. &diskData->FailurePredictionCapability);
  348. if (diskData->FailurePredictionCapability != FailurePredictionNone)
  349. {
  350. //
  351. // Cool, we've got some sort of failure prediction, enable it
  352. // at the hardware and then enable polling for it
  353. //
  354. //
  355. // By default we allow performance to be degradeded if failure
  356. // prediction is enabled.
  357. //
  358. // TODO: Make a registry entry ?
  359. //
  360. diskData->AllowFPPerfHit = TRUE;
  361. //
  362. // Enable polling only after Atapi and SBP2 add support for the new
  363. // SRB flag that indicates that the request should not reset the
  364. // drive spin down idle timer.
  365. //
  366. status = DiskEnableDisableFailurePredictPolling(fdoExtension,
  367. TRUE,
  368. DISK_DEFAULT_FAILURE_POLLING_PERIOD);
  369. DebugPrint((3, "DiskInitFdo: Failure Prediction Poll enabled as "
  370. "%d for device %p\n",
  371. diskData->FailurePredictionCapability,
  372. Fdo));
  373. }
  374. } else {
  375. //
  376. // In safe boot mode we do not enable failure prediction, as perhaps
  377. // it is the reason why normal boot does not work
  378. //
  379. diskData->FailurePredictionCapability = FailurePredictionNone;
  380. }
  381. //
  382. // Initialize the verify mutex
  383. //
  384. KeInitializeMutex(&diskData->VerifyMutex, MAX_SECTORS_PER_VERIFY);
  385. //
  386. // Initialize the flush group context
  387. //
  388. RtlZeroMemory(&diskData->FlushContext, sizeof(DISK_GROUP_CONTEXT));
  389. InitializeListHead(&diskData->FlushContext.CurrList);
  390. InitializeListHead(&diskData->FlushContext.NextList);
  391. KeInitializeMutex(&diskData->FlushContext.Mutex, 0);
  392. KeInitializeEvent(&diskData->FlushContext.Event, SynchronizationEvent, FALSE);
  393. return STATUS_SUCCESS;
  394. } // end DiskInitFdo()
  395. NTSTATUS
  396. DiskInitPdo(
  397. IN PDEVICE_OBJECT Pdo
  398. )
  399. /*++
  400. Routine Description:
  401. This routine will create the well known names for a PDO and register
  402. it's device interfaces.
  403. --*/
  404. {
  405. PCOMMON_DEVICE_EXTENSION pdoExtension = Pdo->DeviceExtension;
  406. PDISK_DATA diskData = pdoExtension->DriverData;
  407. UNICODE_STRING interfaceName;
  408. NTSTATUS status;
  409. PAGED_CODE();
  410. DiskCreateSymbolicLinks(Pdo);
  411. //
  412. // Register interfaces for this device
  413. //
  414. RtlInitUnicodeString(&interfaceName, NULL);
  415. status = IoRegisterDeviceInterface(Pdo,
  416. (LPGUID) &PartitionClassGuid,
  417. NULL,
  418. &interfaceName);
  419. if(NT_SUCCESS(status)) {
  420. diskData->PartitionInterfaceString = interfaceName;
  421. status = IoSetDeviceInterfaceState(&interfaceName, TRUE);
  422. } else {
  423. interfaceName.Buffer = NULL;
  424. }
  425. if(!NT_SUCCESS(status)) {
  426. DebugPrint((1, "DiskInitPdo: Unable to register partition DCA for "
  427. "pdo %p [%lx]\n", Pdo, status));
  428. RtlFreeUnicodeString(&interfaceName);
  429. RtlInitUnicodeString(&(diskData->PartitionInterfaceString), NULL);
  430. }
  431. return STATUS_SUCCESS;
  432. }
  433. NTSTATUS
  434. DiskStartPdo(
  435. IN PDEVICE_OBJECT Pdo
  436. )
  437. /*++
  438. Routine Description:
  439. This routine will create the well known names for a PDO and register
  440. it's device interfaces.
  441. --*/
  442. {
  443. PAGED_CODE();
  444. return STATUS_SUCCESS;
  445. }
  446. NTSTATUS
  447. DiskStopDevice(
  448. IN PDEVICE_OBJECT DeviceObject,
  449. IN UCHAR Type
  450. )
  451. {
  452. PFUNCTIONAL_DEVICE_EXTENSION fdo = DeviceObject->DeviceExtension;
  453. if(fdo->CommonExtension.IsFdo) {
  454. DiskAcquirePartitioningLock(fdo);
  455. DiskInvalidatePartitionTable(fdo, TRUE);
  456. DiskReleasePartitioningLock(fdo);
  457. }
  458. return STATUS_SUCCESS;
  459. }
  460. NTSTATUS
  461. DiskQueryId(
  462. IN PDEVICE_OBJECT Pdo,
  463. IN BUS_QUERY_ID_TYPE IdType,
  464. IN PUNICODE_STRING UnicodeIdString
  465. )
  466. /*++
  467. Routine Description:
  468. This routine generates the PNP id's for the disk's "children". If the
  469. specified ID isn't one that the routine can generate it must return
  470. STATUS_NOT_IMPLEMENTED so classpnp will know not to do anything with the
  471. PNP request's status.
  472. This routine allocates the buffer for the UnicodeIdString. It is the
  473. caller's responsibility to free the buffer when it's done.
  474. Arguments:
  475. Pdo - a pointer to the PDO we are to generate an ID for
  476. IdType - the type of ID to be generated
  477. UnicodeIdString - a string to put the results into.
  478. Return Value:
  479. STATUS_SUCCCESS if successful
  480. STATUS_NOT_IMPLEMENTED if the IdType is not one supported by this routine
  481. error status otherwise.
  482. --*/
  483. {
  484. ANSI_STRING ansiIdString;
  485. NTSTATUS status;
  486. PAGED_CODE();
  487. ASSERT_PDO(Pdo);
  488. if (IdType == BusQueryDeviceID) {
  489. if (!TEST_FLAG(Pdo->Characteristics, FILE_REMOVABLE_MEDIA)) {
  490. RtlInitAnsiString(&ansiIdString, "STORAGE\\Partition");
  491. return RtlAnsiStringToUnicodeString(UnicodeIdString, &ansiIdString, TRUE);
  492. }
  493. RtlInitAnsiString(&ansiIdString,
  494. "STORAGE\\RemovableMedia");
  495. return RtlAnsiStringToUnicodeString(UnicodeIdString, &ansiIdString, TRUE);
  496. }
  497. if (IdType == BusQueryInstanceID) {
  498. PPHYSICAL_DEVICE_EXTENSION pdoExtension = Pdo->DeviceExtension;
  499. PCOMMON_DEVICE_EXTENSION commonExtension = Pdo->DeviceExtension;
  500. PDISK_DATA diskData = commonExtension->PartitionZeroExtension->CommonExtension.DriverData;
  501. UCHAR string[64] = { 0 };
  502. if (!TEST_FLAG(Pdo->Characteristics, FILE_REMOVABLE_MEDIA)) {
  503. if (diskData->PartitionStyle == PARTITION_STYLE_MBR) {
  504. _snprintf(string, sizeof(string) - 1,
  505. "S%08lx_O%I64lx_L%I64lx",
  506. diskData->Mbr.Signature,
  507. commonExtension->StartingOffset.QuadPart,
  508. commonExtension->PartitionLength.QuadPart);
  509. } else {
  510. _snprintf(string, sizeof(string) - 1,
  511. "S%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02xS_O%I64lx_L%I64lx",
  512. diskData->Efi.DiskId.Data1,
  513. diskData->Efi.DiskId.Data2,
  514. diskData->Efi.DiskId.Data3,
  515. diskData->Efi.DiskId.Data4[0],
  516. diskData->Efi.DiskId.Data4[1],
  517. diskData->Efi.DiskId.Data4[2],
  518. diskData->Efi.DiskId.Data4[3],
  519. diskData->Efi.DiskId.Data4[4],
  520. diskData->Efi.DiskId.Data4[5],
  521. diskData->Efi.DiskId.Data4[6],
  522. diskData->Efi.DiskId.Data4[7],
  523. commonExtension->StartingOffset.QuadPart,
  524. commonExtension->PartitionLength.QuadPart);
  525. }
  526. } else {
  527. sprintf(string, "RM");
  528. }
  529. RtlInitAnsiString(&ansiIdString, string);
  530. return RtlAnsiStringToUnicodeString(UnicodeIdString, &ansiIdString, TRUE);
  531. }
  532. if((IdType == BusQueryHardwareIDs) || (IdType == BusQueryCompatibleIDs)) {
  533. RtlInitAnsiString(&ansiIdString, "STORAGE\\Volume");
  534. UnicodeIdString->MaximumLength = (USHORT) RtlAnsiStringToUnicodeSize(&ansiIdString) + sizeof(UNICODE_NULL);
  535. UnicodeIdString->Buffer = ExAllocatePoolWithTag(PagedPool,
  536. UnicodeIdString->MaximumLength,
  537. DISK_TAG_PNP_ID);
  538. if(UnicodeIdString->Buffer == NULL) {
  539. return STATUS_INSUFFICIENT_RESOURCES;
  540. }
  541. RtlZeroMemory(UnicodeIdString->Buffer, UnicodeIdString->MaximumLength);
  542. return RtlAnsiStringToUnicodeString(UnicodeIdString,
  543. &ansiIdString,
  544. FALSE);
  545. }
  546. return STATUS_NOT_IMPLEMENTED;
  547. }
  548. NTSTATUS
  549. DiskGenerateDeviceName(
  550. IN BOOLEAN IsFdo,
  551. IN ULONG DeviceNumber,
  552. IN OPTIONAL ULONG PartitionNumber,
  553. IN OPTIONAL PLARGE_INTEGER StartingOffset,
  554. IN OPTIONAL PLARGE_INTEGER PartitionLength,
  555. OUT PUCHAR *RawName
  556. )
  557. /*++
  558. Routine Description:
  559. This routine will allocate a unicode string buffer and then fill it in
  560. with a generated name for the specified device object.
  561. It is the responsibility of the user to allocate a UNICODE_STRING structure
  562. to pass in and to free UnicodeName->Buffer when done with it.
  563. Arguments:
  564. DeviceObject - a pointer to the device object
  565. UnicodeName - a unicode string to put the name buffer into
  566. Return Value:
  567. status
  568. --*/
  569. #define PDO_NAME_FORMAT "\\Device\\Harddisk%d\\DP(%d)%#I64x-%#I64x+%lx"
  570. #define FDO_NAME_FORMAT "\\Device\\Harddisk%d\\DR%d"
  571. {
  572. UCHAR rawName[64] = { 0 };
  573. PAGED_CODE();
  574. if(!IsFdo) {
  575. ASSERT(ARGUMENT_PRESENT((PVOID)(ULONG_PTR) PartitionNumber));
  576. ASSERT(ARGUMENT_PRESENT(PartitionLength));
  577. ASSERT(ARGUMENT_PRESENT(StartingOffset));
  578. _snprintf(rawName, sizeof(rawName) - 1, PDO_NAME_FORMAT, DeviceNumber, PartitionNumber,
  579. StartingOffset->QuadPart,
  580. PartitionLength->QuadPart,
  581. diskDeviceSequenceNumber++);
  582. } else {
  583. ASSERT(!ARGUMENT_PRESENT((PVOID)(ULONG_PTR) PartitionNumber));
  584. ASSERT(!ARGUMENT_PRESENT(PartitionLength));
  585. ASSERT(!ARGUMENT_PRESENT(StartingOffset));
  586. _snprintf(rawName, sizeof(rawName) - 1, FDO_NAME_FORMAT, DeviceNumber,
  587. diskDeviceSequenceNumber++);
  588. }
  589. *RawName = ExAllocatePoolWithTag(PagedPool,
  590. strlen(rawName) + 1,
  591. DISK_TAG_NAME);
  592. if(*RawName == NULL) {
  593. return STATUS_INSUFFICIENT_RESOURCES;
  594. }
  595. strncpy(*RawName, rawName, strlen(rawName) + 1);
  596. DebugPrint((2, "DiskGenerateDeviceName: generated \"%s\"\n", rawName));
  597. return STATUS_SUCCESS;
  598. }
  599. VOID
  600. DiskCreateSymbolicLinks(
  601. IN PDEVICE_OBJECT DeviceObject
  602. )
  603. /*++
  604. Routine Description:
  605. This routine will generate a symbolic link for the specified device object
  606. using the well known form \\Device\HarddiskX\PartitionY, where X and Y are
  607. filled in using the partition information in the device object's extension.
  608. This routine will not try to delete any previous symbolic link for the
  609. same generated name - the caller must make sure the symbolic link has
  610. been broken before calling this routine.
  611. Arguments:
  612. DeviceObject - the device object to make a well known name for
  613. Return Value:
  614. STATUS
  615. --*/
  616. {
  617. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  618. PDISK_DATA diskData = commonExtension->DriverData;
  619. WCHAR wideSourceName[64] = { 0 };
  620. UNICODE_STRING unicodeSourceName;
  621. NTSTATUS status;
  622. PAGED_CODE();
  623. //
  624. // Build the destination for the link first using the device name
  625. // stored in the device object
  626. //
  627. ASSERT(commonExtension->DeviceName.Buffer);
  628. if(!diskData->LinkStatus.WellKnownNameCreated) {
  629. //
  630. // Put together the source name using the partition and device number
  631. // in the device extension and disk data segment
  632. //
  633. _snwprintf(wideSourceName, sizeof(wideSourceName) / sizeof(wideSourceName[0]) - 1, L"\\Device\\Harddisk%d\\Partition%d",
  634. commonExtension->PartitionZeroExtension->DeviceNumber,
  635. (commonExtension->IsFdo ?
  636. 0 :
  637. commonExtension->PartitionNumber));
  638. RtlInitUnicodeString(&unicodeSourceName, wideSourceName);
  639. DebugPrint((1, "DiskCreateSymbolicLink: Linking %wZ to %wZ\n",
  640. &unicodeSourceName,
  641. &commonExtension->DeviceName));
  642. status = IoCreateSymbolicLink(&unicodeSourceName,
  643. &commonExtension->DeviceName);
  644. if(NT_SUCCESS(status)){
  645. diskData->LinkStatus.WellKnownNameCreated = TRUE;
  646. }
  647. }
  648. if((!diskData->LinkStatus.PhysicalDriveLinkCreated) &&
  649. (commonExtension->IsFdo)) {
  650. //
  651. // Create a physical drive N link using the device number we saved
  652. // away during AddDevice.
  653. //
  654. _snwprintf(wideSourceName, sizeof(wideSourceName) / sizeof(wideSourceName[0]) - 1,
  655. L"\\DosDevices\\PhysicalDrive%d",
  656. commonExtension->PartitionZeroExtension->DeviceNumber);
  657. RtlInitUnicodeString(&unicodeSourceName, wideSourceName);
  658. DebugPrint((1, "DiskCreateSymbolicLink: Linking %wZ to %wZ\n",
  659. &unicodeSourceName,
  660. &(commonExtension->DeviceName)));
  661. status = IoCreateSymbolicLink(&unicodeSourceName,
  662. &(commonExtension->DeviceName));
  663. if(NT_SUCCESS(status)) {
  664. diskData->LinkStatus.PhysicalDriveLinkCreated = TRUE;
  665. }
  666. } else if(commonExtension->IsFdo == FALSE) {
  667. diskData->LinkStatus.PhysicalDriveLinkCreated = FALSE;
  668. }
  669. return;
  670. }
  671. VOID
  672. DiskDeleteSymbolicLinks(
  673. IN PDEVICE_OBJECT DeviceObject
  674. )
  675. /*++
  676. Routine Description:
  677. This routine will delete the well known name (symlink) for the specified
  678. device. It generates the link name using information stored in the
  679. device extension
  680. Arguments:
  681. DeviceObject - the device object we are unlinking
  682. Return Value:
  683. status
  684. --*/
  685. {
  686. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  687. PDISK_DATA diskData = commonExtension->DriverData;
  688. WCHAR wideLinkName[64] = { 0 };
  689. UNICODE_STRING unicodeLinkName;
  690. PAGED_CODE();
  691. if(diskData->LinkStatus.WellKnownNameCreated) {
  692. _snwprintf(wideLinkName, sizeof(wideLinkName) / sizeof(wideLinkName[0]) - 1,
  693. L"\\Device\\Harddisk%d\\Partition%d",
  694. commonExtension->PartitionZeroExtension->DeviceNumber,
  695. (commonExtension->IsFdo ? 0 :
  696. commonExtension->PartitionNumber));
  697. RtlInitUnicodeString(&unicodeLinkName, wideLinkName);
  698. IoDeleteSymbolicLink(&unicodeLinkName);
  699. diskData->LinkStatus.WellKnownNameCreated = FALSE;
  700. }
  701. if(diskData->LinkStatus.PhysicalDriveLinkCreated) {
  702. ASSERT_FDO(DeviceObject);
  703. _snwprintf(wideLinkName, sizeof(wideLinkName) / sizeof(wideLinkName[0]) - 1,
  704. L"\\DosDevices\\PhysicalDrive%d",
  705. commonExtension->PartitionZeroExtension->DeviceNumber);
  706. RtlInitUnicodeString(&unicodeLinkName, wideLinkName);
  707. IoDeleteSymbolicLink(&unicodeLinkName);
  708. diskData->LinkStatus.PhysicalDriveLinkCreated = FALSE;
  709. }
  710. return;
  711. }
  712. NTSTATUS
  713. DiskRemoveDevice(
  714. IN PDEVICE_OBJECT DeviceObject,
  715. IN UCHAR Type
  716. )
  717. /*++
  718. Routine Description:
  719. This routine will release any resources the device may have allocated for
  720. this device object and return.
  721. Arguments:
  722. DeviceObject - the device object being removed
  723. Return Value:
  724. status
  725. --*/
  726. {
  727. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  728. PDISK_DATA diskData = commonExtension->DriverData;
  729. PAGED_CODE();
  730. //
  731. // Handle query and cancel
  732. //
  733. if((Type == IRP_MN_QUERY_REMOVE_DEVICE) ||
  734. (Type == IRP_MN_CANCEL_REMOVE_DEVICE)) {
  735. return STATUS_SUCCESS;
  736. }
  737. if(commonExtension->IsFdo) {
  738. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension =
  739. DeviceObject->DeviceExtension;
  740. //
  741. // Purge the cached partition table (if any).
  742. //
  743. DiskAcquirePartitioningLock(fdoExtension);
  744. DiskInvalidatePartitionTable(fdoExtension, TRUE);
  745. DiskReleasePartitioningLock(fdoExtension);
  746. //
  747. // Delete our object directory.
  748. //
  749. if(fdoExtension->AdapterDescriptor) {
  750. ExFreePool(fdoExtension->AdapterDescriptor);
  751. fdoExtension->AdapterDescriptor = NULL;
  752. }
  753. if(fdoExtension->DeviceDescriptor) {
  754. ExFreePool(fdoExtension->DeviceDescriptor);
  755. fdoExtension->DeviceDescriptor = NULL;
  756. }
  757. if(fdoExtension->DeviceDirectory != NULL) {
  758. ZwMakeTemporaryObject(fdoExtension->DeviceDirectory);
  759. ZwClose(fdoExtension->DeviceDirectory);
  760. fdoExtension->DeviceDirectory = NULL;
  761. }
  762. if(Type == IRP_MN_REMOVE_DEVICE) {
  763. if(fdoExtension->SenseData) {
  764. ExFreePool(fdoExtension->SenseData);
  765. fdoExtension->SenseData = NULL;
  766. }
  767. IoGetConfigurationInformation()->DiskCount--;
  768. }
  769. } else {
  770. PPHYSICAL_DEVICE_EXTENSION pdoExtension = DeviceObject->DeviceExtension;
  771. }
  772. DiskDeleteSymbolicLinks(DeviceObject);
  773. //
  774. // Release the mounted device interface if we've set it.
  775. //
  776. if(diskData->PartitionInterfaceString.Buffer != NULL) {
  777. IoSetDeviceInterfaceState(&(diskData->PartitionInterfaceString), FALSE);
  778. RtlFreeUnicodeString(&(diskData->PartitionInterfaceString));
  779. RtlInitUnicodeString(&(diskData->PartitionInterfaceString), NULL);
  780. }
  781. if(diskData->DiskInterfaceString.Buffer != NULL) {
  782. IoSetDeviceInterfaceState(&(diskData->DiskInterfaceString), FALSE);
  783. RtlFreeUnicodeString(&(diskData->DiskInterfaceString));
  784. RtlInitUnicodeString(&(diskData->DiskInterfaceString), NULL);
  785. }
  786. if (Type == IRP_MN_REMOVE_DEVICE)
  787. {
  788. ClassDeleteSrbLookasideList(commonExtension);
  789. }
  790. return STATUS_SUCCESS;
  791. }
  792. NTSTATUS
  793. DiskStartFdo(
  794. IN PDEVICE_OBJECT Fdo
  795. )
  796. /*++
  797. Routine Description:
  798. This routine will query the underlying device for any information necessary
  799. to complete initialization of the device. This will include physical
  800. disk geometry, mode sense information and such.
  801. This routine does not perform partition enumeration - that is left to the
  802. re-enumeration routine
  803. If this routine fails it will return an error value. It does not clean up
  804. any resources - that is left for the Stop/Remove routine.
  805. Arguments:
  806. Fdo - a pointer to the functional device object for this device
  807. Return Value:
  808. status
  809. --*/
  810. {
  811. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  812. PCOMMON_DEVICE_EXTENSION commonExtension = &(fdoExtension->CommonExtension);
  813. PDISK_DATA diskData = commonExtension->DriverData;
  814. STORAGE_HOTPLUG_INFO hotplugInfo = { 0 };
  815. DISK_CACHE_INFORMATION cacheInfo = { 0 };
  816. ULONG isPowerProtected = 0;
  817. NTSTATUS status;
  818. PAGED_CODE();
  819. //
  820. // Get the hotplug information, so we can turn off write cache if needed
  821. //
  822. // NOTE: Capabilities info is not good enough to determine hotplugedness
  823. // as we cannot determine device relations information and other
  824. // dependencies. Get the hotplug info instead
  825. //
  826. {
  827. PIRP irp;
  828. KEVENT event;
  829. IO_STATUS_BLOCK statusBlock = { 0 };
  830. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  831. irp = IoBuildDeviceIoControlRequest(IOCTL_STORAGE_GET_HOTPLUG_INFO,
  832. Fdo,
  833. NULL,
  834. 0L,
  835. &hotplugInfo,
  836. sizeof(STORAGE_HOTPLUG_INFO),
  837. FALSE,
  838. &event,
  839. &statusBlock);
  840. if (irp != NULL) {
  841. // send to self -- classpnp handles this
  842. status = IoCallDriver(Fdo, irp);
  843. if (status == STATUS_PENDING) {
  844. KeWaitForSingleObject(&event,
  845. Executive,
  846. KernelMode,
  847. FALSE,
  848. NULL);
  849. status = statusBlock.Status;
  850. }
  851. }
  852. }
  853. //
  854. // Clear the DEV_WRITE_CACHE flag now and set
  855. // it below only if we read that from the disk
  856. //
  857. CLEAR_FLAG(fdoExtension->DeviceFlags, DEV_WRITE_CACHE);
  858. diskData->WriteCacheOverride = DiskWriteCacheDefault;
  859. //
  860. // Look into the registry to see if the user
  861. // has chosen to override the default setting
  862. //
  863. ClassGetDeviceParameter(fdoExtension,
  864. DiskDeviceParameterSubkey,
  865. DiskDeviceUserWriteCacheSetting,
  866. (PULONG)&diskData->WriteCacheOverride);
  867. if (diskData->WriteCacheOverride == DiskWriteCacheDefault)
  868. {
  869. //
  870. // The user has not overridden the default settings
  871. //
  872. if (TEST_FLAG(fdoExtension->ScanForSpecialFlags, CLASS_SPECIAL_DISABLE_WRITE_CACHE))
  873. {
  874. //
  875. // This flag indicates that we have faulty firmware and this
  876. // may cause the filesystem to refuse to mount on this media
  877. //
  878. DebugPrint((ClassDebugWarning, "DiskStartFdo: Turning off write cache for %p due to a firmware issue\n", Fdo));
  879. diskData->WriteCacheOverride = DiskWriteCacheDisable;
  880. }
  881. else if (hotplugInfo.DeviceHotplug && !hotplugInfo.WriteCacheEnableOverride)
  882. {
  883. //
  884. // This flag indicates that the device is hotpluggable making it unsafe to enable caching
  885. //
  886. DebugPrint((ClassDebugWarning, "DiskStartFdo: Turning off write cache for %p due to hotpluggable device\n", Fdo));
  887. diskData->WriteCacheOverride = DiskWriteCacheDisable;
  888. }
  889. else if (hotplugInfo.MediaHotplug)
  890. {
  891. //
  892. // This flag indicates that the media in the device cannot be reliably locked
  893. //
  894. DebugPrint((ClassDebugWarning, "DiskStartFdo: Turning off write cache for %p due to unlockable media\n", Fdo));
  895. diskData->WriteCacheOverride = DiskWriteCacheDisable;
  896. }
  897. else
  898. {
  899. //
  900. // Even though the device does not seem to have any obvious problems
  901. // we leave it to the user to modify the previous write cache setting
  902. //
  903. }
  904. }
  905. //
  906. // Query the disk to see if write cache is enabled
  907. // and set the DEV_WRITE_CACHE flag appropriately
  908. //
  909. status = DiskGetCacheInformation(fdoExtension, &cacheInfo);
  910. if (NT_SUCCESS(status))
  911. {
  912. if (cacheInfo.WriteCacheEnabled == TRUE)
  913. {
  914. SET_FLAG(fdoExtension->DeviceFlags, DEV_WRITE_CACHE);
  915. if (diskData->WriteCacheOverride == DiskWriteCacheDisable)
  916. {
  917. //
  918. // Write cache is currently enabled on this
  919. // device, but we would like to turn it off
  920. //
  921. cacheInfo.WriteCacheEnabled = FALSE;
  922. status = DiskSetCacheInformation(fdoExtension, &cacheInfo);
  923. }
  924. }
  925. else
  926. {
  927. if (diskData->WriteCacheOverride == DiskWriteCacheEnable)
  928. {
  929. //
  930. // Write cache is currently disabled on this
  931. // device, but we would like to turn it on
  932. //
  933. cacheInfo.WriteCacheEnabled = TRUE;
  934. status = DiskSetCacheInformation(fdoExtension, &cacheInfo);
  935. }
  936. }
  937. }
  938. //
  939. // Query the registry to see if this disk is power-protected or not
  940. //
  941. CLEAR_FLAG(fdoExtension->DeviceFlags, DEV_POWER_PROTECTED);
  942. ClassGetDeviceParameter(fdoExtension, DiskDeviceParameterSubkey, DiskDeviceCacheIsPowerProtected, &isPowerProtected);
  943. if (isPowerProtected == 1)
  944. {
  945. SET_FLAG(fdoExtension->DeviceFlags, DEV_POWER_PROTECTED);
  946. }
  947. //
  948. // In the event that there's a cached partition table flush it now.
  949. //
  950. DiskAcquirePartitioningLock(fdoExtension);
  951. DiskInvalidatePartitionTable(fdoExtension, TRUE);
  952. DiskReleasePartitioningLock(fdoExtension);
  953. //
  954. // Get the SCSI address if it's available for use with SMART ioctls.
  955. //
  956. {
  957. PIRP irp;
  958. KEVENT event;
  959. IO_STATUS_BLOCK statusBlock = { 0 };
  960. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  961. irp = IoBuildDeviceIoControlRequest(IOCTL_SCSI_GET_ADDRESS,
  962. commonExtension->LowerDeviceObject,
  963. NULL,
  964. 0L,
  965. &(diskData->ScsiAddress),
  966. sizeof(SCSI_ADDRESS),
  967. FALSE,
  968. &event,
  969. &statusBlock);
  970. if(irp != NULL) {
  971. status = IoCallDriver(commonExtension->LowerDeviceObject, irp);
  972. if(status == STATUS_PENDING) {
  973. KeWaitForSingleObject(&event,
  974. Executive,
  975. KernelMode,
  976. FALSE,
  977. NULL);
  978. status = statusBlock.Status;
  979. }
  980. }
  981. }
  982. return STATUS_SUCCESS;
  983. } // end DiskStartFdo()