Source code of Windows XP (NT5)
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.

9178 lines
272 KiB

  1. /*++
  2. Copyright (C) Microsoft Corporation, 1991 - 1999
  3. Module Name:
  4. class.c
  5. Abstract:
  6. SCSI class driver routines
  7. Environment:
  8. kernel mode only
  9. Notes:
  10. Revision History:
  11. --*/
  12. #define CLASS_INIT_GUID 1
  13. #include "classp.h"
  14. #include "debug.h"
  15. #ifdef ALLOC_PRAGMA
  16. #pragma alloc_text(INIT, DriverEntry)
  17. #pragma alloc_text(PAGE, ClassAddDevice)
  18. #pragma alloc_text(PAGE, ClassClaimDevice)
  19. #pragma alloc_text(PAGE, ClassCreateDeviceObject)
  20. #pragma alloc_text(PAGE, ClassDispatchPnp)
  21. #pragma alloc_text(PAGE, ClassGetDescriptor)
  22. #pragma alloc_text(PAGE, ClassGetPdoId)
  23. #pragma alloc_text(PAGE, ClassInitialize)
  24. #pragma alloc_text(PAGE, ClassInitializeEx)
  25. #pragma alloc_text(PAGE, ClassInvalidateBusRelations)
  26. #pragma alloc_text(PAGE, ClassMarkChildMissing)
  27. #pragma alloc_text(PAGE, ClassMarkChildrenMissing)
  28. #pragma alloc_text(PAGE, ClassModeSense)
  29. #pragma alloc_text(PAGE, ClassPnpQueryFdoRelations)
  30. #pragma alloc_text(PAGE, ClassPnpStartDevice)
  31. #pragma alloc_text(PAGE, ClassQueryPnpCapabilities)
  32. #pragma alloc_text(PAGE, ClassQueryTimeOutRegistryValue)
  33. #pragma alloc_text(PAGE, ClassRemoveDevice)
  34. #pragma alloc_text(PAGE, ClassRetrieveDeviceRelations)
  35. #pragma alloc_text(PAGE, ClassUpdateInformationInRegistry)
  36. #pragma alloc_text(PAGE, ClassSendDeviceIoControlSynchronous)
  37. #pragma alloc_text(PAGE, ClassUnload)
  38. #pragma alloc_text(PAGE, ClasspAllocateReleaseRequest)
  39. #pragma alloc_text(PAGE, ClasspFreeReleaseRequest)
  40. #pragma alloc_text(PAGE, ClasspInitializeHotplugInfo)
  41. #pragma alloc_text(PAGE, ClasspRegisterMountedDeviceInterface)
  42. #pragma alloc_text(PAGE, ClasspScanForClassHacks)
  43. #pragma alloc_text(PAGE, ClasspScanForSpecialInRegistry)
  44. #endif
  45. ULONG ClassPnpAllowUnload = TRUE;
  46. #define FirstDriveLetter 'C'
  47. #define LastDriveLetter 'Z'
  48. /*++////////////////////////////////////////////////////////////////////////////
  49. DriverEntry()
  50. Routine Description:
  51. Temporary entry point needed to initialize the class system dll.
  52. It doesn't do anything.
  53. Arguments:
  54. DriverObject - Pointer to the driver object created by the system.
  55. Return Value:
  56. STATUS_SUCCESS
  57. --*/
  58. NTSTATUS
  59. DriverEntry(
  60. IN PDRIVER_OBJECT DriverObject,
  61. IN PUNICODE_STRING RegistryPath
  62. )
  63. {
  64. return STATUS_SUCCESS;
  65. }
  66. /*++////////////////////////////////////////////////////////////////////////////
  67. ClassInitialize()
  68. Routine Description:
  69. This routine is called by a class driver during its
  70. DriverEntry routine to initialize the driver.
  71. Arguments:
  72. Argument1 - Driver Object.
  73. Argument2 - Registry Path.
  74. InitializationData - Device-specific driver's initialization data.
  75. Return Value:
  76. A valid return code for a DriverEntry routine.
  77. --*/
  78. ULONG
  79. ClassInitialize(
  80. IN PVOID Argument1,
  81. IN PVOID Argument2,
  82. IN PCLASS_INIT_DATA InitializationData
  83. )
  84. {
  85. PDRIVER_OBJECT DriverObject = Argument1;
  86. PUNICODE_STRING RegistryPath = Argument2;
  87. PCLASS_DRIVER_EXTENSION driverExtension;
  88. NTSTATUS status;
  89. PAGED_CODE();
  90. DebugPrint((3,"\n\nSCSI Class Driver\n"));
  91. ClasspInitializeDebugGlobals();
  92. //
  93. // Validate the length of this structure. This is effectively a
  94. // version check.
  95. //
  96. if (InitializationData->InitializationDataSize != sizeof(CLASS_INIT_DATA)) {
  97. //
  98. // This DebugPrint is to help third-party driver writers
  99. //
  100. DebugPrint((0,"ClassInitialize: Class driver wrong version\n"));
  101. return (ULONG) STATUS_REVISION_MISMATCH;
  102. }
  103. //
  104. // Check that each required entry is not NULL. Note that Shutdown, Flush and Error
  105. // are not required entry points.
  106. //
  107. if ((!InitializationData->FdoData.ClassDeviceControl) ||
  108. (!((InitializationData->FdoData.ClassReadWriteVerification) ||
  109. (InitializationData->ClassStartIo))) ||
  110. (!InitializationData->ClassAddDevice) ||
  111. (!InitializationData->FdoData.ClassStartDevice)) {
  112. //
  113. // This DebugPrint is to help third-party driver writers
  114. //
  115. DebugPrint((0,
  116. "ClassInitialize: Class device-specific driver missing required "
  117. "FDO entry\n"));
  118. return (ULONG) STATUS_REVISION_MISMATCH;
  119. }
  120. if ((InitializationData->ClassEnumerateDevice) &&
  121. ((!InitializationData->PdoData.ClassDeviceControl) ||
  122. (!InitializationData->PdoData.ClassStartDevice) ||
  123. (!((InitializationData->PdoData.ClassReadWriteVerification) ||
  124. (InitializationData->ClassStartIo))))) {
  125. //
  126. // This DebugPrint is to help third-party driver writers
  127. //
  128. DebugPrint((0, "ClassInitialize: Class device-specific missing "
  129. "required PDO entry\n"));
  130. return (ULONG) STATUS_REVISION_MISMATCH;
  131. }
  132. if((InitializationData->FdoData.ClassStopDevice == NULL) ||
  133. ((InitializationData->ClassEnumerateDevice != NULL) &&
  134. (InitializationData->PdoData.ClassStopDevice == NULL))) {
  135. //
  136. // This DebugPrint is to help third-party driver writers
  137. //
  138. DebugPrint((0, "ClassInitialize: Class device-specific missing "
  139. "required PDO entry\n"));
  140. ASSERT(FALSE);
  141. return (ULONG) STATUS_REVISION_MISMATCH;
  142. }
  143. //
  144. // Setup the default power handlers if the class driver didn't provide
  145. // any.
  146. //
  147. if(InitializationData->FdoData.ClassPowerDevice == NULL) {
  148. InitializationData->FdoData.ClassPowerDevice = ClassMinimalPowerHandler;
  149. }
  150. if((InitializationData->ClassEnumerateDevice != NULL) &&
  151. (InitializationData->PdoData.ClassPowerDevice == NULL)) {
  152. InitializationData->PdoData.ClassPowerDevice = ClassMinimalPowerHandler;
  153. }
  154. //
  155. // warn that unload is not supported
  156. //
  157. // ISSUE-2000/02/03-peterwie
  158. // We should think about making this a fatal error.
  159. //
  160. if(InitializationData->ClassUnload == NULL) {
  161. //
  162. // This DebugPrint is to help third-party driver writers
  163. //
  164. DebugPrint((0, "ClassInitialize: driver does not support unload %wZ\n",
  165. RegistryPath));
  166. }
  167. //
  168. // Create an extension for the driver object
  169. //
  170. status = IoAllocateDriverObjectExtension(DriverObject,
  171. CLASS_DRIVER_EXTENSION_KEY,
  172. sizeof(CLASS_DRIVER_EXTENSION),
  173. &driverExtension);
  174. if(NT_SUCCESS(status)) {
  175. //
  176. // Copy the registry path into the driver extension so we can use it later
  177. //
  178. driverExtension->RegistryPath.Length = RegistryPath->Length;
  179. driverExtension->RegistryPath.MaximumLength = RegistryPath->MaximumLength;
  180. driverExtension->RegistryPath.Buffer =
  181. ExAllocatePoolWithTag(PagedPool,
  182. RegistryPath->MaximumLength,
  183. '1CcS');
  184. if(driverExtension->RegistryPath.Buffer == NULL) {
  185. status = STATUS_INSUFFICIENT_RESOURCES;
  186. return status;
  187. }
  188. RtlCopyUnicodeString(
  189. &(driverExtension->RegistryPath),
  190. RegistryPath);
  191. //
  192. // Copy the initialization data into the driver extension so we can reuse
  193. // it during our add device routine
  194. //
  195. RtlCopyMemory(
  196. &(driverExtension->InitData),
  197. InitializationData,
  198. sizeof(CLASS_INIT_DATA));
  199. driverExtension->DeviceCount = 0;
  200. } else if (status == STATUS_OBJECT_NAME_COLLISION) {
  201. //
  202. // The extension already exists - get a pointer to it
  203. //
  204. driverExtension = IoGetDriverObjectExtension(DriverObject,
  205. CLASS_DRIVER_EXTENSION_KEY);
  206. ASSERT(driverExtension != NULL);
  207. } else {
  208. DebugPrint((1, "ClassInitialize: Class driver extension could not be "
  209. "allocated %lx\n", status));
  210. return status;
  211. }
  212. //
  213. // Update driver object with entry points.
  214. //
  215. DriverObject->MajorFunction[IRP_MJ_CREATE] = ClassCreateClose;
  216. DriverObject->MajorFunction[IRP_MJ_CLOSE] = ClassCreateClose;
  217. DriverObject->MajorFunction[IRP_MJ_READ] = ClassReadWrite;
  218. DriverObject->MajorFunction[IRP_MJ_WRITE] = ClassReadWrite;
  219. DriverObject->MajorFunction[IRP_MJ_SCSI] = ClassInternalIoControl;
  220. DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = ClassDeviceControlDispatch;
  221. DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = ClassShutdownFlush;
  222. DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = ClassShutdownFlush;
  223. DriverObject->MajorFunction[IRP_MJ_PNP] = ClassDispatchPnp;
  224. DriverObject->MajorFunction[IRP_MJ_POWER] = ClassDispatchPower;
  225. DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = ClassSystemControl;
  226. if (InitializationData->ClassStartIo) {
  227. DriverObject->DriverStartIo = ClasspStartIo;
  228. }
  229. if ((InitializationData->ClassUnload) && (ClassPnpAllowUnload == TRUE)) {
  230. DriverObject->DriverUnload = ClassUnload;
  231. } else {
  232. DriverObject->DriverUnload = NULL;
  233. }
  234. DriverObject->DriverExtension->AddDevice = ClassAddDevice;
  235. status = STATUS_SUCCESS;
  236. return status;
  237. } // end ClassInitialize()
  238. /*++////////////////////////////////////////////////////////////////////////////
  239. ClassInitializeEx()
  240. Routine Description:
  241. This routine is allows the caller to do any extra initialization or
  242. setup that is not done in ClassInitialize. The operation is
  243. controlled by the GUID that is passed and the contents of the Data
  244. parameter is dependent upon the GUID.
  245. This is the list of supported operations:
  246. Guid - GUID_CLASSPNP_QUERY_REGINFOEX
  247. Data - A PCLASS_QUERY_WMI_REGINFO_EX callback function pointer
  248. Initialized classpnp to callback a PCLASS_QUERY_WMI_REGINFO_EX
  249. callback instead of a PCLASS_QUERY_WMI_REGINFO callback. The
  250. former callback allows the driver to specify the name of the
  251. mof resource.
  252. Arguments:
  253. DriverObject
  254. Guid
  255. Data
  256. Return Value:
  257. Status Code
  258. --*/
  259. ULONG
  260. ClassInitializeEx(
  261. IN PDRIVER_OBJECT DriverObject,
  262. IN LPGUID Guid,
  263. IN PVOID Data
  264. )
  265. {
  266. PCLASS_DRIVER_EXTENSION driverExtension;
  267. NTSTATUS status;
  268. PAGED_CODE();
  269. driverExtension = IoGetDriverObjectExtension( DriverObject,
  270. CLASS_DRIVER_EXTENSION_KEY
  271. );
  272. if (IsEqualGUID(Guid, &ClassGuidQueryRegInfoEx))
  273. {
  274. PCLASS_QUERY_WMI_REGINFO_EX_LIST List;
  275. //
  276. // Indicate the device supports PCLASS_QUERY_REGINFO_EX
  277. // callback instead of PCLASS_QUERY_REGINFO callback.
  278. //
  279. List = (PCLASS_QUERY_WMI_REGINFO_EX_LIST)Data;
  280. if (List->Size == sizeof(CLASS_QUERY_WMI_REGINFO_EX_LIST))
  281. {
  282. driverExtension->ClassFdoQueryWmiRegInfoEx = List->ClassFdoQueryWmiRegInfoEx;
  283. driverExtension->ClassPdoQueryWmiRegInfoEx = List->ClassPdoQueryWmiRegInfoEx;
  284. status = STATUS_SUCCESS;
  285. } else {
  286. status = STATUS_INVALID_PARAMETER;
  287. }
  288. } else {
  289. status = STATUS_NOT_SUPPORTED;
  290. }
  291. return(status);
  292. } // end ClassInitializeEx()
  293. /*++////////////////////////////////////////////////////////////////////////////
  294. ClassUnload()
  295. Routine Description:
  296. called when there are no more references to the driver. this allows
  297. drivers to be updated without rebooting.
  298. Arguments:
  299. DriverObject - a pointer to the driver object that is being unloaded
  300. Status:
  301. --*/
  302. VOID
  303. ClassUnload(
  304. IN PDRIVER_OBJECT DriverObject
  305. )
  306. {
  307. PCLASS_DRIVER_EXTENSION driverExtension;
  308. NTSTATUS status;
  309. PAGED_CODE();
  310. ASSERT( DriverObject->DeviceObject == NULL );
  311. driverExtension = IoGetDriverObjectExtension( DriverObject,
  312. CLASS_DRIVER_EXTENSION_KEY
  313. );
  314. ASSERT(driverExtension != NULL);
  315. ASSERT(driverExtension->RegistryPath.Buffer != NULL);
  316. ASSERT(driverExtension->InitData.ClassUnload != NULL);
  317. DebugPrint((1, "ClassUnload: driver unloading %wZ\n",
  318. &driverExtension->RegistryPath));
  319. //
  320. // attempt to process the driver's unload routine first.
  321. //
  322. driverExtension->InitData.ClassUnload(DriverObject);
  323. //
  324. // free own allocated resources and return
  325. //
  326. ExFreePool( driverExtension->RegistryPath.Buffer );
  327. driverExtension->RegistryPath.Buffer = NULL;
  328. driverExtension->RegistryPath.Length = 0;
  329. driverExtension->RegistryPath.MaximumLength = 0;
  330. return;
  331. } // end ClassUnload()
  332. /*++////////////////////////////////////////////////////////////////////////////
  333. ClassAddDevice()
  334. Routine Description:
  335. SCSI class driver add device routine. This is called by pnp when a new
  336. physical device come into being.
  337. This routine will call out to the class driver to verify that it should
  338. own this device then will create and attach a device object and then hand
  339. it to the driver to initialize and create symbolic links
  340. Arguments:
  341. DriverObject - a pointer to the driver object that this is being created for
  342. PhysicalDeviceObject - a pointer to the physical device object
  343. Status: STATUS_NO_SUCH_DEVICE if the class driver did not want this device
  344. STATUS_SUCCESS if the creation and attachment was successful
  345. status of device creation and initialization
  346. --*/
  347. NTSTATUS
  348. ClassAddDevice(
  349. IN PDRIVER_OBJECT DriverObject,
  350. IN PDEVICE_OBJECT PhysicalDeviceObject
  351. )
  352. {
  353. PCLASS_DRIVER_EXTENSION driverExtension =
  354. IoGetDriverObjectExtension(DriverObject,
  355. CLASS_DRIVER_EXTENSION_KEY);
  356. NTSTATUS status;
  357. PAGED_CODE();
  358. status = driverExtension->InitData.ClassAddDevice(DriverObject,
  359. PhysicalDeviceObject);
  360. return status;
  361. } // end ClassAddDevice()
  362. /*++////////////////////////////////////////////////////////////////////////////
  363. ClassDispatchPnp()
  364. Routine Description:
  365. Storage class driver pnp routine. This is called by the io system when
  366. a PNP request is sent to the device.
  367. Arguments:
  368. DeviceObject - pointer to the device object
  369. Irp - pointer to the io request packet
  370. Return Value:
  371. status
  372. --*/
  373. NTSTATUS
  374. ClassDispatchPnp(
  375. IN PDEVICE_OBJECT DeviceObject,
  376. IN PIRP Irp
  377. )
  378. {
  379. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  380. BOOLEAN isFdo = commonExtension->IsFdo;
  381. PCLASS_DRIVER_EXTENSION driverExtension;
  382. PCLASS_INIT_DATA initData;
  383. PCLASS_DEV_INFO devInfo;
  384. PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
  385. PIO_STACK_LOCATION nextIrpStack = IoGetNextIrpStackLocation(Irp);
  386. NTSTATUS status = Irp->IoStatus.Status;
  387. BOOLEAN completeRequest = TRUE;
  388. BOOLEAN lockReleased = FALSE;
  389. ULONG isRemoved;
  390. PAGED_CODE();
  391. //
  392. // Extract all the useful information out of the driver object
  393. // extension
  394. //
  395. driverExtension = IoGetDriverObjectExtension(DeviceObject->DriverObject,
  396. CLASS_DRIVER_EXTENSION_KEY);
  397. if (driverExtension){
  398. initData = &(driverExtension->InitData);
  399. if(isFdo) {
  400. devInfo = &(initData->FdoData);
  401. } else {
  402. devInfo = &(initData->PdoData);
  403. }
  404. isRemoved = ClassAcquireRemoveLock(DeviceObject, Irp);
  405. DebugPrint((2, "ClassDispatchPnp (%p,%p): minor code %#x for %s %p\n",
  406. DeviceObject, Irp,
  407. irpStack->MinorFunction,
  408. isFdo ? "fdo" : "pdo",
  409. DeviceObject));
  410. DebugPrint((2, "ClassDispatchPnp (%p,%p): previous %#x, current %#x\n",
  411. DeviceObject, Irp,
  412. commonExtension->PreviousState,
  413. commonExtension->CurrentState));
  414. switch(irpStack->MinorFunction) {
  415. case IRP_MN_START_DEVICE: {
  416. //
  417. // if this is sent to the FDO we should forward it down the
  418. // attachment chain before we start the FDO.
  419. //
  420. if (isFdo) {
  421. status = ClassForwardIrpSynchronous(commonExtension, Irp);
  422. }
  423. else {
  424. status = STATUS_SUCCESS;
  425. }
  426. if (NT_SUCCESS(status)){
  427. status = Irp->IoStatus.Status = ClassPnpStartDevice(DeviceObject);
  428. }
  429. break;
  430. }
  431. case IRP_MN_QUERY_DEVICE_RELATIONS: {
  432. DEVICE_RELATION_TYPE type =
  433. irpStack->Parameters.QueryDeviceRelations.Type;
  434. PDEVICE_RELATIONS deviceRelations = NULL;
  435. if(!isFdo) {
  436. if(type == TargetDeviceRelation) {
  437. //
  438. // Device relations has one entry built in to it's size.
  439. //
  440. status = STATUS_INSUFFICIENT_RESOURCES;
  441. deviceRelations = ExAllocatePoolWithTag(PagedPool,
  442. sizeof(DEVICE_RELATIONS),
  443. '2CcS');
  444. if(deviceRelations != NULL) {
  445. RtlZeroMemory(deviceRelations,
  446. sizeof(DEVICE_RELATIONS));
  447. Irp->IoStatus.Information = (ULONG_PTR) deviceRelations;
  448. deviceRelations->Count = 1;
  449. deviceRelations->Objects[0] = DeviceObject;
  450. ObReferenceObject(deviceRelations->Objects[0]);
  451. status = STATUS_SUCCESS;
  452. }
  453. } else {
  454. //
  455. // PDO's just complete enumeration requests without altering
  456. // the status.
  457. //
  458. status = Irp->IoStatus.Status;
  459. }
  460. break;
  461. } else if (type == BusRelations) {
  462. ASSERT(commonExtension->IsInitialized);
  463. //
  464. // Make sure we support enumeration
  465. //
  466. if(initData->ClassEnumerateDevice == NULL) {
  467. //
  468. // Just send the request down to the lower driver. Perhaps
  469. // It can enumerate children.
  470. //
  471. } else {
  472. //
  473. // Re-enumerate the device
  474. //
  475. status = ClassPnpQueryFdoRelations(DeviceObject, Irp);
  476. if(!NT_SUCCESS(status)) {
  477. completeRequest = TRUE;
  478. break;
  479. }
  480. }
  481. }
  482. IoCopyCurrentIrpStackLocationToNext(Irp);
  483. ClassReleaseRemoveLock(DeviceObject, Irp);
  484. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  485. completeRequest = FALSE;
  486. break;
  487. }
  488. case IRP_MN_QUERY_ID: {
  489. BUS_QUERY_ID_TYPE idType = irpStack->Parameters.QueryId.IdType;
  490. UNICODE_STRING unicodeString;
  491. if(isFdo) {
  492. //
  493. // FDO's should just forward the query down to the lower
  494. // device objects
  495. //
  496. IoCopyCurrentIrpStackLocationToNext(Irp);
  497. ClassReleaseRemoveLock(DeviceObject, Irp);
  498. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  499. completeRequest = FALSE;
  500. break;
  501. }
  502. //
  503. // PDO's need to give an answer - this is easy for now
  504. //
  505. RtlInitUnicodeString(&unicodeString, NULL);
  506. status = ClassGetPdoId(DeviceObject,
  507. idType,
  508. &unicodeString);
  509. if(status == STATUS_NOT_IMPLEMENTED) {
  510. //
  511. // The driver doesn't implement this ID (whatever it is).
  512. // Use the status out of the IRP so that we don't mangle a
  513. // response from someone else.
  514. //
  515. status = Irp->IoStatus.Status;
  516. } else if(NT_SUCCESS(status)) {
  517. Irp->IoStatus.Information = (ULONG_PTR) unicodeString.Buffer;
  518. } else {
  519. Irp->IoStatus.Information = (ULONG_PTR) NULL;
  520. }
  521. break;
  522. }
  523. case IRP_MN_QUERY_STOP_DEVICE:
  524. case IRP_MN_QUERY_REMOVE_DEVICE: {
  525. DebugPrint((2, "ClassDispatchPnp (%p,%p): Processing QUERY_%s irp\n",
  526. DeviceObject, Irp,
  527. ((irpStack->MinorFunction == IRP_MN_QUERY_STOP_DEVICE) ?
  528. "STOP" : "REMOVE")));
  529. //
  530. // If this device is in use for some reason (paging, etc...)
  531. // then we need to fail the request.
  532. //
  533. if(commonExtension->PagingPathCount != 0) {
  534. DebugPrint((1, "ClassDispatchPnp (%p,%p): device is in paging "
  535. "path and cannot be removed\n",
  536. DeviceObject, Irp));
  537. status = STATUS_DEVICE_BUSY;
  538. break;
  539. }
  540. //
  541. // Check with the class driver to see if the query operation
  542. // can succeed.
  543. //
  544. if(irpStack->MinorFunction == IRP_MN_QUERY_STOP_DEVICE) {
  545. status = devInfo->ClassStopDevice(DeviceObject,
  546. irpStack->MinorFunction);
  547. } else {
  548. status = devInfo->ClassRemoveDevice(DeviceObject,
  549. irpStack->MinorFunction);
  550. }
  551. if(NT_SUCCESS(status)) {
  552. //
  553. // ASSERT that we never get two queries in a row, as
  554. // this will severly mess up the state machine
  555. //
  556. ASSERT(commonExtension->CurrentState != irpStack->MinorFunction);
  557. commonExtension->PreviousState = commonExtension->CurrentState;
  558. commonExtension->CurrentState = irpStack->MinorFunction;
  559. if(isFdo) {
  560. DebugPrint((2, "ClassDispatchPnp (%p,%p): Forwarding QUERY_"
  561. "%s irp\n", DeviceObject, Irp,
  562. ((irpStack->MinorFunction == IRP_MN_QUERY_STOP_DEVICE) ?
  563. "STOP" : "REMOVE")));
  564. status = ClassForwardIrpSynchronous(commonExtension, Irp);
  565. }
  566. }
  567. DebugPrint((2, "ClassDispatchPnp (%p,%p): Final status == %x\n",
  568. DeviceObject, Irp, status));
  569. break;
  570. }
  571. case IRP_MN_CANCEL_STOP_DEVICE:
  572. case IRP_MN_CANCEL_REMOVE_DEVICE: {
  573. //
  574. // Check with the class driver to see if the query or cancel
  575. // operation can succeed.
  576. //
  577. if(irpStack->MinorFunction == IRP_MN_CANCEL_STOP_DEVICE) {
  578. status = devInfo->ClassStopDevice(DeviceObject,
  579. irpStack->MinorFunction);
  580. ASSERTMSG("ClassDispatchPnp !! CANCEL_STOP_DEVICE should "
  581. "never be failed\n", NT_SUCCESS(status));
  582. } else {
  583. status = devInfo->ClassRemoveDevice(DeviceObject,
  584. irpStack->MinorFunction);
  585. ASSERTMSG("ClassDispatchPnp !! CANCEL_REMOVE_DEVICE should "
  586. "never be failed\n", NT_SUCCESS(status));
  587. }
  588. Irp->IoStatus.Status = status;
  589. //
  590. // We got a CANCEL - roll back to the previous state only
  591. // if the current state is the respective QUERY state.
  592. //
  593. if(((irpStack->MinorFunction == IRP_MN_CANCEL_STOP_DEVICE) &&
  594. (commonExtension->CurrentState == IRP_MN_QUERY_STOP_DEVICE)
  595. ) ||
  596. ((irpStack->MinorFunction == IRP_MN_CANCEL_REMOVE_DEVICE) &&
  597. (commonExtension->CurrentState == IRP_MN_QUERY_REMOVE_DEVICE)
  598. )
  599. ) {
  600. commonExtension->CurrentState =
  601. commonExtension->PreviousState;
  602. commonExtension->PreviousState = 0xff;
  603. }
  604. if(isFdo) {
  605. IoCopyCurrentIrpStackLocationToNext(Irp);
  606. ClassReleaseRemoveLock(DeviceObject, Irp);
  607. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  608. completeRequest = FALSE;
  609. } else {
  610. status = STATUS_SUCCESS;
  611. }
  612. break;
  613. }
  614. case IRP_MN_STOP_DEVICE: {
  615. //
  616. // These all mean nothing to the class driver currently. The
  617. // port driver will handle all queueing when necessary.
  618. //
  619. DebugPrint((2, "ClassDispatchPnp (%p,%p): got stop request for %s\n",
  620. DeviceObject, Irp,
  621. (isFdo ? "fdo" : "pdo")
  622. ));
  623. ASSERT(commonExtension->PagingPathCount == 0);
  624. //
  625. // ISSUE-2000/02/03-peterwie
  626. // if we stop the timer here then it means no class driver can
  627. // do i/o in its ClassStopDevice routine. This is because the
  628. // retry (among other things) is tied into the tick handler
  629. // and disabling retries could cause the class driver to deadlock.
  630. // Currently no class driver we're aware of issues i/o in its
  631. // Stop routine but this is a case we may want to defend ourself
  632. // against.
  633. //
  634. if (DeviceObject->Timer) {
  635. IoStopTimer(DeviceObject);
  636. }
  637. status = devInfo->ClassStopDevice(DeviceObject, IRP_MN_STOP_DEVICE);
  638. ASSERTMSG("ClassDispatchPnp !! STOP_DEVICE should "
  639. "never be failed\n", NT_SUCCESS(status));
  640. if(isFdo) {
  641. status = ClassForwardIrpSynchronous(commonExtension, Irp);
  642. }
  643. if(NT_SUCCESS(status)) {
  644. commonExtension->CurrentState = irpStack->MinorFunction;
  645. commonExtension->PreviousState = 0xff;
  646. }
  647. break;
  648. }
  649. case IRP_MN_REMOVE_DEVICE:
  650. case IRP_MN_SURPRISE_REMOVAL: {
  651. PDEVICE_OBJECT lowerDeviceObject = commonExtension->LowerDeviceObject;
  652. UCHAR removeType = irpStack->MinorFunction;
  653. if (commonExtension->PagingPathCount != 0) {
  654. DBGTRACE(ClassDebugWarning, ("ClassDispatchPnp (%p,%p): paging device is getting removed!", DeviceObject, Irp));
  655. }
  656. //
  657. // Release the lock for this IRP before calling in.
  658. //
  659. ClassReleaseRemoveLock(DeviceObject, Irp);
  660. lockReleased = TRUE;
  661. /*
  662. * If a timer was started on the device, stop it.
  663. */
  664. if (DeviceObject->Timer) {
  665. IoStopTimer(DeviceObject);
  666. }
  667. /*
  668. * "Fire-and-forget" the remove irp to the lower stack.
  669. * Don't touch the irp (or the irp stack!) after this.
  670. */
  671. if (isFdo) {
  672. IoCopyCurrentIrpStackLocationToNext(Irp);
  673. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  674. ASSERT(NT_SUCCESS(status));
  675. completeRequest = FALSE;
  676. }
  677. else {
  678. status = STATUS_SUCCESS;
  679. }
  680. /*
  681. * Do our own cleanup and call the class driver's remove
  682. * cleanup routine.
  683. * For IRP_MN_REMOVE_DEVICE, this also deletes our device object,
  684. * so don't touch the extension after this.
  685. */
  686. commonExtension->PreviousState = commonExtension->CurrentState;
  687. commonExtension->CurrentState = removeType;
  688. ClassRemoveDevice(DeviceObject, removeType);
  689. break;
  690. }
  691. case IRP_MN_DEVICE_USAGE_NOTIFICATION: {
  692. switch(irpStack->Parameters.UsageNotification.Type) {
  693. case DeviceUsageTypePaging: {
  694. BOOLEAN setPagable;
  695. if((irpStack->Parameters.UsageNotification.InPath) &&
  696. (commonExtension->CurrentState != IRP_MN_START_DEVICE)) {
  697. //
  698. // Device isn't started. Don't allow adding a
  699. // paging file, but allow a removal of one.
  700. //
  701. status = STATUS_DEVICE_NOT_READY;
  702. break;
  703. }
  704. ASSERT(commonExtension->IsInitialized);
  705. //
  706. // need to synchronize this now...
  707. //
  708. KeEnterCriticalRegion();
  709. status = KeWaitForSingleObject(&commonExtension->PathCountEvent,
  710. Executive, KernelMode,
  711. FALSE, NULL);
  712. ASSERT(NT_SUCCESS(status));
  713. status = STATUS_SUCCESS;
  714. //
  715. // If the volume is removable we should try to lock it in
  716. // place or unlock it once per paging path count
  717. //
  718. if (commonExtension->IsFdo){
  719. status = ClasspEjectionControl(
  720. DeviceObject,
  721. Irp,
  722. InternalMediaLock,
  723. (BOOLEAN)irpStack->Parameters.UsageNotification.InPath);
  724. }
  725. if (!NT_SUCCESS(status)){
  726. KeSetEvent(&commonExtension->PathCountEvent, IO_NO_INCREMENT, FALSE);
  727. KeLeaveCriticalRegion();
  728. break;
  729. }
  730. //
  731. // if removing last paging device, need to set DO_POWER_PAGABLE
  732. // bit here, and possible re-set it below on failure.
  733. //
  734. setPagable = FALSE;
  735. if (!irpStack->Parameters.UsageNotification.InPath &&
  736. commonExtension->PagingPathCount == 1
  737. ) {
  738. //
  739. // removing last paging file
  740. // must have DO_POWER_PAGABLE bits set, but only
  741. // if noone set the DO_POWER_INRUSH bit
  742. //
  743. if (TEST_FLAG(DeviceObject->Flags, DO_POWER_INRUSH)) {
  744. DebugPrint((2, "ClassDispatchPnp (%p,%p): Last "
  745. "paging file removed, but "
  746. "DO_POWER_INRUSH was set, so NOT "
  747. "setting DO_POWER_PAGABLE\n",
  748. DeviceObject, Irp));
  749. } else {
  750. DebugPrint((2, "ClassDispatchPnp (%p,%p): Last "
  751. "paging file removed, "
  752. "setting DO_POWER_PAGABLE\n",
  753. DeviceObject, Irp));
  754. SET_FLAG(DeviceObject->Flags, DO_POWER_PAGABLE);
  755. setPagable = TRUE;
  756. }
  757. }
  758. //
  759. // forward the irp before finishing handling the
  760. // special cases
  761. //
  762. status = ClassForwardIrpSynchronous(commonExtension, Irp);
  763. //
  764. // now deal with the failure and success cases.
  765. // note that we are not allowed to fail the irp
  766. // once it is sent to the lower drivers.
  767. //
  768. if (NT_SUCCESS(status)) {
  769. IoAdjustPagingPathCount(
  770. &commonExtension->PagingPathCount,
  771. irpStack->Parameters.UsageNotification.InPath);
  772. if (irpStack->Parameters.UsageNotification.InPath) {
  773. if (commonExtension->PagingPathCount == 1) {
  774. DebugPrint((2, "ClassDispatchPnp (%p,%p): "
  775. "Clearing PAGABLE bit\n",
  776. DeviceObject, Irp));
  777. CLEAR_FLAG(DeviceObject->Flags, DO_POWER_PAGABLE);
  778. }
  779. }
  780. } else {
  781. //
  782. // cleanup the changes done above
  783. //
  784. if (setPagable == TRUE) {
  785. DebugPrint((2, "ClassDispatchPnp (%p,%p): Unsetting "
  786. "PAGABLE bit due to irp failure\n",
  787. DeviceObject, Irp));
  788. CLEAR_FLAG(DeviceObject->Flags, DO_POWER_PAGABLE);
  789. setPagable = FALSE;
  790. }
  791. //
  792. // relock or unlock the media if needed.
  793. //
  794. if (commonExtension->IsFdo) {
  795. ClasspEjectionControl(
  796. DeviceObject,
  797. Irp,
  798. InternalMediaLock,
  799. (BOOLEAN)!irpStack->Parameters.UsageNotification.InPath);
  800. }
  801. }
  802. //
  803. // set the event so the next one can occur.
  804. //
  805. KeSetEvent(&commonExtension->PathCountEvent,
  806. IO_NO_INCREMENT, FALSE);
  807. KeLeaveCriticalRegion();
  808. break;
  809. }
  810. case DeviceUsageTypeHibernation: {
  811. IoAdjustPagingPathCount(
  812. &commonExtension->HibernationPathCount,
  813. irpStack->Parameters.UsageNotification.InPath
  814. );
  815. status = ClassForwardIrpSynchronous(commonExtension, Irp);
  816. if (!NT_SUCCESS(status)) {
  817. IoAdjustPagingPathCount(
  818. &commonExtension->HibernationPathCount,
  819. !irpStack->Parameters.UsageNotification.InPath
  820. );
  821. }
  822. break;
  823. }
  824. case DeviceUsageTypeDumpFile: {
  825. IoAdjustPagingPathCount(
  826. &commonExtension->DumpPathCount,
  827. irpStack->Parameters.UsageNotification.InPath
  828. );
  829. status = ClassForwardIrpSynchronous(commonExtension, Irp);
  830. if (!NT_SUCCESS(status)) {
  831. IoAdjustPagingPathCount(
  832. &commonExtension->DumpPathCount,
  833. !irpStack->Parameters.UsageNotification.InPath
  834. );
  835. }
  836. break;
  837. }
  838. default: {
  839. status = STATUS_INVALID_PARAMETER;
  840. break;
  841. }
  842. }
  843. break;
  844. }
  845. case IRP_MN_QUERY_CAPABILITIES: {
  846. DebugPrint((2, "ClassDispatchPnp (%p,%p): QueryCapabilities\n",
  847. DeviceObject, Irp));
  848. if(!isFdo) {
  849. status = ClassQueryPnpCapabilities(
  850. DeviceObject,
  851. irpStack->Parameters.DeviceCapabilities.Capabilities
  852. );
  853. break;
  854. } else {
  855. PDEVICE_CAPABILITIES deviceCapabilities;
  856. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
  857. PCLASS_PRIVATE_FDO_DATA fdoData;
  858. fdoExtension = DeviceObject->DeviceExtension;
  859. fdoData = fdoExtension->PrivateFdoData;
  860. deviceCapabilities =
  861. irpStack->Parameters.DeviceCapabilities.Capabilities;
  862. //
  863. // forward the irp before handling the special cases
  864. //
  865. status = ClassForwardIrpSynchronous(commonExtension, Irp);
  866. if (!NT_SUCCESS(status)) {
  867. break;
  868. }
  869. //
  870. // we generally want to remove the device from the hotplug
  871. // applet, which requires the SR-OK bit to be set.
  872. // only when the user specifies that they are capable of
  873. // safely removing things do we want to clear this bit
  874. // (saved in WriteCacheEnableOverride)
  875. //
  876. // setting of this bit is done either above, or by the
  877. // lower driver.
  878. //
  879. // note: may not be started, so check we have FDO data first.
  880. //
  881. if (fdoData &&
  882. fdoData->HotplugInfo.WriteCacheEnableOverride) {
  883. if (deviceCapabilities->SurpriseRemovalOK) {
  884. DebugPrint((1, "Classpnp: Clearing SR-OK bit in "
  885. "device capabilities due to hotplug "
  886. "device or media\n"));
  887. }
  888. deviceCapabilities->SurpriseRemovalOK = FALSE;
  889. }
  890. break;
  891. } // end QUERY_CAPABILITIES for FDOs
  892. ASSERT(FALSE);
  893. break;
  894. } // end QUERY_CAPABILITIES
  895. default: {
  896. if (isFdo){
  897. IoCopyCurrentIrpStackLocationToNext(Irp);
  898. ClassReleaseRemoveLock(DeviceObject, Irp);
  899. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  900. completeRequest = FALSE;
  901. }
  902. break;
  903. }
  904. }
  905. }
  906. else {
  907. ASSERT(driverExtension);
  908. status = STATUS_INTERNAL_ERROR;
  909. }
  910. if (completeRequest){
  911. Irp->IoStatus.Status = status;
  912. if (!lockReleased){
  913. ClassReleaseRemoveLock(DeviceObject, Irp);
  914. }
  915. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  916. DBGTRACE(ClassDebugTrace, ("ClassDispatchPnp (%p,%p): leaving with previous %#x, current %#x.", DeviceObject, Irp, commonExtension->PreviousState, commonExtension->CurrentState));
  917. }
  918. else {
  919. /*
  920. * The irp is already completed so don't touch it.
  921. * This may be a remove so don't touch the device extension.
  922. */
  923. DBGTRACE(ClassDebugTrace, ("ClassDispatchPnp (%p,%p): leaving.", DeviceObject, Irp));
  924. }
  925. return status;
  926. } // end ClassDispatchPnp()
  927. /*++////////////////////////////////////////////////////////////////////////////
  928. ClassPnpStartDevice()
  929. Routine Description:
  930. Storage class driver routine for IRP_MN_START_DEVICE requests.
  931. This routine kicks off any device specific initialization
  932. Arguments:
  933. DeviceObject - a pointer to the device object
  934. Irp - a pointer to the io request packet
  935. Return Value:
  936. none
  937. --*/
  938. NTSTATUS ClassPnpStartDevice(IN PDEVICE_OBJECT DeviceObject)
  939. {
  940. PCLASS_DRIVER_EXTENSION driverExtension;
  941. PCLASS_INIT_DATA initData;
  942. PCLASS_DEV_INFO devInfo;
  943. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  944. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
  945. BOOLEAN isFdo = commonExtension->IsFdo;
  946. BOOLEAN isMountedDevice = TRUE;
  947. UNICODE_STRING interfaceName;
  948. BOOLEAN timerStarted;
  949. NTSTATUS status = STATUS_SUCCESS;
  950. PAGED_CODE();
  951. driverExtension = IoGetDriverObjectExtension(DeviceObject->DriverObject,
  952. CLASS_DRIVER_EXTENSION_KEY);
  953. initData = &(driverExtension->InitData);
  954. if(isFdo) {
  955. devInfo = &(initData->FdoData);
  956. } else {
  957. devInfo = &(initData->PdoData);
  958. }
  959. ASSERT(devInfo->ClassInitDevice != NULL);
  960. ASSERT(devInfo->ClassStartDevice != NULL);
  961. if (!commonExtension->IsInitialized){
  962. //
  963. // perform FDO/PDO specific initialization
  964. //
  965. if (isFdo){
  966. STORAGE_PROPERTY_ID propertyId;
  967. //
  968. // allocate a private extension for class data
  969. //
  970. if (fdoExtension->PrivateFdoData == NULL) {
  971. fdoExtension->PrivateFdoData =
  972. ExAllocatePoolWithTag(NonPagedPool,
  973. sizeof(CLASS_PRIVATE_FDO_DATA),
  974. CLASS_TAG_PRIVATE_DATA
  975. );
  976. }
  977. if (fdoExtension->PrivateFdoData == NULL) {
  978. DebugPrint((0, "ClassPnpStartDevice: Cannot allocate for "
  979. "private fdo data\n"));
  980. return STATUS_INSUFFICIENT_RESOURCES;
  981. }
  982. //
  983. // initialize the struct's various fields.
  984. //
  985. RtlZeroMemory(fdoExtension->PrivateFdoData,
  986. sizeof(CLASS_PRIVATE_FDO_DATA)
  987. );
  988. KeInitializeTimer(&fdoExtension->PrivateFdoData->Retry.Timer);
  989. KeInitializeDpc(&fdoExtension->PrivateFdoData->Retry.Dpc,
  990. ClasspRetryRequestDpc,
  991. DeviceObject);
  992. KeInitializeSpinLock(&fdoExtension->PrivateFdoData->Retry.Lock);
  993. fdoExtension->PrivateFdoData->Retry.Granularity =
  994. KeQueryTimeIncrement();
  995. commonExtension->Reserved4 = (ULONG_PTR)(' GPH'); // debug aid
  996. //
  997. // NOTE: the old interface allowed the class driver to allocate
  998. // this. this was unsafe for low-memory conditions. allocate one
  999. // unconditionally now, and modify our internal functions to use
  1000. // our own exclusively as it is the only safe way to do this.
  1001. //
  1002. status = ClasspAllocateReleaseQueueIrp(fdoExtension);
  1003. if (!NT_SUCCESS(status)) {
  1004. DebugPrint((0, "ClassPnpStartDevice: Cannot allocate the "
  1005. "private release queue irp\n"));
  1006. return status;
  1007. }
  1008. //
  1009. // Call port driver to get adapter capabilities.
  1010. //
  1011. propertyId = StorageAdapterProperty;
  1012. status = ClassGetDescriptor(
  1013. commonExtension->LowerDeviceObject,
  1014. &propertyId,
  1015. &fdoExtension->AdapterDescriptor);
  1016. if(!NT_SUCCESS(status)) {
  1017. //
  1018. // This DebugPrint is to help third-party driver writers
  1019. //
  1020. DebugPrint((0, "ClassPnpStartDevice: ClassGetDescriptor "
  1021. "[ADAPTER] failed %lx\n", status));
  1022. return status;
  1023. }
  1024. //
  1025. // Call port driver to get device descriptor.
  1026. //
  1027. propertyId = StorageDeviceProperty;
  1028. status = ClassGetDescriptor(
  1029. commonExtension->LowerDeviceObject,
  1030. &propertyId,
  1031. &fdoExtension->DeviceDescriptor);
  1032. if(!NT_SUCCESS(status)) {
  1033. //
  1034. // This DebugPrint is to help third-party driver writers
  1035. //
  1036. DebugPrint((0, "ClassPnpStartDevice: ClassGetDescriptor "
  1037. "[DEVICE] failed %lx\n", status));
  1038. return status;
  1039. }
  1040. ClasspScanForSpecialInRegistry(fdoExtension);
  1041. ClassScanForSpecial(fdoExtension,
  1042. ClassBadItems,
  1043. ClasspScanForClassHacks);
  1044. //
  1045. // allow perf to be re-enabled after a given number of failed IOs
  1046. // require this number to be at least CLASS_PERF_RESTORE_MINIMUM
  1047. //
  1048. {
  1049. ULONG t = 0;
  1050. ClassGetDeviceParameter(fdoExtension,
  1051. CLASSP_REG_SUBKEY_NAME,
  1052. CLASSP_REG_PERF_RESTORE_VALUE_NAME,
  1053. &t);
  1054. if (t >= CLASS_PERF_RESTORE_MINIMUM) {
  1055. fdoExtension->PrivateFdoData->Perf.ReEnableThreshhold = t;
  1056. }
  1057. }
  1058. //
  1059. // compatibility comes first. writable cd media will not
  1060. // get a SYNCH_CACHE on power down.
  1061. //
  1062. if (fdoExtension->DeviceObject->DeviceType != FILE_DEVICE_DISK) {
  1063. SET_FLAG(fdoExtension->PrivateFdoData->HackFlags,
  1064. FDO_HACK_NO_SYNC_CACHE);
  1065. }
  1066. //
  1067. // initialize the hotplug information only after the ScanForSpecial
  1068. // routines, as it relies upon the hack flags.
  1069. //
  1070. status = ClasspInitializeHotplugInfo(fdoExtension);
  1071. if (!NT_SUCCESS(status)) {
  1072. DebugPrint((1, "ClassPnpStartDevice: Could not initialize "
  1073. "hotplug information %lx\n", status));
  1074. return status;
  1075. }
  1076. /*
  1077. * Allocate/initialize TRANSFER_PACKETs and related resources.
  1078. */
  1079. status = InitializeTransferPackets(DeviceObject);
  1080. }
  1081. //
  1082. // ISSUE - drivers need to disable write caching on the media
  1083. // if hotplug and !useroverride. perhaps we should
  1084. // allow registration of a callback to enable/disable
  1085. // write cache instead.
  1086. //
  1087. if (NT_SUCCESS(status)){
  1088. status = devInfo->ClassInitDevice(DeviceObject);
  1089. }
  1090. }
  1091. if (!NT_SUCCESS(status)){
  1092. //
  1093. // Just bail out - the remove that comes down will clean up the
  1094. // initialized scraps.
  1095. //
  1096. return status;
  1097. } else {
  1098. commonExtension->IsInitialized = TRUE;
  1099. if (commonExtension->IsFdo) {
  1100. fdoExtension->PrivateFdoData->Perf.OriginalSrbFlags = fdoExtension->SrbFlags;
  1101. }
  1102. }
  1103. //
  1104. // If device requests autorun functionality or a once a second callback
  1105. // then enable the once per second timer.
  1106. //
  1107. // NOTE: This assumes that ClassInitializeMediaChangeDetection is always
  1108. // called in the context of the ClassInitDevice callback. If called
  1109. // after then this check will have already been made and the
  1110. // once a second timer will not have been enabled.
  1111. //
  1112. if ((isFdo) &&
  1113. ((initData->ClassTick != NULL) ||
  1114. (fdoExtension->MediaChangeDetectionInfo != NULL) ||
  1115. ((fdoExtension->FailurePredictionInfo != NULL) &&
  1116. (fdoExtension->FailurePredictionInfo->Method != FailurePredictionNone))))
  1117. {
  1118. ClasspEnableTimer(DeviceObject);
  1119. timerStarted = TRUE;
  1120. } else {
  1121. timerStarted = FALSE;
  1122. }
  1123. //
  1124. // NOTE: the timer looks at commonExtension->CurrentState now
  1125. // to prevent Media Change Notification code from running
  1126. // until the device is started, but allows the device
  1127. // specific tick handler to run. therefore it is imperative
  1128. // that commonExtension->CurrentState not be updated until
  1129. // the device specific startdevice handler has finished.
  1130. //
  1131. status = devInfo->ClassStartDevice(DeviceObject);
  1132. if(NT_SUCCESS(status)) {
  1133. commonExtension->CurrentState = IRP_MN_START_DEVICE;
  1134. if((isFdo) && (initData->ClassEnumerateDevice != NULL)) {
  1135. isMountedDevice = FALSE;
  1136. }
  1137. if((DeviceObject->DeviceType != FILE_DEVICE_DISK) &&
  1138. (DeviceObject->DeviceType != FILE_DEVICE_CD_ROM)) {
  1139. isMountedDevice = FALSE;
  1140. }
  1141. if(isMountedDevice) {
  1142. ClasspRegisterMountedDeviceInterface(DeviceObject);
  1143. }
  1144. if((commonExtension->IsFdo) &&
  1145. (devInfo->ClassWmiInfo.GuidRegInfo != NULL)) {
  1146. IoWMIRegistrationControl(DeviceObject, WMIREG_ACTION_REGISTER);
  1147. }
  1148. } else {
  1149. if (timerStarted) {
  1150. ClasspDisableTimer(DeviceObject);
  1151. }
  1152. }
  1153. return status;
  1154. }
  1155. /*++////////////////////////////////////////////////////////////////////////////
  1156. ClassReadWrite()
  1157. Routine Description:
  1158. This is the system entry point for read and write requests. The
  1159. device-specific handler is invoked to perform any validation necessary.
  1160. If the device object is a PDO (partition object) then the request will
  1161. simply be adjusted for Partition0 and issued to the lower device driver.
  1162. IF the device object is an FDO (paritition 0 object), the number of bytes
  1163. in the request are checked against the maximum byte counts that the adapter
  1164. supports and requests are broken up into
  1165. smaller sizes if necessary.
  1166. Arguments:
  1167. DeviceObject - a pointer to the device object for this request
  1168. Irp - IO request
  1169. Return Value:
  1170. NT Status
  1171. --*/
  1172. NTSTATUS ClassReadWrite(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
  1173. {
  1174. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  1175. PDEVICE_OBJECT lowerDeviceObject = commonExtension->LowerDeviceObject;
  1176. PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(Irp);
  1177. LARGE_INTEGER startingOffset = currentIrpStack->Parameters.Read.ByteOffset;
  1178. ULONG transferByteCount = currentIrpStack->Parameters.Read.Length;
  1179. ULONG isRemoved;
  1180. NTSTATUS status;
  1181. /*
  1182. * Grab the remove lock. If we can't acquire it, bail out.
  1183. */
  1184. isRemoved = ClassAcquireRemoveLock(DeviceObject, Irp);
  1185. if (isRemoved) {
  1186. Irp->IoStatus.Status = STATUS_DEVICE_DOES_NOT_EXIST;
  1187. ClassReleaseRemoveLock(DeviceObject, Irp);
  1188. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  1189. status = STATUS_DEVICE_DOES_NOT_EXIST;
  1190. }
  1191. else if (TEST_FLAG(DeviceObject->Flags, DO_VERIFY_VOLUME) &&
  1192. (currentIrpStack->MinorFunction != CLASSP_VOLUME_VERIFY_CHECKED) &&
  1193. !TEST_FLAG(currentIrpStack->Flags, SL_OVERRIDE_VERIFY_VOLUME)){
  1194. /*
  1195. * DO_VERIFY_VOLUME is set for the device object,
  1196. * but this request is not itself a verify request.
  1197. * So fail this request.
  1198. */
  1199. IoSetHardErrorOrVerifyDevice(Irp, DeviceObject);
  1200. Irp->IoStatus.Status = STATUS_VERIFY_REQUIRED;
  1201. Irp->IoStatus.Information = 0;
  1202. ClassReleaseRemoveLock(DeviceObject, Irp);
  1203. ClassCompleteRequest(DeviceObject, Irp, 0);
  1204. status = STATUS_VERIFY_REQUIRED;
  1205. }
  1206. else {
  1207. /*
  1208. * Since we've bypassed the verify-required tests we don't need to repeat
  1209. * them with this IRP - in particular we don't want to worry about
  1210. * hitting them at the partition 0 level if the request has come through
  1211. * a non-zero partition.
  1212. */
  1213. currentIrpStack->MinorFunction = CLASSP_VOLUME_VERIFY_CHECKED;
  1214. /*
  1215. * Call the miniport driver's pre-pass filter to check if we
  1216. * should continue with this transfer.
  1217. */
  1218. ASSERT(commonExtension->DevInfo->ClassReadWriteVerification);
  1219. status = commonExtension->DevInfo->ClassReadWriteVerification(DeviceObject, Irp);
  1220. if (!NT_SUCCESS(status)){
  1221. ASSERT(Irp->IoStatus.Status == status);
  1222. ClassReleaseRemoveLock(DeviceObject, Irp);
  1223. ClassCompleteRequest (DeviceObject, Irp, IO_NO_INCREMENT);
  1224. }
  1225. else if (status == STATUS_PENDING){
  1226. /*
  1227. * ClassReadWriteVerification queued this request.
  1228. * So don't touch the irp anymore.
  1229. */
  1230. }
  1231. else {
  1232. if (transferByteCount == 0) {
  1233. /*
  1234. * Several parts of the code turn 0 into 0xffffffff,
  1235. * so don't process a zero-length request any further.
  1236. */
  1237. Irp->IoStatus.Status = STATUS_SUCCESS;
  1238. Irp->IoStatus.Information = 0;
  1239. ClassReleaseRemoveLock(DeviceObject, Irp);
  1240. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  1241. status = STATUS_SUCCESS;
  1242. }
  1243. else {
  1244. /*
  1245. * If the driver has its own StartIo routine, call it.
  1246. */
  1247. if (commonExtension->DriverExtension->InitData.ClassStartIo) {
  1248. IoMarkIrpPending(Irp);
  1249. IoStartPacket(DeviceObject, Irp, NULL, NULL);
  1250. status = STATUS_PENDING;
  1251. }
  1252. else {
  1253. /*
  1254. * The driver does not have its own StartIo routine.
  1255. * So process this request ourselves.
  1256. */
  1257. /*
  1258. * Add partition byte offset to make starting byte relative to
  1259. * beginning of disk.
  1260. */
  1261. currentIrpStack->Parameters.Read.ByteOffset.QuadPart +=
  1262. commonExtension->StartingOffset.QuadPart;
  1263. if (commonExtension->IsFdo){
  1264. /*
  1265. * Add in any skew for the disk manager software.
  1266. */
  1267. currentIrpStack->Parameters.Read.ByteOffset.QuadPart +=
  1268. commonExtension->PartitionZeroExtension->DMByteSkew;
  1269. /*
  1270. * Perform the actual transfer(s) on the hardware
  1271. * to service this request.
  1272. */
  1273. ServiceTransferRequest(DeviceObject, Irp);
  1274. status = STATUS_PENDING;
  1275. }
  1276. else {
  1277. /*
  1278. * This is a child PDO enumerated for our FDO by e.g. disk.sys
  1279. * and owned by e.g. partmgr. Send it down to the next device
  1280. * and the same irp will come back to us for the FDO.
  1281. */
  1282. IoCopyCurrentIrpStackLocationToNext(Irp);
  1283. ClassReleaseRemoveLock(DeviceObject, Irp);
  1284. status = IoCallDriver(lowerDeviceObject, Irp);
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }
  1290. return status;
  1291. }
  1292. /*++////////////////////////////////////////////////////////////////////////////
  1293. ClassReadDriveCapacity()
  1294. Routine Description:
  1295. This routine sends a READ CAPACITY to the requested device, updates
  1296. the geometry information in the device object and returns
  1297. when it is complete. This routine is synchronous.
  1298. This routine must be called with the remove lock held or some other
  1299. assurance that the Fdo will not be removed while processing.
  1300. Arguments:
  1301. DeviceObject - Supplies a pointer to the device object that represents
  1302. the device whose capacity is to be read.
  1303. Return Value:
  1304. Status is returned.
  1305. --*/
  1306. NTSTATUS ClassReadDriveCapacity(IN PDEVICE_OBJECT Fdo)
  1307. {
  1308. READ_CAPACITY_DATA readCapacityBuffer = {0};
  1309. NTSTATUS status;
  1310. PMDL driveCapMdl;
  1311. driveCapMdl = BuildDeviceInputMdl(&readCapacityBuffer, sizeof(READ_CAPACITY_DATA));
  1312. if (driveCapMdl){
  1313. TRANSFER_PACKET *pkt = DequeueFreeTransferPacket(Fdo, TRUE);
  1314. if (pkt){
  1315. PFUNCTIONAL_DEVICE_EXTENSION fdoExt = Fdo->DeviceExtension;
  1316. KEVENT event;
  1317. NTSTATUS pktStatus;
  1318. IRP pseudoIrp = {0};
  1319. /*
  1320. * Our engine needs an "original irp" to write the status back to
  1321. * and to count down packets (one in this case).
  1322. * Just use a pretend irp for this.
  1323. */
  1324. pseudoIrp.Tail.Overlay.DriverContext[0] = LongToPtr(1);
  1325. pseudoIrp.IoStatus.Status = STATUS_SUCCESS;
  1326. pseudoIrp.IoStatus.Information = 0;
  1327. pseudoIrp.MdlAddress = driveCapMdl;
  1328. /*
  1329. * Set this up as a SYNCHRONOUS transfer, submit it,
  1330. * and wait for the packet to complete. The result
  1331. * status will be written to the original irp.
  1332. */
  1333. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  1334. SetupDriveCapacityTransferPacket( pkt,
  1335. &readCapacityBuffer,
  1336. sizeof(READ_CAPACITY_DATA),
  1337. &event,
  1338. &pseudoIrp);
  1339. SubmitTransferPacket(pkt);
  1340. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  1341. status = pseudoIrp.IoStatus.Status;
  1342. /*
  1343. * If we got an UNDERRUN, retry exactly once.
  1344. * (The transfer_packet engine didn't retry because the result
  1345. * status was success).
  1346. */
  1347. if (NT_SUCCESS(status) &&
  1348. (pseudoIrp.IoStatus.Information < sizeof(READ_CAPACITY_DATA))){
  1349. DBGERR(("ClassReadDriveCapacity: read len (%xh) < %xh, retrying ...", (ULONG)pseudoIrp.IoStatus.Information, sizeof(READ_CAPACITY_DATA)));
  1350. pkt = DequeueFreeTransferPacket(Fdo, TRUE);
  1351. if (pkt){
  1352. pseudoIrp.Tail.Overlay.DriverContext[0] = LongToPtr(1);
  1353. pseudoIrp.IoStatus.Status = STATUS_SUCCESS;
  1354. pseudoIrp.IoStatus.Information = 0;
  1355. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  1356. SetupDriveCapacityTransferPacket( pkt,
  1357. &readCapacityBuffer,
  1358. sizeof(READ_CAPACITY_DATA),
  1359. &event,
  1360. &pseudoIrp);
  1361. SubmitTransferPacket(pkt);
  1362. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  1363. status = pseudoIrp.IoStatus.Status;
  1364. if (pseudoIrp.IoStatus.Information < sizeof(READ_CAPACITY_DATA)){
  1365. status = STATUS_DEVICE_BUSY;
  1366. }
  1367. }
  1368. else {
  1369. status = STATUS_INSUFFICIENT_RESOURCES;
  1370. }
  1371. }
  1372. if (NT_SUCCESS(status)){
  1373. /*
  1374. * The request succeeded.
  1375. * Read out and store the drive information.
  1376. */
  1377. ULONG cylinderSize;
  1378. ULONG bytesPerSector;
  1379. ULONG tmp;
  1380. ULONG lastSector;
  1381. /*
  1382. * Read the bytesPerSector value,
  1383. * which is big-endian in the returned buffer.
  1384. * Default to the standard 512 bytes.
  1385. */
  1386. tmp = readCapacityBuffer.BytesPerBlock;
  1387. ((PFOUR_BYTE)&bytesPerSector)->Byte0 = ((PFOUR_BYTE)&tmp)->Byte3;
  1388. ((PFOUR_BYTE)&bytesPerSector)->Byte1 = ((PFOUR_BYTE)&tmp)->Byte2;
  1389. ((PFOUR_BYTE)&bytesPerSector)->Byte2 = ((PFOUR_BYTE)&tmp)->Byte1;
  1390. ((PFOUR_BYTE)&bytesPerSector)->Byte3 = ((PFOUR_BYTE)&tmp)->Byte0;
  1391. if (bytesPerSector == 0) {
  1392. bytesPerSector = 512;
  1393. }
  1394. else {
  1395. /*
  1396. * Clear all but the highest set bit.
  1397. * That will give us a bytesPerSector value that is a power of 2.
  1398. */
  1399. while (bytesPerSector & (bytesPerSector-1)) {
  1400. bytesPerSector &= bytesPerSector-1;
  1401. }
  1402. }
  1403. fdoExt->DiskGeometry.BytesPerSector = bytesPerSector;
  1404. //
  1405. // Copy last sector in reverse byte order.
  1406. //
  1407. tmp = readCapacityBuffer.LogicalBlockAddress;
  1408. ((PFOUR_BYTE)&lastSector)->Byte0 = ((PFOUR_BYTE)&tmp)->Byte3;
  1409. ((PFOUR_BYTE)&lastSector)->Byte1 = ((PFOUR_BYTE)&tmp)->Byte2;
  1410. ((PFOUR_BYTE)&lastSector)->Byte2 = ((PFOUR_BYTE)&tmp)->Byte1;
  1411. ((PFOUR_BYTE)&lastSector)->Byte3 = ((PFOUR_BYTE)&tmp)->Byte0;
  1412. //
  1413. // Calculate sector to byte shift.
  1414. //
  1415. WHICH_BIT(fdoExt->DiskGeometry.BytesPerSector, fdoExt->SectorShift);
  1416. DebugPrint((2,"SCSI ClassReadDriveCapacity: Sector size is %d\n",
  1417. fdoExt->DiskGeometry.BytesPerSector));
  1418. DebugPrint((2,"SCSI ClassReadDriveCapacity: Number of Sectors is %d\n",
  1419. lastSector + 1));
  1420. if (fdoExt->DMActive){
  1421. DebugPrint((1, "SCSI ClassReadDriveCapacity: reducing number of sectors by %d\n",
  1422. fdoExt->DMSkew));
  1423. lastSector -= fdoExt->DMSkew;
  1424. }
  1425. /*
  1426. * Check to see if we have a geometry we should be using already.
  1427. */
  1428. cylinderSize = (fdoExt->DiskGeometry.TracksPerCylinder *
  1429. fdoExt->DiskGeometry.SectorsPerTrack);
  1430. if (cylinderSize == 0){
  1431. DebugPrint((1, "ClassReadDriveCapacity: resetting H & S geometry "
  1432. "values from %#x/%#x to %#x/%#x\n",
  1433. fdoExt->DiskGeometry.TracksPerCylinder,
  1434. fdoExt->DiskGeometry.SectorsPerTrack,
  1435. 0xff,
  1436. 0x3f));
  1437. fdoExt->DiskGeometry.TracksPerCylinder = 0xff;
  1438. fdoExt->DiskGeometry.SectorsPerTrack = 0x3f;
  1439. cylinderSize = (fdoExt->DiskGeometry.TracksPerCylinder *
  1440. fdoExt->DiskGeometry.SectorsPerTrack);
  1441. }
  1442. //
  1443. // Calculate number of cylinders.
  1444. //
  1445. fdoExt->DiskGeometry.Cylinders.QuadPart = (LONGLONG)((lastSector + 1)/cylinderSize);
  1446. //
  1447. // if there are zero cylinders, then the device lied AND it's
  1448. // smaller than 0xff*0x3f (about 16k sectors, usually 8 meg)
  1449. // this can fit into a single LONGLONG, so create another usable
  1450. // geometry, even if it's unusual looking. This allows small,
  1451. // non-standard devices, such as Sony's Memory Stick, to show
  1452. // up as having a partition.
  1453. //
  1454. if (fdoExt->DiskGeometry.Cylinders.QuadPart == (LONGLONG)0) {
  1455. fdoExt->DiskGeometry.SectorsPerTrack = 1;
  1456. fdoExt->DiskGeometry.TracksPerCylinder = 1;
  1457. fdoExt->DiskGeometry.Cylinders.QuadPart = lastSector;
  1458. }
  1459. //
  1460. // Calculate media capacity in bytes.
  1461. //
  1462. fdoExt->CommonExtension.PartitionLength.QuadPart =
  1463. ((LONGLONG)(lastSector + 1)) << fdoExt->SectorShift;
  1464. /*
  1465. * Is this removable or fixed media
  1466. */
  1467. if (TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)){
  1468. fdoExt->DiskGeometry.MediaType = RemovableMedia;
  1469. }
  1470. else {
  1471. fdoExt->DiskGeometry.MediaType = FixedMedia;
  1472. }
  1473. }
  1474. else {
  1475. /*
  1476. * The request failed.
  1477. */
  1478. //
  1479. // ISSUE - 2000/02/04 - henrygab - non-512-byte sector sizes and failed geometry update
  1480. // what happens when the disk's sector size is bigger than
  1481. // 512 bytes and we hit this code path? this is untested.
  1482. //
  1483. // If the read capacity fails, set the geometry to reasonable parameter
  1484. // so things don't fail at unexpected places. Zero the geometry
  1485. // except for the bytes per sector and sector shift.
  1486. //
  1487. /*
  1488. * This request can sometimes fail legitimately
  1489. * (e.g. when a SCSI device is attached but turned off)
  1490. * so this is not necessarily a device/driver bug.
  1491. */
  1492. DBGTRACE(ClassDebugWarning, ("ClassReadDriveCapacity on Fdo %xh failed with status %xh.", Fdo, status));
  1493. /*
  1494. * Write in a default disk geometry which we HOPE is right (??).
  1495. * BUGBUG !!
  1496. */
  1497. RtlZeroMemory(&fdoExt->DiskGeometry, sizeof(DISK_GEOMETRY));
  1498. fdoExt->DiskGeometry.BytesPerSector = 512;
  1499. fdoExt->SectorShift = 9;
  1500. fdoExt->CommonExtension.PartitionLength.QuadPart = (LONGLONG) 0;
  1501. /*
  1502. * Is this removable or fixed media
  1503. */
  1504. if (TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)){
  1505. fdoExt->DiskGeometry.MediaType = RemovableMedia;
  1506. }
  1507. else {
  1508. fdoExt->DiskGeometry.MediaType = FixedMedia;
  1509. }
  1510. }
  1511. }
  1512. else {
  1513. status = STATUS_INSUFFICIENT_RESOURCES;
  1514. }
  1515. FreeDeviceInputMdl(driveCapMdl);
  1516. }
  1517. else {
  1518. status = STATUS_INSUFFICIENT_RESOURCES;
  1519. }
  1520. return status;
  1521. }
  1522. /*++////////////////////////////////////////////////////////////////////////////
  1523. ClassSendStartUnit()
  1524. Routine Description:
  1525. Send command to SCSI unit to start or power up.
  1526. Because this command is issued asynchronounsly, that is, without
  1527. waiting on it to complete, the IMMEDIATE flag is not set. This
  1528. means that the CDB will not return until the drive has powered up.
  1529. This should keep subsequent requests from being submitted to the
  1530. device before it has completely spun up.
  1531. This routine is called from the InterpretSense routine, when a
  1532. request sense returns data indicating that a drive must be
  1533. powered up.
  1534. This routine may also be called from a class driver's error handler,
  1535. or anytime a non-critical start device should be sent to the device.
  1536. Arguments:
  1537. Fdo - The functional device object for the stopped device.
  1538. Return Value:
  1539. None.
  1540. --*/
  1541. VOID
  1542. ClassSendStartUnit(
  1543. IN PDEVICE_OBJECT Fdo
  1544. )
  1545. {
  1546. PIO_STACK_LOCATION irpStack;
  1547. PIRP irp;
  1548. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  1549. PSCSI_REQUEST_BLOCK srb;
  1550. PCOMPLETION_CONTEXT context;
  1551. PCDB cdb;
  1552. //
  1553. // Allocate Srb from nonpaged pool.
  1554. //
  1555. context = ExAllocatePoolWithTag(NonPagedPool,
  1556. sizeof(COMPLETION_CONTEXT),
  1557. '6CcS');
  1558. if(context == NULL) {
  1559. //
  1560. // ISSUE-2000/02/03-peterwie
  1561. // This code path was inheritted from the NT 4.0 class2.sys driver.
  1562. // It needs to be changed to survive low-memory conditions.
  1563. //
  1564. KeBugCheck(SCSI_DISK_DRIVER_INTERNAL);
  1565. }
  1566. //
  1567. // Save the device object in the context for use by the completion
  1568. // routine.
  1569. //
  1570. context->DeviceObject = Fdo;
  1571. srb = &context->Srb;
  1572. //
  1573. // Zero out srb.
  1574. //
  1575. RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK));
  1576. //
  1577. // Write length to SRB.
  1578. //
  1579. srb->Length = sizeof(SCSI_REQUEST_BLOCK);
  1580. srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
  1581. //
  1582. // Set timeout value large enough for drive to spin up.
  1583. //
  1584. srb->TimeOutValue = START_UNIT_TIMEOUT;
  1585. //
  1586. // Set the transfer length.
  1587. //
  1588. srb->SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER |
  1589. SRB_FLAGS_DISABLE_AUTOSENSE |
  1590. SRB_FLAGS_DISABLE_SYNCH_TRANSFER;
  1591. //
  1592. // Build the start unit CDB.
  1593. //
  1594. srb->CdbLength = 6;
  1595. cdb = (PCDB)srb->Cdb;
  1596. cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
  1597. cdb->START_STOP.Start = 1;
  1598. cdb->START_STOP.Immediate = 0;
  1599. cdb->START_STOP.LogicalUnitNumber = srb->Lun;
  1600. //
  1601. // Build the asynchronous request to be sent to the port driver.
  1602. // Since this routine is called from a DPC the IRP should always be
  1603. // available.
  1604. //
  1605. irp = IoAllocateIrp(Fdo->StackSize, FALSE);
  1606. if(irp == NULL) {
  1607. //
  1608. // ISSUE-2000/02/03-peterwie
  1609. // This code path was inheritted from the NT 4.0 class2.sys driver.
  1610. // It needs to be changed to survive low-memory conditions.
  1611. //
  1612. KeBugCheck(SCSI_DISK_DRIVER_INTERNAL);
  1613. }
  1614. ClassAcquireRemoveLock(Fdo, irp);
  1615. IoSetCompletionRoutine(irp,
  1616. (PIO_COMPLETION_ROUTINE)ClassAsynchronousCompletion,
  1617. context,
  1618. TRUE,
  1619. TRUE,
  1620. TRUE);
  1621. irpStack = IoGetNextIrpStackLocation(irp);
  1622. irpStack->MajorFunction = IRP_MJ_SCSI;
  1623. srb->OriginalRequest = irp;
  1624. //
  1625. // Store the SRB address in next stack for port driver.
  1626. //
  1627. irpStack->Parameters.Scsi.Srb = srb;
  1628. //
  1629. // Call the port driver with the IRP.
  1630. //
  1631. IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, irp);
  1632. return;
  1633. } // end StartUnit()
  1634. /*++////////////////////////////////////////////////////////////////////////////
  1635. ClassAsynchronousCompletion() ISSUE-2000/02/18-henrygab - why public?!
  1636. Routine Description:
  1637. This routine is called when an asynchronous I/O request
  1638. which was issused by the class driver completes. Examples of such requests
  1639. are release queue or START UNIT. This routine releases the queue if
  1640. necessary. It then frees the context and the IRP.
  1641. Arguments:
  1642. DeviceObject - The device object for the logical unit; however since this
  1643. is the top stack location the value is NULL.
  1644. Irp - Supplies a pointer to the Irp to be processed.
  1645. Context - Supplies the context to be used to process this request.
  1646. Return Value:
  1647. None.
  1648. --*/
  1649. NTSTATUS
  1650. ClassAsynchronousCompletion(
  1651. PDEVICE_OBJECT DeviceObject,
  1652. PIRP Irp,
  1653. PVOID Context
  1654. )
  1655. {
  1656. PCOMPLETION_CONTEXT context = Context;
  1657. PSCSI_REQUEST_BLOCK srb;
  1658. if(DeviceObject == NULL) {
  1659. DeviceObject = context->DeviceObject;
  1660. }
  1661. srb = &context->Srb;
  1662. //
  1663. // If this is an execute srb, then check the return status and make sure.
  1664. // the queue is not frozen.
  1665. //
  1666. if (srb->Function == SRB_FUNCTION_EXECUTE_SCSI) {
  1667. //
  1668. // Check for a frozen queue.
  1669. //
  1670. if (srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN) {
  1671. //
  1672. // Unfreeze the queue getting the device object from the context.
  1673. //
  1674. ClassReleaseQueue(context->DeviceObject);
  1675. }
  1676. }
  1677. { // free port-allocated sense buffer if we can detect
  1678. if (((PCOMMON_DEVICE_EXTENSION)(DeviceObject->DeviceExtension))->IsFdo) {
  1679. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
  1680. if (PORT_ALLOCATED_SENSE(fdoExtension, srb)) {
  1681. FREE_PORT_ALLOCATED_SENSE_BUFFER(fdoExtension, srb);
  1682. }
  1683. } else {
  1684. ASSERT(!TEST_FLAG(srb->SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
  1685. }
  1686. }
  1687. //
  1688. // Free the context and the Irp.
  1689. //
  1690. if (Irp->MdlAddress != NULL) {
  1691. MmUnlockPages(Irp->MdlAddress);
  1692. IoFreeMdl(Irp->MdlAddress);
  1693. Irp->MdlAddress = NULL;
  1694. }
  1695. ClassReleaseRemoveLock(DeviceObject, Irp);
  1696. ExFreePool(context);
  1697. IoFreeIrp(Irp);
  1698. //
  1699. // Indicate the I/O system should stop processing the Irp completion.
  1700. //
  1701. return STATUS_MORE_PROCESSING_REQUIRED;
  1702. } // end ClassAsynchronousCompletion()
  1703. VOID ServiceTransferRequest(PDEVICE_OBJECT Fdo, PIRP Irp)
  1704. {
  1705. PCOMMON_DEVICE_EXTENSION commonExt = Fdo->DeviceExtension;
  1706. PFUNCTIONAL_DEVICE_EXTENSION fdoExt = Fdo->DeviceExtension;
  1707. PCLASS_PRIVATE_FDO_DATA fdoData = fdoExt->PrivateFdoData;
  1708. PSTORAGE_ADAPTER_DESCRIPTOR adapterDesc = commonExt->PartitionZeroExtension->AdapterDescriptor;
  1709. PIO_STACK_LOCATION currentSp = IoGetCurrentIrpStackLocation(Irp);
  1710. ULONG entireXferLen = currentSp->Parameters.Read.Length;
  1711. PUCHAR bufPtr = MmGetMdlVirtualAddress(Irp->MdlAddress);
  1712. LARGE_INTEGER targetLocation = currentSp->Parameters.Read.ByteOffset;
  1713. PTRANSFER_PACKET pkt;
  1714. SINGLE_LIST_ENTRY pktList;
  1715. PSINGLE_LIST_ENTRY slistEntry;
  1716. ULONG numPackets;
  1717. KIRQL oldIrql;
  1718. ULONG i;
  1719. /*
  1720. * Compute the number of hw xfers we'll have to do.
  1721. * Calculate this without allowing for an overflow condition.
  1722. */
  1723. ASSERT(fdoData->HwMaxXferLen >= PAGE_SIZE);
  1724. numPackets = entireXferLen/fdoData->HwMaxXferLen;
  1725. if (entireXferLen % fdoData->HwMaxXferLen){
  1726. numPackets++;
  1727. }
  1728. /*
  1729. * First get all the TRANSFER_PACKETs that we'll need at once.
  1730. * Use our 'simple' slist functions since we don't need interlocked.
  1731. */
  1732. SimpleInitSlistHdr(&pktList);
  1733. for (i = 0; i < numPackets; i++){
  1734. pkt = DequeueFreeTransferPacket(Fdo, TRUE);
  1735. if (pkt){
  1736. SimplePushSlist(&pktList, &pkt->SlistEntry);
  1737. }
  1738. else {
  1739. break;
  1740. }
  1741. }
  1742. if (i == numPackets){
  1743. /*
  1744. * Initialize the original IRP's status to success.
  1745. * If any of the packets fail, they will set it to an error status.
  1746. * The IoStatus.Information field will be incremented to the
  1747. * transfer length as the pieces complete.
  1748. */
  1749. Irp->IoStatus.Status = STATUS_SUCCESS;
  1750. Irp->IoStatus.Information = 0;
  1751. /*
  1752. * Store the number of transfer pieces inside the original IRP.
  1753. * It will be used to count down the pieces as they complete.
  1754. */
  1755. Irp->Tail.Overlay.DriverContext[0] = LongToPtr(numPackets);
  1756. /*
  1757. * We are proceeding with the transfer.
  1758. * Mark the client IRP pending since it may complete on a different thread.
  1759. */
  1760. IoMarkIrpPending(Irp);
  1761. /*
  1762. * Transmit the pieces of the transfer.
  1763. */
  1764. while (entireXferLen > 0){
  1765. ULONG thisPieceLen = MIN(fdoData->HwMaxXferLen, entireXferLen);
  1766. /*
  1767. * Set up a TRANSFER_PACKET for this piece and send it.
  1768. */
  1769. slistEntry = SimplePopSlist(&pktList);
  1770. ASSERT(slistEntry);
  1771. pkt = CONTAINING_RECORD(slistEntry, TRANSFER_PACKET, SlistEntry);
  1772. SetupReadWriteTransferPacket( pkt,
  1773. bufPtr,
  1774. thisPieceLen,
  1775. targetLocation,
  1776. Irp);
  1777. SubmitTransferPacket(pkt);
  1778. entireXferLen -= thisPieceLen;
  1779. bufPtr += thisPieceLen;
  1780. targetLocation.QuadPart += thisPieceLen;
  1781. }
  1782. ASSERT(SimpleIsSlistEmpty(&pktList));
  1783. }
  1784. else if (i >= 1){
  1785. /*
  1786. * We were unable to get all the TRANSFER_PACKETs we need,
  1787. * but we did get at least one.
  1788. * That means that we are in extreme low-memory stress.
  1789. * We'll try doing this transfer using a single packet.
  1790. * The port driver is certainly also in stress, so use one-page
  1791. * transfers.
  1792. */
  1793. /*
  1794. * Free all but one of the TRANSFER_PACKETs.
  1795. */
  1796. while (i-- > 1){
  1797. slistEntry = SimplePopSlist(&pktList);
  1798. ASSERT(slistEntry);
  1799. pkt = CONTAINING_RECORD(slistEntry, TRANSFER_PACKET, SlistEntry);
  1800. EnqueueFreeTransferPacket(Fdo, pkt);
  1801. }
  1802. /*
  1803. * Get the single TRANSFER_PACKET that we'll be using.
  1804. */
  1805. slistEntry = SimplePopSlist(&pktList);
  1806. ASSERT(slistEntry);
  1807. ASSERT(SimpleIsSlistEmpty(&pktList));
  1808. pkt = CONTAINING_RECORD(slistEntry, TRANSFER_PACKET, SlistEntry);
  1809. DBGWARN(("Insufficient packets available in ServiceTransferRequest - entering lowMemRetry with pkt=%xh.", pkt));
  1810. /*
  1811. * Set default status and the number of transfer packets (one)
  1812. * inside the original irp.
  1813. */
  1814. Irp->IoStatus.Status = STATUS_SUCCESS;
  1815. Irp->IoStatus.Information = 0;
  1816. Irp->Tail.Overlay.DriverContext[0] = LongToPtr(1);
  1817. /*
  1818. * Mark the client irp pending since it may complete on
  1819. * another thread.
  1820. */
  1821. IoMarkIrpPending(Irp);
  1822. /*
  1823. * Set up the TRANSFER_PACKET for a lowMem transfer and launch.
  1824. */
  1825. SetupReadWriteTransferPacket( pkt,
  1826. bufPtr,
  1827. entireXferLen,
  1828. targetLocation,
  1829. Irp);
  1830. InitLowMemRetry(pkt, bufPtr, entireXferLen, targetLocation);
  1831. StepLowMemRetry(pkt);
  1832. }
  1833. else {
  1834. /*
  1835. * We were unable to get ANY TRANSFER_PACKETs.
  1836. * Defer this client irp until some TRANSFER_PACKETs free up.
  1837. */
  1838. DBGWARN(("No packets available in ServiceTransferRequest - deferring transfer (Irp=%xh)...", Irp));
  1839. IoMarkIrpPending(Irp);
  1840. EnqueueDeferredClientIrp(fdoData, Irp);
  1841. }
  1842. }
  1843. /*++////////////////////////////////////////////////////////////////////////////
  1844. ClassIoComplete()
  1845. Routine Description:
  1846. This routine executes when the port driver has completed a request.
  1847. It looks at the SRB status in the completing SRB and if not success
  1848. it checks for valid request sense buffer information. If valid, the
  1849. info is used to update status with more precise message of type of
  1850. error. This routine deallocates the SRB.
  1851. This routine should only be placed on the stack location for a class
  1852. driver FDO.
  1853. Arguments:
  1854. Fdo - Supplies the device object which represents the logical
  1855. unit.
  1856. Irp - Supplies the Irp which has completed.
  1857. Context - Supplies a pointer to the SRB.
  1858. Return Value:
  1859. NT status
  1860. --*/
  1861. NTSTATUS
  1862. ClassIoComplete(
  1863. IN PDEVICE_OBJECT Fdo,
  1864. IN PIRP Irp,
  1865. IN PVOID Context
  1866. )
  1867. {
  1868. PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
  1869. PSCSI_REQUEST_BLOCK srb = Context;
  1870. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  1871. PCLASS_PRIVATE_FDO_DATA fdoData = fdoExtension->PrivateFdoData;
  1872. NTSTATUS status;
  1873. BOOLEAN retry;
  1874. BOOLEAN callStartNextPacket;
  1875. ASSERT(fdoExtension->CommonExtension.IsFdo);
  1876. //
  1877. // Check SRB status for success of completing request.
  1878. //
  1879. if (SRB_STATUS(srb->SrbStatus) != SRB_STATUS_SUCCESS) {
  1880. ULONG retryInterval;
  1881. DebugPrint((2, "ClassIoComplete: IRP %p, SRB %p\n", Irp, srb));
  1882. //
  1883. // Release the queue if it is frozen.
  1884. //
  1885. if (srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN) {
  1886. ClassReleaseQueue(Fdo);
  1887. }
  1888. retry = ClassInterpretSenseInfo(
  1889. Fdo,
  1890. srb,
  1891. irpStack->MajorFunction,
  1892. irpStack->MajorFunction == IRP_MJ_DEVICE_CONTROL ?
  1893. irpStack->Parameters.DeviceIoControl.IoControlCode :
  1894. 0,
  1895. MAXIMUM_RETRIES -
  1896. ((ULONG)(ULONG_PTR)irpStack->Parameters.Others.Argument4),
  1897. &status,
  1898. &retryInterval);
  1899. //
  1900. // If the status is verified required and the this request
  1901. // should bypass verify required then retry the request.
  1902. //
  1903. if (TEST_FLAG(irpStack->Flags, SL_OVERRIDE_VERIFY_VOLUME) &&
  1904. status == STATUS_VERIFY_REQUIRED) {
  1905. status = STATUS_IO_DEVICE_ERROR;
  1906. retry = TRUE;
  1907. }
  1908. if (retry && ((ULONG)(ULONG_PTR)irpStack->Parameters.Others.Argument4)--) {
  1909. //
  1910. // Retry request.
  1911. //
  1912. DebugPrint((1, "Retry request %p\n", Irp));
  1913. if (PORT_ALLOCATED_SENSE(fdoExtension, srb)) {
  1914. FREE_PORT_ALLOCATED_SENSE_BUFFER(fdoExtension, srb);
  1915. }
  1916. RetryRequest(Fdo, Irp, srb, FALSE, retryInterval);
  1917. return STATUS_MORE_PROCESSING_REQUIRED;
  1918. }
  1919. } else {
  1920. //
  1921. // Set status for successful request
  1922. //
  1923. fdoData->LoggedTURFailureSinceLastIO = FALSE;
  1924. ClasspPerfIncrementSuccessfulIo(fdoExtension);
  1925. status = STATUS_SUCCESS;
  1926. } // end if (SRB_STATUS(srb->SrbStatus) == SRB_STATUS_SUCCESS)
  1927. //
  1928. // ensure we have returned some info, and it matches what the
  1929. // original request wanted for PAGING operations only
  1930. //
  1931. if ((NT_SUCCESS(status)) && TEST_FLAG(Irp->Flags, IRP_PAGING_IO)) {
  1932. ASSERT(Irp->IoStatus.Information != 0);
  1933. ASSERT(irpStack->Parameters.Read.Length == Irp->IoStatus.Information);
  1934. }
  1935. //
  1936. // remember if the caller wanted to skip calling IoStartNextPacket.
  1937. // for legacy reasons, we cannot call IoStartNextPacket for IoDeviceControl
  1938. // calls. this setting only affects device objects with StartIo routines.
  1939. //
  1940. callStartNextPacket = !TEST_FLAG(srb->SrbFlags, SRB_FLAGS_DONT_START_NEXT_PACKET);
  1941. if (irpStack->MajorFunction == IRP_MJ_DEVICE_CONTROL) {
  1942. callStartNextPacket = FALSE;
  1943. }
  1944. //
  1945. // Free the srb
  1946. //
  1947. if(!TEST_FLAG(srb->SrbFlags, SRB_CLASS_FLAGS_PERSISTANT)) {
  1948. if (PORT_ALLOCATED_SENSE(fdoExtension, srb)) {
  1949. FREE_PORT_ALLOCATED_SENSE_BUFFER(fdoExtension, srb);
  1950. }
  1951. if (fdoExtension->CommonExtension.IsSrbLookasideListInitialized){
  1952. ClassFreeOrReuseSrb(fdoExtension, srb);
  1953. }
  1954. else {
  1955. DBGWARN(("ClassIoComplete is freeing an SRB (possibly) on behalf of another driver."));
  1956. ExFreePool(srb);
  1957. }
  1958. } else {
  1959. DebugPrint((2, "ClassIoComplete: Not Freeing srb @ %p because "
  1960. "SRB_CLASS_FLAGS_PERSISTANT set\n", srb));
  1961. if (PORT_ALLOCATED_SENSE(fdoExtension, srb)) {
  1962. DebugPrint((2, "ClassIoComplete: Not Freeing sensebuffer @ %p "
  1963. " because SRB_CLASS_FLAGS_PERSISTANT set\n",
  1964. srb->SenseInfoBuffer));
  1965. }
  1966. }
  1967. //
  1968. // Set status in completing IRP.
  1969. //
  1970. Irp->IoStatus.Status = status;
  1971. //
  1972. // Set the hard error if necessary.
  1973. //
  1974. if (!NT_SUCCESS(status) &&
  1975. IoIsErrorUserInduced(status) &&
  1976. (Irp->Tail.Overlay.Thread != NULL)
  1977. ) {
  1978. //
  1979. // Store DeviceObject for filesystem, and clear
  1980. // in IoStatus.Information field.
  1981. //
  1982. IoSetHardErrorOrVerifyDevice(Irp, Fdo);
  1983. Irp->IoStatus.Information = 0;
  1984. }
  1985. //
  1986. // If pending has be returned for this irp then mark the current stack as
  1987. // pending.
  1988. //
  1989. if (Irp->PendingReturned) {
  1990. IoMarkIrpPending(Irp);
  1991. }
  1992. if (fdoExtension->CommonExtension.DriverExtension->InitData.ClassStartIo) {
  1993. if (callStartNextPacket) {
  1994. KIRQL oldIrql;
  1995. KeRaiseIrql(DISPATCH_LEVEL, &oldIrql);
  1996. IoStartNextPacket(Fdo, FALSE);
  1997. KeLowerIrql(oldIrql);
  1998. }
  1999. }
  2000. ClassReleaseRemoveLock(Fdo, Irp);
  2001. return status;
  2002. } // end ClassIoComplete()
  2003. /*++////////////////////////////////////////////////////////////////////////////
  2004. ClassSendSrbSynchronous()
  2005. Routine Description:
  2006. This routine is called by SCSI device controls to complete an
  2007. SRB and send it to the port driver synchronously (ie wait for
  2008. completion). The CDB is already completed along with the SRB CDB
  2009. size and request timeout value.
  2010. Arguments:
  2011. Fdo - Supplies the functional device object which represents the target.
  2012. Srb - Supplies a partially initialized SRB. The SRB cannot come from zone.
  2013. BufferAddress - Supplies the address of the buffer.
  2014. BufferLength - Supplies the length in bytes of the buffer.
  2015. WriteToDevice - Indicates the data should be transfer to the device.
  2016. Return Value:
  2017. NTSTATUS indicating the final results of the operation.
  2018. If NT_SUCCESS(), then the amount of usable data is contained in the field
  2019. Srb->DataTransferLength
  2020. --*/
  2021. NTSTATUS
  2022. ClassSendSrbSynchronous(
  2023. PDEVICE_OBJECT Fdo,
  2024. PSCSI_REQUEST_BLOCK Srb,
  2025. PVOID BufferAddress,
  2026. ULONG BufferLength,
  2027. BOOLEAN WriteToDevice
  2028. )
  2029. {
  2030. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  2031. PCLASS_PRIVATE_FDO_DATA fdoData = fdoExtension->PrivateFdoData;
  2032. IO_STATUS_BLOCK ioStatus;
  2033. ULONG controlType;
  2034. PIRP irp;
  2035. PIO_STACK_LOCATION irpStack;
  2036. KEVENT event;
  2037. PUCHAR senseInfoBuffer;
  2038. ULONG retryCount = MAXIMUM_RETRIES;
  2039. NTSTATUS status;
  2040. BOOLEAN retry;
  2041. //
  2042. // NOTE: This code is only pagable because we are not freezing
  2043. // the queue. Allowing the queue to be frozen from a pagable
  2044. // routine could leave the queue frozen as we try to page in
  2045. // the code to unfreeze the queue. The result would be a nice
  2046. // case of deadlock. Therefore, since we are unfreezing the
  2047. // queue regardless of the result, just set the NO_FREEZE_QUEUE
  2048. // flag in the SRB.
  2049. //
  2050. ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
  2051. ASSERT(fdoExtension->CommonExtension.IsFdo);
  2052. //
  2053. // Write length to SRB.
  2054. //
  2055. Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
  2056. //
  2057. // Set SCSI bus address.
  2058. //
  2059. Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
  2060. //
  2061. // Enable auto request sense.
  2062. //
  2063. Srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE;
  2064. //
  2065. // Sense buffer is in aligned nonpaged pool.
  2066. //
  2067. //
  2068. senseInfoBuffer = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
  2069. SENSE_BUFFER_SIZE,
  2070. '7CcS');
  2071. if (senseInfoBuffer == NULL) {
  2072. DebugPrint((1, "ClassSendSrbSynchronous: Can't allocate request sense "
  2073. "buffer\n"));
  2074. return(STATUS_INSUFFICIENT_RESOURCES);
  2075. }
  2076. Srb->SenseInfoBuffer = senseInfoBuffer;
  2077. Srb->DataBuffer = BufferAddress;
  2078. //
  2079. // Start retries here.
  2080. //
  2081. retry:
  2082. //
  2083. // use fdoextension's flags by default.
  2084. // do not move out of loop, as the flag may change due to errors
  2085. // sending this command.
  2086. //
  2087. Srb->SrbFlags = fdoExtension->SrbFlags;
  2088. if(BufferAddress != NULL) {
  2089. if(WriteToDevice) {
  2090. SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_OUT);
  2091. } else {
  2092. SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_IN);
  2093. }
  2094. }
  2095. //
  2096. // Initialize the QueueAction field.
  2097. //
  2098. Srb->QueueAction = SRB_SIMPLE_TAG_REQUEST;
  2099. //
  2100. // Disable synchronous transfer for these requests.
  2101. // Disable freezing the queue, since all we do is unfreeze it anyways.
  2102. //
  2103. SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
  2104. SET_FLAG(Srb->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE);
  2105. //
  2106. // Set the event object to the unsignaled state.
  2107. // It will be used to signal request completion.
  2108. //
  2109. KeInitializeEvent(&event, NotificationEvent, FALSE);
  2110. //
  2111. // Build device I/O control request with METHOD_NEITHER data transfer.
  2112. // We'll queue a completion routine to cleanup the MDL's and such ourself.
  2113. //
  2114. irp = IoAllocateIrp(
  2115. (CCHAR) (fdoExtension->CommonExtension.LowerDeviceObject->StackSize + 1),
  2116. FALSE);
  2117. if(irp == NULL) {
  2118. ExFreePool(senseInfoBuffer);
  2119. DebugPrint((1, "ClassSendSrbSynchronous: Can't allocate Irp\n"));
  2120. return(STATUS_INSUFFICIENT_RESOURCES);
  2121. }
  2122. //
  2123. // Get next stack location.
  2124. //
  2125. irpStack = IoGetNextIrpStackLocation(irp);
  2126. //
  2127. // Set up SRB for execute scsi request. Save SRB address in next stack
  2128. // for the port driver.
  2129. //
  2130. irpStack->MajorFunction = IRP_MJ_SCSI;
  2131. irpStack->Parameters.Scsi.Srb = Srb;
  2132. IoSetCompletionRoutine(irp,
  2133. ClasspSendSynchronousCompletion,
  2134. Srb,
  2135. TRUE,
  2136. TRUE,
  2137. TRUE);
  2138. irp->UserIosb = &ioStatus;
  2139. irp->UserEvent = &event;
  2140. if(BufferAddress) {
  2141. //
  2142. // Build an MDL for the data buffer and stick it into the irp. The
  2143. // completion routine will unlock the pages and free the MDL.
  2144. //
  2145. irp->MdlAddress = IoAllocateMdl( BufferAddress,
  2146. BufferLength,
  2147. FALSE,
  2148. FALSE,
  2149. irp );
  2150. if (irp->MdlAddress == NULL) {
  2151. ExFreePool(senseInfoBuffer);
  2152. Srb->SenseInfoBuffer = NULL;
  2153. IoFreeIrp( irp );
  2154. DebugPrint((1, "ClassSendSrbSynchronous: Can't allocate MDL\n"));
  2155. return STATUS_INSUFFICIENT_RESOURCES;
  2156. }
  2157. try {
  2158. //
  2159. // the io manager unlocks these pages upon completion
  2160. //
  2161. MmProbeAndLockPages( irp->MdlAddress,
  2162. KernelMode,
  2163. (WriteToDevice ? IoReadAccess :
  2164. IoWriteAccess));
  2165. } except(EXCEPTION_EXECUTE_HANDLER) {
  2166. status = GetExceptionCode();
  2167. ExFreePool(senseInfoBuffer);
  2168. Srb->SenseInfoBuffer = NULL;
  2169. IoFreeMdl(irp->MdlAddress);
  2170. IoFreeIrp(irp);
  2171. DebugPrint((1, "ClassSendSrbSynchronous: Exception %lx "
  2172. "locking buffer\n", status));
  2173. return status;
  2174. }
  2175. }
  2176. //
  2177. // Set the transfer length.
  2178. //
  2179. Srb->DataTransferLength = BufferLength;
  2180. //
  2181. // Zero out status.
  2182. //
  2183. Srb->ScsiStatus = Srb->SrbStatus = 0;
  2184. Srb->NextSrb = 0;
  2185. //
  2186. // Set up IRP Address.
  2187. //
  2188. Srb->OriginalRequest = irp;
  2189. //
  2190. // Call the port driver with the request and wait for it to complete.
  2191. //
  2192. status = IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, irp);
  2193. if (status == STATUS_PENDING) {
  2194. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  2195. status = ioStatus.Status;
  2196. }
  2197. //
  2198. // Check that request completed without error.
  2199. //
  2200. if (SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_SUCCESS) {
  2201. ULONG retryInterval;
  2202. DBGTRACE(ClassDebugWarning, ("ClassSendSrbSynchronous - srb %ph failed (op=%s srbstat=%s(%xh), irpstat=%xh, sense=%s/%s/%s)", Srb, DBGGETSCSIOPSTR(Srb), DBGGETSRBSTATUSSTR(Srb), (ULONG)Srb->SrbStatus, status, DBGGETSENSECODESTR(Srb), DBGGETADSENSECODESTR(Srb), DBGGETADSENSEQUALIFIERSTR(Srb)));
  2203. //
  2204. // assert that the queue is not frozen
  2205. //
  2206. ASSERT(!TEST_FLAG(Srb->SrbStatus, SRB_STATUS_QUEUE_FROZEN));
  2207. //
  2208. // Update status and determine if request should be retried.
  2209. //
  2210. retry = ClassInterpretSenseInfo(Fdo,
  2211. Srb,
  2212. IRP_MJ_SCSI,
  2213. 0,
  2214. MAXIMUM_RETRIES - retryCount,
  2215. &status,
  2216. &retryInterval);
  2217. if (retry) {
  2218. if ((status == STATUS_DEVICE_NOT_READY &&
  2219. ((PSENSE_DATA) senseInfoBuffer)->AdditionalSenseCode ==
  2220. SCSI_ADSENSE_LUN_NOT_READY) ||
  2221. (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_SELECTION_TIMEOUT)) {
  2222. LARGE_INTEGER delay;
  2223. //
  2224. // Delay for at least 2 seconds.
  2225. //
  2226. if(retryInterval < 2) {
  2227. retryInterval = 2;
  2228. }
  2229. delay.QuadPart = (LONGLONG)( - 10 * 1000 * (LONGLONG)1000 * retryInterval);
  2230. //
  2231. // Stall for a while to let the device become ready
  2232. //
  2233. KeDelayExecutionThread(KernelMode, FALSE, &delay);
  2234. }
  2235. //
  2236. // If retries are not exhausted then retry this operation.
  2237. //
  2238. if (retryCount--) {
  2239. if (PORT_ALLOCATED_SENSE(fdoExtension, Srb)) {
  2240. FREE_PORT_ALLOCATED_SENSE_BUFFER(fdoExtension, Srb);
  2241. }
  2242. goto retry;
  2243. }
  2244. }
  2245. } else {
  2246. fdoData->LoggedTURFailureSinceLastIO = FALSE;
  2247. status = STATUS_SUCCESS;
  2248. }
  2249. //
  2250. // required even though we allocated our own, since the port driver may
  2251. // have allocated one also
  2252. //
  2253. if (PORT_ALLOCATED_SENSE(fdoExtension, Srb)) {
  2254. FREE_PORT_ALLOCATED_SENSE_BUFFER(fdoExtension, Srb);
  2255. }
  2256. Srb->SenseInfoBuffer = NULL;
  2257. ExFreePool(senseInfoBuffer);
  2258. return status;
  2259. }
  2260. /*++////////////////////////////////////////////////////////////////////////////
  2261. ClassInterpretSenseInfo()
  2262. Routine Description:
  2263. This routine interprets the data returned from the SCSI
  2264. request sense. It determines the status to return in the
  2265. IRP and whether this request can be retried.
  2266. Arguments:
  2267. DeviceObject - Supplies the device object associated with this request.
  2268. Srb - Supplies the scsi request block which failed.
  2269. MajorFunctionCode - Supplies the function code to be used for logging.
  2270. IoDeviceCode - Supplies the device code to be used for logging.
  2271. Status - Returns the status for the request.
  2272. Return Value:
  2273. BOOLEAN TRUE: Drivers should retry this request.
  2274. FALSE: Drivers should not retry this request.
  2275. --*/
  2276. BOOLEAN
  2277. ClassInterpretSenseInfo(
  2278. IN PDEVICE_OBJECT Fdo,
  2279. IN PSCSI_REQUEST_BLOCK Srb,
  2280. IN UCHAR MajorFunctionCode,
  2281. IN ULONG IoDeviceCode,
  2282. IN ULONG RetryCount,
  2283. OUT NTSTATUS *Status,
  2284. OUT OPTIONAL ULONG *RetryInterval
  2285. )
  2286. {
  2287. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  2288. PCOMMON_DEVICE_EXTENSION commonExtension = Fdo->DeviceExtension;
  2289. PCLASS_PRIVATE_FDO_DATA fdoData = fdoExtension->PrivateFdoData;
  2290. PSENSE_DATA senseBuffer = Srb->SenseInfoBuffer;
  2291. BOOLEAN retry = TRUE;
  2292. BOOLEAN logError = FALSE;
  2293. BOOLEAN unhandledError = FALSE;
  2294. BOOLEAN incrementErrorCount = FALSE;
  2295. ULONG badSector = 0;
  2296. ULONG uniqueId = 0;
  2297. NTSTATUS logStatus;
  2298. ULONG readSector;
  2299. ULONG index;
  2300. ULONG retryInterval = 0;
  2301. KIRQL oldIrql;
  2302. logStatus = -1;
  2303. if(TEST_FLAG(Srb->SrbFlags, SRB_CLASS_FLAGS_PAGING)) {
  2304. //
  2305. // Log anything remotely incorrect about paging i/o
  2306. //
  2307. logError = TRUE;
  2308. uniqueId = 301;
  2309. logStatus = IO_WARNING_PAGING_FAILURE;
  2310. }
  2311. //
  2312. // Check that request sense buffer is valid.
  2313. //
  2314. ASSERT(fdoExtension->CommonExtension.IsFdo);
  2315. //
  2316. // must handle the SRB_STATUS_INTERNAL_ERROR case first,
  2317. // as it has all the flags set.
  2318. //
  2319. if (SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_INTERNAL_ERROR) {
  2320. DebugPrint((ClassDebugSenseInfo,
  2321. "ClassInterpretSenseInfo: Internal Error code is %x\n",
  2322. Srb->InternalStatus));
  2323. retry = FALSE;
  2324. *Status = Srb->InternalStatus;
  2325. } else if ((Srb->SrbStatus & SRB_STATUS_AUTOSENSE_VALID) &&
  2326. (Srb->SenseInfoBufferLength >=
  2327. offsetof(SENSE_DATA, CommandSpecificInformation))) {
  2328. //
  2329. // Zero the additional sense code and additional sense code qualifier
  2330. // if they were not returned by the device.
  2331. //
  2332. readSector = senseBuffer->AdditionalSenseLength +
  2333. offsetof(SENSE_DATA, AdditionalSenseLength);
  2334. if (readSector > Srb->SenseInfoBufferLength) {
  2335. readSector = Srb->SenseInfoBufferLength;
  2336. }
  2337. if (readSector <= offsetof(SENSE_DATA, AdditionalSenseCode)) {
  2338. senseBuffer->AdditionalSenseCode = 0;
  2339. }
  2340. if (readSector <= offsetof(SENSE_DATA, AdditionalSenseCodeQualifier)) {
  2341. senseBuffer->AdditionalSenseCodeQualifier = 0;
  2342. }
  2343. DebugPrint((ClassDebugSenseInfo,
  2344. "ClassInterpretSenseInfo: Error code is %x\n",
  2345. senseBuffer->ErrorCode));
  2346. DebugPrint((ClassDebugSenseInfo,
  2347. "ClassInterpretSenseInfo: Sense key is %x\n",
  2348. senseBuffer->SenseKey));
  2349. DebugPrint((ClassDebugSenseInfo,
  2350. "ClassInterpretSenseInfo: Additional sense code is %x\n",
  2351. senseBuffer->AdditionalSenseCode));
  2352. DebugPrint((ClassDebugSenseInfo,
  2353. "ClassInterpretSenseInfo: Additional sense code qualifier "
  2354. "is %x\n",
  2355. senseBuffer->AdditionalSenseCodeQualifier));
  2356. switch (senseBuffer->SenseKey & 0xf) {
  2357. case SCSI_SENSE_NOT_READY: {
  2358. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2359. "Device not ready\n"));
  2360. *Status = STATUS_DEVICE_NOT_READY;
  2361. switch (senseBuffer->AdditionalSenseCode) {
  2362. case SCSI_ADSENSE_LUN_NOT_READY: {
  2363. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2364. "Lun not ready\n"));
  2365. switch (senseBuffer->AdditionalSenseCodeQualifier) {
  2366. case SCSI_SENSEQ_OPERATION_IN_PROGRESS: {
  2367. DEVICE_EVENT_BECOMING_READY notReady;
  2368. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2369. "Operation In Progress\n"));
  2370. retryInterval = NOT_READY_RETRY_INTERVAL;
  2371. RtlZeroMemory(&notReady, sizeof(DEVICE_EVENT_BECOMING_READY));
  2372. notReady.Version = 1;
  2373. notReady.Reason = 2;
  2374. notReady.Estimated100msToReady = retryInterval * 10;
  2375. ClasspSendNotification(fdoExtension,
  2376. &GUID_IO_DEVICE_BECOMING_READY,
  2377. sizeof(DEVICE_EVENT_BECOMING_READY),
  2378. &notReady);
  2379. break;
  2380. }
  2381. case SCSI_SENSEQ_BECOMING_READY: {
  2382. DEVICE_EVENT_BECOMING_READY notReady;
  2383. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2384. "In process of becoming ready\n"));
  2385. retryInterval = NOT_READY_RETRY_INTERVAL;
  2386. RtlZeroMemory(&notReady, sizeof(DEVICE_EVENT_BECOMING_READY));
  2387. notReady.Version = 1;
  2388. notReady.Reason = 1;
  2389. notReady.Estimated100msToReady = retryInterval * 10;
  2390. ClasspSendNotification(fdoExtension,
  2391. &GUID_IO_DEVICE_BECOMING_READY,
  2392. sizeof(DEVICE_EVENT_BECOMING_READY),
  2393. &notReady);
  2394. break;
  2395. }
  2396. case SCSI_SENSEQ_LONG_WRITE_IN_PROGRESS: {
  2397. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2398. "Long write in progress\n"));
  2399. retry = FALSE;
  2400. break;
  2401. }
  2402. case SCSI_SENSEQ_MANUAL_INTERVENTION_REQUIRED: {
  2403. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2404. "Manual intervention required\n"));
  2405. *Status = STATUS_NO_MEDIA_IN_DEVICE;
  2406. retry = FALSE;
  2407. break;
  2408. }
  2409. case SCSI_SENSEQ_FORMAT_IN_PROGRESS: {
  2410. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2411. "Format in progress\n"));
  2412. retry = FALSE;
  2413. break;
  2414. }
  2415. case SCSI_SENSEQ_CAUSE_NOT_REPORTABLE: {
  2416. if(!TEST_FLAG(fdoExtension->ScanForSpecialFlags,
  2417. CLASS_SPECIAL_CAUSE_NOT_REPORTABLE_HACK)) {
  2418. DebugPrint((ClassDebugSenseInfo,
  2419. "ClassInterpretSenseInfo: "
  2420. "not ready, cause unknown\n"));
  2421. /*
  2422. Many non-WHQL certified drives (mostly CD-RW) return
  2423. this when they have no media instead of the obvious
  2424. choice of:
  2425. SCSI_SENSE_NOT_READY/SCSI_ADSENSE_NO_MEDIA_IN_DEVICE
  2426. These drives should not pass WHQL certification due
  2427. to this discrepency.
  2428. */
  2429. retry = FALSE;
  2430. break;
  2431. } else {
  2432. //
  2433. // Treat this as init command required and fall through.
  2434. //
  2435. }
  2436. }
  2437. case SCSI_SENSEQ_INIT_COMMAND_REQUIRED:
  2438. default: {
  2439. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2440. "Initializing command required\n"));
  2441. //
  2442. // This sense code/additional sense code
  2443. // combination may indicate that the device
  2444. // needs to be started. Send an start unit if this
  2445. // is a disk device.
  2446. //
  2447. if(TEST_FLAG(fdoExtension->DeviceFlags,
  2448. DEV_SAFE_START_UNIT) &&
  2449. !TEST_FLAG(Srb->SrbFlags,
  2450. SRB_CLASS_FLAGS_LOW_PRIORITY)) {
  2451. ClassSendStartUnit(Fdo);
  2452. }
  2453. break;
  2454. }
  2455. } // end switch (senseBuffer->AdditionalSenseCodeQualifier)
  2456. break;
  2457. }
  2458. case SCSI_ADSENSE_NO_MEDIA_IN_DEVICE: {
  2459. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2460. "No Media in device.\n"));
  2461. *Status = STATUS_NO_MEDIA_IN_DEVICE;
  2462. retry = FALSE;
  2463. //
  2464. // signal MCN that there isn't any media in the device
  2465. //
  2466. if (!TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) {
  2467. DebugPrint((ClassDebugError, "ClassInterpretSenseInfo: "
  2468. "No Media in a non-removable device %p\n",
  2469. Fdo));
  2470. }
  2471. ClassSetMediaChangeState(fdoExtension, MediaNotPresent, FALSE);
  2472. break;
  2473. }
  2474. } // end switch (senseBuffer->AdditionalSenseCode)
  2475. break;
  2476. } // end SCSI_SENSE_NOT_READY
  2477. case SCSI_SENSE_DATA_PROTECT: {
  2478. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2479. "Media write protected\n"));
  2480. *Status = STATUS_MEDIA_WRITE_PROTECTED;
  2481. retry = FALSE;
  2482. break;
  2483. } // end SCSI_SENSE_DATA_PROTECT
  2484. case SCSI_SENSE_MEDIUM_ERROR: {
  2485. DebugPrint((ClassDebugSenseInfo,"ClassInterpretSenseInfo: "
  2486. "Medium Error (bad block)\n"));
  2487. *Status = STATUS_DEVICE_DATA_ERROR;
  2488. retry = FALSE;
  2489. logError = TRUE;
  2490. uniqueId = 256;
  2491. logStatus = IO_ERR_BAD_BLOCK;
  2492. //
  2493. // Check if this error is due to unknown format
  2494. //
  2495. if (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_INVALID_MEDIA){
  2496. switch (senseBuffer->AdditionalSenseCodeQualifier) {
  2497. case SCSI_SENSEQ_UNKNOWN_FORMAT: {
  2498. *Status = STATUS_UNRECOGNIZED_MEDIA;
  2499. //
  2500. // Log error only if this is a paging request
  2501. //
  2502. if(!TEST_FLAG(Srb->SrbFlags, SRB_CLASS_FLAGS_PAGING)) {
  2503. logError = FALSE;
  2504. }
  2505. break;
  2506. }
  2507. case SCSI_SENSEQ_CLEANING_CARTRIDGE_INSTALLED: {
  2508. *Status = STATUS_CLEANER_CARTRIDGE_INSTALLED;
  2509. logError = FALSE;
  2510. break;
  2511. }
  2512. default: {
  2513. break;
  2514. }
  2515. } // end switch AdditionalSenseCodeQualifier
  2516. } // end SCSI_ADSENSE_INVALID_MEDIA
  2517. break;
  2518. } // end SCSI_SENSE_MEDIUM_ERROR
  2519. case SCSI_SENSE_HARDWARE_ERROR: {
  2520. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2521. "Hardware error\n"));
  2522. *Status = STATUS_IO_DEVICE_ERROR;
  2523. logError = TRUE;
  2524. uniqueId = 257;
  2525. logStatus = IO_ERR_CONTROLLER_ERROR;
  2526. break;
  2527. } // end SCSI_SENSE_HARDWARE_ERROR
  2528. case SCSI_SENSE_ILLEGAL_REQUEST: {
  2529. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2530. "Illegal SCSI request\n"));
  2531. *Status = STATUS_INVALID_DEVICE_REQUEST;
  2532. retry = FALSE;
  2533. switch (senseBuffer->AdditionalSenseCode) {
  2534. case SCSI_ADSENSE_ILLEGAL_COMMAND: {
  2535. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2536. "Illegal command\n"));
  2537. break;
  2538. }
  2539. case SCSI_ADSENSE_ILLEGAL_BLOCK: {
  2540. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2541. "Illegal block address\n"));
  2542. *Status = STATUS_NONEXISTENT_SECTOR;
  2543. break;
  2544. }
  2545. case SCSI_ADSENSE_INVALID_LUN: {
  2546. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2547. "Invalid LUN\n"));
  2548. *Status = STATUS_NO_SUCH_DEVICE;
  2549. break;
  2550. }
  2551. case SCSI_ADSENSE_MUSIC_AREA: {
  2552. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2553. "Music area\n"));
  2554. break;
  2555. }
  2556. case SCSI_ADSENSE_DATA_AREA: {
  2557. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2558. "Data area\n"));
  2559. break;
  2560. }
  2561. case SCSI_ADSENSE_VOLUME_OVERFLOW: {
  2562. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2563. "Volume overflow\n"));
  2564. break;
  2565. }
  2566. case SCSI_ADSENSE_COPY_PROTECTION_FAILURE: {
  2567. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2568. "Copy protection failure\n"));
  2569. *Status = STATUS_COPY_PROTECTION_FAILURE;
  2570. switch (senseBuffer->AdditionalSenseCodeQualifier) {
  2571. case SCSI_SENSEQ_AUTHENTICATION_FAILURE:
  2572. DebugPrint((ClassDebugSenseInfo,
  2573. "ClassInterpretSenseInfo: "
  2574. "Authentication failure\n"));
  2575. *Status = STATUS_CSS_AUTHENTICATION_FAILURE;
  2576. break;
  2577. case SCSI_SENSEQ_KEY_NOT_PRESENT:
  2578. DebugPrint((ClassDebugSenseInfo,
  2579. "ClassInterpretSenseInfo: "
  2580. "Key not present\n"));
  2581. *Status = STATUS_CSS_KEY_NOT_PRESENT;
  2582. break;
  2583. case SCSI_SENSEQ_KEY_NOT_ESTABLISHED:
  2584. DebugPrint((ClassDebugSenseInfo,
  2585. "ClassInterpretSenseInfo: "
  2586. "Key not established\n"));
  2587. *Status = STATUS_CSS_KEY_NOT_ESTABLISHED;
  2588. break;
  2589. case SCSI_SENSEQ_READ_OF_SCRAMBLED_SECTOR_WITHOUT_AUTHENTICATION:
  2590. DebugPrint((ClassDebugSenseInfo,
  2591. "ClassInterpretSenseInfo: "
  2592. "Read of scrambled sector w/o "
  2593. "authentication\n"));
  2594. *Status = STATUS_CSS_SCRAMBLED_SECTOR;
  2595. break;
  2596. case SCSI_SENSEQ_MEDIA_CODE_MISMATCHED_TO_LOGICAL_UNIT:
  2597. DebugPrint((ClassDebugSenseInfo,
  2598. "ClassInterpretSenseInfo: "
  2599. "Media region does not logical unit "
  2600. "region\n"));
  2601. *Status = STATUS_CSS_REGION_MISMATCH;
  2602. break;
  2603. case SCSI_SENSEQ_LOGICAL_UNIT_RESET_COUNT_ERROR:
  2604. DebugPrint((ClassDebugSenseInfo,
  2605. "ClassInterpretSenseInfo: "
  2606. "Region set error -- region may "
  2607. "be permanent\n"));
  2608. *Status = STATUS_CSS_RESETS_EXHAUSTED;
  2609. break;
  2610. } // end switch of ASCQ for COPY_PROTECTION_FAILURE
  2611. break;
  2612. }
  2613. case SCSI_ADSENSE_INVALID_CDB: {
  2614. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2615. "Invalid CDB\n"));
  2616. //
  2617. // Note: the retry interval is not typically used.
  2618. // it is set here only because a ClassErrorHandler
  2619. // cannot set the retryInterval, and the error may
  2620. // require a few commands to be sent to clear whatever
  2621. // caused this condition (i.e. disk clears the write
  2622. // cache, requiring at least two commands)
  2623. //
  2624. // hopefully, this shortcoming can be changed for
  2625. // blackcomb.
  2626. //
  2627. retryInterval = 3;
  2628. break;
  2629. }
  2630. } // end switch (senseBuffer->AdditionalSenseCode)
  2631. break;
  2632. } // end SCSI_SENSE_ILLEGAL_REQUEST
  2633. case SCSI_SENSE_UNIT_ATTENTION: {
  2634. PVPB vpb;
  2635. ULONG count;
  2636. //
  2637. // A media change may have occured so increment the change
  2638. // count for the physical device
  2639. //
  2640. count = InterlockedIncrement(&fdoExtension->MediaChangeCount);
  2641. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2642. "Media change count for device %d incremented to %#lx\n",
  2643. fdoExtension->DeviceNumber, count));
  2644. switch (senseBuffer->AdditionalSenseCode) {
  2645. case SCSI_ADSENSE_MEDIUM_CHANGED: {
  2646. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2647. "Media changed\n"));
  2648. if (!TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) {
  2649. DebugPrint((ClassDebugError, "ClassInterpretSenseInfo: "
  2650. "Media Changed on non-removable device %p\n",
  2651. Fdo));
  2652. }
  2653. ClassSetMediaChangeState(fdoExtension, MediaPresent, FALSE);
  2654. break;
  2655. }
  2656. case SCSI_ADSENSE_BUS_RESET: {
  2657. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2658. "Bus reset\n"));
  2659. break;
  2660. }
  2661. case SCSI_ADSENSE_OPERATOR_REQUEST: {
  2662. switch (senseBuffer->AdditionalSenseCodeQualifier) {
  2663. case SCSI_SENSEQ_MEDIUM_REMOVAL: {
  2664. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2665. "Ejection request received!\n"));
  2666. ClassSendEjectionNotification(fdoExtension);
  2667. break;
  2668. }
  2669. case SCSI_SENSEQ_WRITE_PROTECT_ENABLE: {
  2670. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2671. "Operator selected write permit?! "
  2672. "(unsupported!)\n"));
  2673. break;
  2674. }
  2675. case SCSI_SENSEQ_WRITE_PROTECT_DISABLE: {
  2676. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2677. "Operator selected write protect?! "
  2678. "(unsupported!)\n"));
  2679. break;
  2680. }
  2681. }
  2682. }
  2683. default: {
  2684. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2685. "Unit attention\n"));
  2686. break;
  2687. }
  2688. } // end switch (senseBuffer->AdditionalSenseCode)
  2689. if (TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA))
  2690. {
  2691. //
  2692. // TODO : Is the media lockable?
  2693. //
  2694. if ((ClassGetVpb(Fdo) != NULL) && (ClassGetVpb(Fdo)->Flags & VPB_MOUNTED))
  2695. {
  2696. //
  2697. // Set bit to indicate that media may have changed
  2698. // and volume needs verification.
  2699. //
  2700. SET_FLAG(Fdo->Flags, DO_VERIFY_VOLUME);
  2701. *Status = STATUS_VERIFY_REQUIRED;
  2702. retry = FALSE;
  2703. }
  2704. }
  2705. else
  2706. {
  2707. *Status = STATUS_IO_DEVICE_ERROR;
  2708. }
  2709. break;
  2710. } // end SCSI_SENSE_UNIT_ATTENTION
  2711. case SCSI_SENSE_ABORTED_COMMAND: {
  2712. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2713. "Command aborted\n"));
  2714. *Status = STATUS_IO_DEVICE_ERROR;
  2715. retryInterval = 1;
  2716. break;
  2717. } // end SCSI_SENSE_ABORTED_COMMAND
  2718. case SCSI_SENSE_BLANK_CHECK: {
  2719. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2720. "Media blank check\n"));
  2721. retry = FALSE;
  2722. *Status = STATUS_NO_DATA_DETECTED;
  2723. break;
  2724. } // end SCSI_SENSE_BLANK_CHECK
  2725. case SCSI_SENSE_RECOVERED_ERROR: {
  2726. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2727. "Recovered error\n"));
  2728. *Status = STATUS_SUCCESS;
  2729. retry = FALSE;
  2730. logError = TRUE;
  2731. uniqueId = 258;
  2732. switch(senseBuffer->AdditionalSenseCode) {
  2733. case SCSI_ADSENSE_SEEK_ERROR:
  2734. case SCSI_ADSENSE_TRACK_ERROR: {
  2735. logStatus = IO_ERR_SEEK_ERROR;
  2736. break;
  2737. }
  2738. case SCSI_ADSENSE_REC_DATA_NOECC:
  2739. case SCSI_ADSENSE_REC_DATA_ECC: {
  2740. logStatus = IO_RECOVERED_VIA_ECC;
  2741. break;
  2742. }
  2743. case SCSI_ADSENSE_FAILURE_PREDICTION_THRESHOLD_EXCEEDED: {
  2744. UCHAR wmiEventData[5];
  2745. *((PULONG)wmiEventData) = sizeof(UCHAR);
  2746. wmiEventData[sizeof(ULONG)] = senseBuffer->AdditionalSenseCodeQualifier;
  2747. //
  2748. // Don't log another eventlog if we have already logged once
  2749. // NOTE: this should have been interlocked, but the structure
  2750. // was publicly defined to use a BOOLEAN (char). Since
  2751. // media only reports these errors once per X minutes,
  2752. // the potential race condition is nearly non-existant.
  2753. // the worst case is duplicate log entries, so ignore.
  2754. //
  2755. if (fdoExtension->FailurePredicted == 0) {
  2756. logError = TRUE;
  2757. }
  2758. fdoExtension->FailurePredicted = TRUE;
  2759. fdoExtension->FailureReason = senseBuffer->AdditionalSenseCodeQualifier;
  2760. logStatus = IO_WRN_FAILURE_PREDICTED;
  2761. ClassNotifyFailurePredicted(fdoExtension,
  2762. (PUCHAR)&wmiEventData,
  2763. sizeof(wmiEventData),
  2764. 0,
  2765. 4,
  2766. Srb->PathId,
  2767. Srb->TargetId,
  2768. Srb->Lun);
  2769. break;
  2770. }
  2771. default: {
  2772. logStatus = IO_ERR_CONTROLLER_ERROR;
  2773. break;
  2774. }
  2775. } // end switch(senseBuffer->AdditionalSenseCode)
  2776. if (senseBuffer->IncorrectLength) {
  2777. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2778. "Incorrect length detected.\n"));
  2779. *Status = STATUS_INVALID_BLOCK_LENGTH ;
  2780. }
  2781. break;
  2782. } // end SCSI_SENSE_RECOVERED_ERROR
  2783. case SCSI_SENSE_NO_SENSE: {
  2784. //
  2785. // Check other indicators.
  2786. //
  2787. if (senseBuffer->IncorrectLength) {
  2788. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2789. "Incorrect length detected.\n"));
  2790. *Status = STATUS_INVALID_BLOCK_LENGTH ;
  2791. retry = FALSE;
  2792. } else {
  2793. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2794. "No specific sense key\n"));
  2795. *Status = STATUS_IO_DEVICE_ERROR;
  2796. retry = TRUE;
  2797. }
  2798. break;
  2799. } // end SCSI_SENSE_NO_SENSE
  2800. default: {
  2801. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2802. "Unrecognized sense code\n"));
  2803. *Status = STATUS_IO_DEVICE_ERROR;
  2804. break;
  2805. }
  2806. } // end switch (senseBuffer->SenseKey & 0xf)
  2807. //
  2808. // Try to determine the bad sector from the inquiry data.
  2809. //
  2810. if ((((PCDB)Srb->Cdb)->CDB10.OperationCode == SCSIOP_READ ||
  2811. ((PCDB)Srb->Cdb)->CDB10.OperationCode == SCSIOP_VERIFY ||
  2812. ((PCDB)Srb->Cdb)->CDB10.OperationCode == SCSIOP_WRITE)) {
  2813. for (index = 0; index < 4; index++) {
  2814. badSector = (badSector << 8) | senseBuffer->Information[index];
  2815. }
  2816. readSector = 0;
  2817. for (index = 0; index < 4; index++) {
  2818. readSector = (readSector << 8) | Srb->Cdb[index+2];
  2819. }
  2820. index = (((PCDB)Srb->Cdb)->CDB10.TransferBlocksMsb << 8) |
  2821. ((PCDB)Srb->Cdb)->CDB10.TransferBlocksLsb;
  2822. //
  2823. // Make sure the bad sector is within the read sectors.
  2824. //
  2825. if (!(badSector >= readSector && badSector < readSector + index)) {
  2826. badSector = readSector;
  2827. }
  2828. }
  2829. } else {
  2830. //
  2831. // Request sense buffer not valid. No sense information
  2832. // to pinpoint the error. Return general request fail.
  2833. //
  2834. DebugPrint((ClassDebugSenseInfo, "ClassInterpretSenseInfo: "
  2835. "Request sense info not valid. SrbStatus %2x\n",
  2836. SRB_STATUS(Srb->SrbStatus)));
  2837. retry = TRUE;
  2838. switch (SRB_STATUS(Srb->SrbStatus)) {
  2839. case SRB_STATUS_INVALID_LUN:
  2840. case SRB_STATUS_INVALID_TARGET_ID:
  2841. case SRB_STATUS_NO_DEVICE:
  2842. case SRB_STATUS_NO_HBA:
  2843. case SRB_STATUS_INVALID_PATH_ID: {
  2844. *Status = STATUS_NO_SUCH_DEVICE;
  2845. retry = FALSE;
  2846. break;
  2847. }
  2848. case SRB_STATUS_COMMAND_TIMEOUT:
  2849. case SRB_STATUS_TIMEOUT: {
  2850. //
  2851. // Update the error count for the device.
  2852. //
  2853. incrementErrorCount = TRUE;
  2854. *Status = STATUS_IO_TIMEOUT;
  2855. break;
  2856. }
  2857. case SRB_STATUS_ABORTED: {
  2858. //
  2859. // Update the error count for the device.
  2860. //
  2861. incrementErrorCount = TRUE;
  2862. *Status = STATUS_IO_TIMEOUT;
  2863. retryInterval = 1;
  2864. break;
  2865. }
  2866. case SRB_STATUS_SELECTION_TIMEOUT: {
  2867. logError = TRUE;
  2868. logStatus = IO_ERR_NOT_READY;
  2869. uniqueId = 260;
  2870. *Status = STATUS_DEVICE_NOT_CONNECTED;
  2871. retry = FALSE;
  2872. break;
  2873. }
  2874. case SRB_STATUS_DATA_OVERRUN: {
  2875. *Status = STATUS_DATA_OVERRUN;
  2876. retry = FALSE;
  2877. break;
  2878. }
  2879. case SRB_STATUS_PHASE_SEQUENCE_FAILURE: {
  2880. //
  2881. // Update the error count for the device.
  2882. //
  2883. incrementErrorCount = TRUE;
  2884. *Status = STATUS_IO_DEVICE_ERROR;
  2885. //
  2886. // If there was phase sequence error then limit the number of
  2887. // retries.
  2888. //
  2889. if (RetryCount > 1 ) {
  2890. retry = FALSE;
  2891. }
  2892. break;
  2893. }
  2894. case SRB_STATUS_REQUEST_FLUSHED: {
  2895. //
  2896. // If the status needs verification bit is set. Then set
  2897. // the status to need verification and no retry; otherwise,
  2898. // just retry the request.
  2899. //
  2900. if (TEST_FLAG(Fdo->Flags, DO_VERIFY_VOLUME)) {
  2901. *Status = STATUS_VERIFY_REQUIRED;
  2902. retry = FALSE;
  2903. } else {
  2904. *Status = STATUS_IO_DEVICE_ERROR;
  2905. }
  2906. break;
  2907. }
  2908. case SRB_STATUS_INVALID_REQUEST: {
  2909. *Status = STATUS_INVALID_DEVICE_REQUEST;
  2910. retry = FALSE;
  2911. break;
  2912. }
  2913. case SRB_STATUS_UNEXPECTED_BUS_FREE:
  2914. case SRB_STATUS_PARITY_ERROR:
  2915. //
  2916. // Update the error count for the device
  2917. // and fall through to below
  2918. //
  2919. incrementErrorCount = TRUE;
  2920. case SRB_STATUS_BUS_RESET: {
  2921. *Status = STATUS_IO_DEVICE_ERROR;
  2922. break;
  2923. }
  2924. case SRB_STATUS_ERROR: {
  2925. *Status = STATUS_IO_DEVICE_ERROR;
  2926. if (Srb->ScsiStatus == 0) {
  2927. //
  2928. // This is some strange return code. Update the error
  2929. // count for the device.
  2930. //
  2931. incrementErrorCount = TRUE;
  2932. } if (Srb->ScsiStatus == SCSISTAT_BUSY) {
  2933. *Status = STATUS_DEVICE_NOT_READY;
  2934. } if (Srb->ScsiStatus == SCSISTAT_RESERVATION_CONFLICT) {
  2935. *Status = STATUS_DEVICE_BUSY;
  2936. retry = FALSE;
  2937. logError = FALSE;
  2938. }
  2939. break;
  2940. }
  2941. default: {
  2942. logError = TRUE;
  2943. logStatus = IO_ERR_CONTROLLER_ERROR;
  2944. uniqueId = 259;
  2945. *Status = STATUS_IO_DEVICE_ERROR;
  2946. unhandledError = TRUE;
  2947. break;
  2948. }
  2949. }
  2950. //
  2951. // NTRAID #183546 - if we support GESN subtype NOT_READY events, and
  2952. // we know from a previous poll when the device will be ready (ETA)
  2953. // we should delay the retry more appropriately than just guessing.
  2954. //
  2955. /*
  2956. if (fdoExtension->MediaChangeDetectionInfo &&
  2957. fdoExtension->MediaChangeDetectionInfo->Gesn.Supported &&
  2958. TEST_FLAG(fdoExtension->MediaChangeDetectionInfo->Gesn.EventMask,
  2959. NOTIFICATION_DEVICE_BUSY_CLASS_MASK)
  2960. ) {
  2961. // check if Gesn.ReadyTime if greater than current tick count
  2962. // if so, delay that long (from 1 to 30 seconds max?)
  2963. // else, leave the guess of time alone.
  2964. }
  2965. */
  2966. }
  2967. if (incrementErrorCount) {
  2968. //
  2969. // if any error count occurred, delay the retry of this io by
  2970. // at least one second, if caller supports it.
  2971. //
  2972. if (retryInterval == 0) {
  2973. retryInterval = 1;
  2974. }
  2975. ClasspPerfIncrementErrorCount(fdoExtension);
  2976. }
  2977. //
  2978. // If there is a class specific error handler call it.
  2979. //
  2980. if (fdoExtension->CommonExtension.DevInfo->ClassError != NULL) {
  2981. fdoExtension->CommonExtension.DevInfo->ClassError(Fdo,
  2982. Srb,
  2983. Status,
  2984. &retry);
  2985. }
  2986. //
  2987. // If the caller wants to know the suggested retry interval tell them.
  2988. //
  2989. if(ARGUMENT_PRESENT(RetryInterval)) {
  2990. *RetryInterval = retryInterval;
  2991. }
  2992. /*
  2993. * LOG the error:
  2994. * Always log the error in our internal log.
  2995. * If logError is set, also log the error in the system log.
  2996. */
  2997. {
  2998. ULONG totalSize;
  2999. ULONG senseBufferSize = 0;
  3000. IO_ERROR_LOG_PACKET staticErrLogEntry = {0};
  3001. CLASS_ERROR_LOG_DATA staticErrLogData = {0};
  3002. //
  3003. // Calculate the total size of the error log entry.
  3004. // add to totalSize in the order that they are used.
  3005. // the advantage to calculating all the sizes here is
  3006. // that we don't have to do a bunch of extraneous checks
  3007. // later on in this code path.
  3008. //
  3009. totalSize = sizeof(IO_ERROR_LOG_PACKET) // required
  3010. - sizeof(ULONG) // struct includes one ULONG
  3011. + sizeof(CLASS_ERROR_LOG_DATA);// struct for ease
  3012. //
  3013. // also save any available extra sense data, up to the maximum errlog
  3014. // packet size . WMI should be used for real-time analysis.
  3015. // the event log should only be used for post-mortem debugging.
  3016. //
  3017. if (TEST_FLAG(Srb->SrbStatus, SRB_STATUS_AUTOSENSE_VALID)) {
  3018. ULONG validSenseBytes;
  3019. BOOLEAN validSense;
  3020. //
  3021. // make sure we can at least access the AdditionalSenseLength field
  3022. //
  3023. validSense = RTL_CONTAINS_FIELD(senseBuffer,
  3024. Srb->SenseInfoBufferLength,
  3025. AdditionalSenseLength);
  3026. if (validSense) {
  3027. //
  3028. // if extra info exists, copy the maximum amount of available
  3029. // sense data that is safe into the the errlog.
  3030. //
  3031. validSenseBytes = senseBuffer->AdditionalSenseLength
  3032. + offsetof(SENSE_DATA, AdditionalSenseLength);
  3033. //
  3034. // this is invalid because it causes overflow!
  3035. // whoever sent this type of request would cause
  3036. // a system crash.
  3037. //
  3038. ASSERT(validSenseBytes < MAX_ADDITIONAL_SENSE_BYTES);
  3039. //
  3040. // set to save the most sense buffer possible
  3041. //
  3042. senseBufferSize = max(validSenseBytes, sizeof(SENSE_DATA));
  3043. senseBufferSize = min(senseBufferSize, Srb->SenseInfoBufferLength);
  3044. } else {
  3045. //
  3046. // it's smaller than required to read the total number of
  3047. // valid bytes, so just use the SenseInfoBufferLength field.
  3048. //
  3049. senseBufferSize = Srb->SenseInfoBufferLength;
  3050. }
  3051. /*
  3052. * Bump totalSize by the number of extra senseBuffer bytes
  3053. * (beyond the default sense buffer within CLASS_ERROR_LOG_DATA).
  3054. * Make sure to never allocate more than ERROR_LOG_MAXIMUM_SIZE.
  3055. */
  3056. if (senseBufferSize > sizeof(SENSE_DATA)){
  3057. totalSize += senseBufferSize-sizeof(SENSE_DATA);
  3058. if (totalSize > ERROR_LOG_MAXIMUM_SIZE){
  3059. senseBufferSize -= totalSize-ERROR_LOG_MAXIMUM_SIZE;
  3060. totalSize = ERROR_LOG_MAXIMUM_SIZE;
  3061. }
  3062. }
  3063. }
  3064. //
  3065. // If we've used up all of our retry attempts, set the final status to
  3066. // reflect the appropriate result.
  3067. //
  3068. if (retry && RetryCount < MAXIMUM_RETRIES) {
  3069. staticErrLogEntry.FinalStatus = STATUS_SUCCESS;
  3070. staticErrLogData.ErrorRetried = TRUE;
  3071. } else {
  3072. staticErrLogEntry.FinalStatus = *Status;
  3073. }
  3074. if (TEST_FLAG(Srb->SrbFlags, SRB_CLASS_FLAGS_PAGING)) {
  3075. staticErrLogData.ErrorPaging = TRUE;
  3076. }
  3077. if (unhandledError) {
  3078. staticErrLogData.ErrorUnhandled = TRUE;
  3079. }
  3080. //
  3081. // Calculate the device offset if there is a geometry.
  3082. //
  3083. staticErrLogEntry.DeviceOffset.QuadPart = (LONGLONG)badSector;
  3084. staticErrLogEntry.DeviceOffset.QuadPart *= (LONGLONG)fdoExtension->DiskGeometry.BytesPerSector;
  3085. if (logStatus == -1){
  3086. staticErrLogEntry.ErrorCode = STATUS_IO_DEVICE_ERROR;
  3087. } else {
  3088. staticErrLogEntry.ErrorCode = logStatus;
  3089. }
  3090. /*
  3091. * The dump data follows the IO_ERROR_LOG_PACKET,
  3092. * with the first ULONG of dump data inside the packet.
  3093. */
  3094. staticErrLogEntry.DumpDataSize = (USHORT)totalSize - sizeof(IO_ERROR_LOG_PACKET) + sizeof(ULONG);
  3095. staticErrLogEntry.SequenceNumber = 0;
  3096. staticErrLogEntry.MajorFunctionCode = MajorFunctionCode;
  3097. staticErrLogEntry.IoControlCode = IoDeviceCode;
  3098. staticErrLogEntry.RetryCount = (UCHAR) RetryCount;
  3099. staticErrLogEntry.UniqueErrorValue = uniqueId;
  3100. KeQueryTickCount(&staticErrLogData.TickCount);
  3101. staticErrLogData.PortNumber = (ULONG)-1;
  3102. /*
  3103. * Save the entire contents of the SRB.
  3104. */
  3105. staticErrLogData.Srb = *Srb;
  3106. /*
  3107. * For our private log, save just the default length of the SENSE_DATA.
  3108. */
  3109. if (senseBufferSize != 0){
  3110. RtlCopyMemory(&staticErrLogData.SenseData, senseBuffer, min(senseBufferSize, sizeof(SENSE_DATA)));
  3111. }
  3112. /*
  3113. * Save the error log in our context.
  3114. * We only save the default sense buffer length.
  3115. */
  3116. KeAcquireSpinLock(&fdoData->SpinLock, &oldIrql);
  3117. fdoData->ErrorLogs[fdoData->ErrorLogNextIndex] = staticErrLogData;
  3118. fdoData->ErrorLogNextIndex++;
  3119. fdoData->ErrorLogNextIndex %= NUM_ERROR_LOG_ENTRIES;
  3120. KeReleaseSpinLock(&fdoData->SpinLock, oldIrql);
  3121. /*
  3122. * If logError is set, also save this log in the system's error log.
  3123. * But make sure we don't log TUR failures over and over
  3124. * (e.g. if an external drive was switched off and we're still sending TUR's to it every second).
  3125. */
  3126. if ((((PCDB)Srb->Cdb)->CDB10.OperationCode == SCSIOP_TEST_UNIT_READY) && logError){
  3127. if (fdoData->LoggedTURFailureSinceLastIO){
  3128. logError = FALSE;
  3129. }
  3130. else {
  3131. fdoData->LoggedTURFailureSinceLastIO = TRUE;
  3132. }
  3133. }
  3134. if (logError){
  3135. PIO_ERROR_LOG_PACKET errorLogEntry;
  3136. PCLASS_ERROR_LOG_DATA errlogData;
  3137. errorLogEntry = (PIO_ERROR_LOG_PACKET)IoAllocateErrorLogEntry(Fdo, (UCHAR)totalSize);
  3138. if (errorLogEntry){
  3139. errlogData = (PCLASS_ERROR_LOG_DATA)errorLogEntry->DumpData;
  3140. *errorLogEntry = staticErrLogEntry;
  3141. *errlogData = staticErrLogData;
  3142. /*
  3143. * For the system log, copy as much of the sense buffer as possible.
  3144. */
  3145. if (senseBufferSize != 0) {
  3146. RtlCopyMemory(&errlogData->SenseData, senseBuffer, senseBufferSize);
  3147. }
  3148. /*
  3149. * Write the error log packet to the system error logging thread.
  3150. */
  3151. IoWriteErrorLogEntry(errorLogEntry);
  3152. }
  3153. }
  3154. }
  3155. return retry;
  3156. } // end ClassInterpretSenseInfo()
  3157. /*++////////////////////////////////////////////////////////////////////////////
  3158. ClassModeSense()
  3159. Routine Description:
  3160. This routine sends a mode sense command to a target ID and returns
  3161. when it is complete.
  3162. Arguments:
  3163. Fdo - Supplies the functional device object associated with this request.
  3164. ModeSenseBuffer - Supplies a buffer to store the sense data.
  3165. Length - Supplies the length in bytes of the mode sense buffer.
  3166. PageMode - Supplies the page or pages of mode sense data to be retrived.
  3167. Return Value:
  3168. Length of the transferred data is returned.
  3169. --*/
  3170. ULONG ClassModeSense( IN PDEVICE_OBJECT Fdo,
  3171. IN PCHAR ModeSenseBuffer,
  3172. IN ULONG Length,
  3173. IN UCHAR PageMode)
  3174. {
  3175. ULONG lengthTransferred = 0;
  3176. PMDL senseBufferMdl;
  3177. PAGED_CODE();
  3178. senseBufferMdl = BuildDeviceInputMdl(ModeSenseBuffer, Length);
  3179. if (senseBufferMdl){
  3180. TRANSFER_PACKET *pkt = DequeueFreeTransferPacket(Fdo, TRUE);
  3181. if (pkt){
  3182. KEVENT event;
  3183. NTSTATUS pktStatus;
  3184. IRP pseudoIrp = {0};
  3185. /*
  3186. * Store the number of packets servicing the irp (one)
  3187. * inside the original IRP. It will be used to counted down
  3188. * to zero when the packet completes.
  3189. * Initialize the original IRP's status to success.
  3190. * If the packet fails, we will set it to the error status.
  3191. */
  3192. pseudoIrp.Tail.Overlay.DriverContext[0] = LongToPtr(1);
  3193. pseudoIrp.IoStatus.Status = STATUS_SUCCESS;
  3194. pseudoIrp.IoStatus.Information = 0;
  3195. pseudoIrp.MdlAddress = senseBufferMdl;
  3196. /*
  3197. * Set this up as a SYNCHRONOUS transfer, submit it,
  3198. * and wait for the packet to complete. The result
  3199. * status will be written to the original irp.
  3200. */
  3201. ASSERT(Length <= 0x0ff);
  3202. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  3203. SetupModeSenseTransferPacket(pkt, &event, ModeSenseBuffer, (UCHAR)Length, PageMode, &pseudoIrp);
  3204. SubmitTransferPacket(pkt);
  3205. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  3206. if (NT_SUCCESS(pseudoIrp.IoStatus.Status)){
  3207. lengthTransferred = (ULONG)pseudoIrp.IoStatus.Information;
  3208. }
  3209. else {
  3210. /*
  3211. * This request can sometimes fail legitimately
  3212. * (e.g. when a SCSI device is attached but turned off)
  3213. * so this is not necessarily a device/driver bug.
  3214. */
  3215. DBGTRACE(ClassDebugWarning, ("ClassModeSense on Fdo %ph failed with status %xh.", Fdo, pseudoIrp.IoStatus.Status));
  3216. }
  3217. }
  3218. FreeDeviceInputMdl(senseBufferMdl);
  3219. }
  3220. return lengthTransferred;
  3221. }
  3222. /*++////////////////////////////////////////////////////////////////////////////
  3223. ClassFindModePage()
  3224. Routine Description:
  3225. This routine scans through the mode sense data and finds the requested
  3226. mode sense page code.
  3227. Arguments:
  3228. ModeSenseBuffer - Supplies a pointer to the mode sense data.
  3229. Length - Indicates the length of valid data.
  3230. PageMode - Supplies the page mode to be searched for.
  3231. Use6Byte - Indicates whether 6 or 10 byte mode sense was used.
  3232. Return Value:
  3233. A pointer to the the requested mode page. If the mode page was not found
  3234. then NULL is return.
  3235. --*/
  3236. PVOID
  3237. ClassFindModePage(
  3238. IN PCHAR ModeSenseBuffer,
  3239. IN ULONG Length,
  3240. IN UCHAR PageMode,
  3241. IN BOOLEAN Use6Byte
  3242. )
  3243. {
  3244. PUCHAR limit;
  3245. ULONG parameterHeaderLength;
  3246. PVOID result = NULL;
  3247. limit = ModeSenseBuffer + Length;
  3248. parameterHeaderLength = (Use6Byte) ? sizeof(MODE_PARAMETER_HEADER) : sizeof(MODE_PARAMETER_HEADER10);
  3249. if (Length >= parameterHeaderLength) {
  3250. PMODE_PARAMETER_HEADER10 modeParam10;
  3251. ULONG blockDescriptorLength;
  3252. /*
  3253. * Skip the mode select header and block descriptors.
  3254. */
  3255. if (Use6Byte){
  3256. blockDescriptorLength = ((PMODE_PARAMETER_HEADER) ModeSenseBuffer)->BlockDescriptorLength;
  3257. }
  3258. else {
  3259. modeParam10 = (PMODE_PARAMETER_HEADER10) ModeSenseBuffer;
  3260. blockDescriptorLength = modeParam10->BlockDescriptorLength[1];
  3261. }
  3262. ModeSenseBuffer += parameterHeaderLength + blockDescriptorLength;
  3263. //
  3264. // ModeSenseBuffer now points at pages. Walk the pages looking for the
  3265. // requested page until the limit is reached.
  3266. //
  3267. while (ModeSenseBuffer +
  3268. RTL_SIZEOF_THROUGH_FIELD(MODE_DISCONNECT_PAGE, PageLength) < limit) {
  3269. if (((PMODE_DISCONNECT_PAGE) ModeSenseBuffer)->PageCode == PageMode) {
  3270. /*
  3271. * found the mode page. make sure it's safe to touch it all
  3272. * before returning the pointer to caller
  3273. */
  3274. if (ModeSenseBuffer + ((PMODE_DISCONNECT_PAGE)ModeSenseBuffer)->PageLength > limit) {
  3275. /*
  3276. * Return NULL since the page is not safe to access in full
  3277. */
  3278. result = NULL;
  3279. }
  3280. else {
  3281. result = ModeSenseBuffer;
  3282. }
  3283. break;
  3284. }
  3285. //
  3286. // Advance to the next page which is 4-byte-aligned offset after this page.
  3287. //
  3288. ModeSenseBuffer +=
  3289. ((PMODE_DISCONNECT_PAGE) ModeSenseBuffer)->PageLength +
  3290. RTL_SIZEOF_THROUGH_FIELD(MODE_DISCONNECT_PAGE, PageLength);
  3291. }
  3292. }
  3293. return result;
  3294. } // end ClassFindModePage()
  3295. /*++////////////////////////////////////////////////////////////////////////////
  3296. ClassSendSrbAsynchronous()
  3297. Routine Description:
  3298. This routine takes a partially built Srb and an Irp and sends it down to
  3299. the port driver.
  3300. This routine must be called with the remove lock held for the specified
  3301. Irp.
  3302. Arguments:
  3303. Fdo - Supplies the functional device object for the orginal request.
  3304. Srb - Supplies a paritally build ScsiRequestBlock. In particular, the
  3305. CDB and the SRB timeout value must be filled in. The SRB must not be
  3306. allocated from zone.
  3307. Irp - Supplies the requesting Irp.
  3308. BufferAddress - Supplies a pointer to the buffer to be transfered.
  3309. BufferLength - Supplies the length of data transfer.
  3310. WriteToDevice - Indicates the data transfer will be from system memory to
  3311. device.
  3312. Return Value:
  3313. Returns STATUS_PENDING if the request is dispatched (since the
  3314. completion routine may change the irp's status value we cannot simply
  3315. return the value of the dispatch)
  3316. or returns a status value to indicate why it failed.
  3317. --*/
  3318. NTSTATUS
  3319. ClassSendSrbAsynchronous(
  3320. PDEVICE_OBJECT Fdo,
  3321. PSCSI_REQUEST_BLOCK Srb,
  3322. PIRP Irp,
  3323. PVOID BufferAddress,
  3324. ULONG BufferLength,
  3325. BOOLEAN WriteToDevice
  3326. )
  3327. {
  3328. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  3329. PIO_STACK_LOCATION irpStack;
  3330. ULONG savedFlags;
  3331. //
  3332. // Write length to SRB.
  3333. //
  3334. Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
  3335. //
  3336. // Set SCSI bus address.
  3337. //
  3338. Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
  3339. //
  3340. // This is a violation of the SCSI spec but it is required for
  3341. // some targets.
  3342. //
  3343. // Srb->Cdb[1] |= deviceExtension->Lun << 5;
  3344. //
  3345. // Indicate auto request sense by specifying buffer and size.
  3346. //
  3347. Srb->SenseInfoBuffer = fdoExtension->SenseData;
  3348. Srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE;
  3349. Srb->DataBuffer = BufferAddress;
  3350. //
  3351. // Save the class driver specific flags away.
  3352. //
  3353. savedFlags = Srb->SrbFlags & SRB_FLAGS_CLASS_DRIVER_RESERVED;
  3354. //
  3355. // Allow the caller to specify that they do not wish
  3356. // IoStartNextPacket() to be called in the completion routine.
  3357. //
  3358. SET_FLAG(savedFlags, (Srb->SrbFlags & SRB_FLAGS_DONT_START_NEXT_PACKET));
  3359. if (BufferAddress != NULL) {
  3360. //
  3361. // Build Mdl if necessary.
  3362. //
  3363. if (Irp->MdlAddress == NULL) {
  3364. if (IoAllocateMdl(BufferAddress,
  3365. BufferLength,
  3366. FALSE,
  3367. FALSE,
  3368. Irp) == NULL) {
  3369. Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
  3370. //
  3371. // ClassIoComplete() would have free'd the srb
  3372. //
  3373. if (PORT_ALLOCATED_SENSE(fdoExtension, Srb)) {
  3374. FREE_PORT_ALLOCATED_SENSE_BUFFER(fdoExtension, Srb);
  3375. }
  3376. ClassFreeOrReuseSrb(fdoExtension, Srb);
  3377. ClassReleaseRemoveLock(Fdo, Irp);
  3378. ClassCompleteRequest(Fdo, Irp, IO_NO_INCREMENT);
  3379. return STATUS_INSUFFICIENT_RESOURCES;
  3380. }
  3381. MmBuildMdlForNonPagedPool(Irp->MdlAddress);
  3382. } else {
  3383. //
  3384. // Make sure the buffer requested matches the MDL.
  3385. //
  3386. ASSERT(BufferAddress == MmGetMdlVirtualAddress(Irp->MdlAddress));
  3387. }
  3388. //
  3389. // Set read flag.
  3390. //
  3391. Srb->SrbFlags = WriteToDevice ? SRB_FLAGS_DATA_OUT : SRB_FLAGS_DATA_IN;
  3392. } else {
  3393. //
  3394. // Clear flags.
  3395. //
  3396. Srb->SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER;
  3397. }
  3398. //
  3399. // Restore saved flags.
  3400. //
  3401. SET_FLAG(Srb->SrbFlags, savedFlags);
  3402. //
  3403. // Disable synchronous transfer for these requests.
  3404. //
  3405. SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
  3406. //
  3407. // Set the transfer length.
  3408. //
  3409. Srb->DataTransferLength = BufferLength;
  3410. //
  3411. // Zero out status.
  3412. //
  3413. Srb->ScsiStatus = Srb->SrbStatus = 0;
  3414. Srb->NextSrb = 0;
  3415. //
  3416. // Save a few parameters in the current stack location.
  3417. //
  3418. irpStack = IoGetCurrentIrpStackLocation(Irp);
  3419. //
  3420. // Save retry count in current Irp stack.
  3421. //
  3422. irpStack->Parameters.Others.Argument4 = (PVOID)MAXIMUM_RETRIES;
  3423. //
  3424. // Set up IoCompletion routine address.
  3425. //
  3426. IoSetCompletionRoutine(Irp, ClassIoComplete, Srb, TRUE, TRUE, TRUE);
  3427. //
  3428. // Get next stack location and
  3429. // set major function code.
  3430. //
  3431. irpStack = IoGetNextIrpStackLocation(Irp);
  3432. irpStack->MajorFunction = IRP_MJ_SCSI;
  3433. //
  3434. // Save SRB address in next stack for port driver.
  3435. //
  3436. irpStack->Parameters.Scsi.Srb = Srb;
  3437. //
  3438. // Set up Irp Address.
  3439. //
  3440. Srb->OriginalRequest = Irp;
  3441. //
  3442. // Call the port driver to process the request.
  3443. //
  3444. IoMarkIrpPending(Irp);
  3445. IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, Irp);
  3446. return STATUS_PENDING;
  3447. } // end ClassSendSrbAsynchronous()
  3448. /*++////////////////////////////////////////////////////////////////////////////
  3449. ClassDeviceControlDispatch()
  3450. Routine Description:
  3451. The routine is the common class driver device control dispatch entry point.
  3452. This routine is invokes the device-specific drivers DeviceControl routine,
  3453. (which may call the Class driver's common DeviceControl routine).
  3454. Arguments:
  3455. DeviceObject - Supplies a pointer to the device object for this request.
  3456. Irp - Supplies the Irp making the request.
  3457. Return Value:
  3458. Returns the status returned from the device-specific driver.
  3459. --*/
  3460. NTSTATUS
  3461. ClassDeviceControlDispatch(
  3462. PDEVICE_OBJECT DeviceObject,
  3463. PIRP Irp
  3464. )
  3465. {
  3466. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  3467. ULONG isRemoved;
  3468. isRemoved = ClassAcquireRemoveLock(DeviceObject, Irp);
  3469. if(isRemoved) {
  3470. ClassReleaseRemoveLock(DeviceObject, Irp);
  3471. Irp->IoStatus.Status = STATUS_DEVICE_DOES_NOT_EXIST;
  3472. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3473. return STATUS_DEVICE_DOES_NOT_EXIST;
  3474. }
  3475. //
  3476. // Call the class specific driver DeviceControl routine.
  3477. // If it doesn't handle it, it will call back into ClassDeviceControl.
  3478. //
  3479. ASSERT(commonExtension->DevInfo->ClassDeviceControl);
  3480. return commonExtension->DevInfo->ClassDeviceControl(DeviceObject,Irp);
  3481. } // end ClassDeviceControlDispatch()
  3482. /*++////////////////////////////////////////////////////////////////////////////
  3483. ClassDeviceControl()
  3484. Routine Description:
  3485. The routine is the common class driver device control dispatch function.
  3486. This routine is called by a class driver when it get an unrecognized
  3487. device control request. This routine will perform the correct action for
  3488. common requests such as lock media. If the device request is unknown it
  3489. passed down to the next level.
  3490. This routine must be called with the remove lock held for the specified
  3491. irp.
  3492. Arguments:
  3493. DeviceObject - Supplies a pointer to the device object for this request.
  3494. Irp - Supplies the Irp making the request.
  3495. Return Value:
  3496. Returns back a STATUS_PENDING or a completion status.
  3497. --*/
  3498. NTSTATUS
  3499. ClassDeviceControl(
  3500. PDEVICE_OBJECT DeviceObject,
  3501. PIRP Irp
  3502. )
  3503. {
  3504. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  3505. PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
  3506. PIO_STACK_LOCATION nextStack = NULL;
  3507. ULONG controlCode = irpStack->Parameters.DeviceIoControl.IoControlCode;
  3508. PSCSI_REQUEST_BLOCK srb = NULL;
  3509. PCDB cdb = NULL;
  3510. NTSTATUS status;
  3511. ULONG modifiedIoControlCode;
  3512. //
  3513. // If this is a pass through I/O control, set the minor function code
  3514. // and device address and pass it to the port driver.
  3515. //
  3516. if ((controlCode == IOCTL_SCSI_PASS_THROUGH) ||
  3517. (controlCode == IOCTL_SCSI_PASS_THROUGH_DIRECT)) {
  3518. PSCSI_PASS_THROUGH scsiPass;
  3519. //
  3520. // Validiate the user buffer.
  3521. //
  3522. #if defined (_WIN64)
  3523. if (IoIs32bitProcess(Irp)) {
  3524. if (irpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(SCSI_PASS_THROUGH32)){
  3525. Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
  3526. ClassReleaseRemoveLock(DeviceObject, Irp);
  3527. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3528. status = STATUS_INVALID_PARAMETER;
  3529. goto SetStatusAndReturn;
  3530. }
  3531. }
  3532. else
  3533. #endif
  3534. {
  3535. if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
  3536. sizeof(SCSI_PASS_THROUGH)) {
  3537. Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
  3538. ClassReleaseRemoveLock(DeviceObject, Irp);
  3539. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3540. status = STATUS_INVALID_PARAMETER;
  3541. goto SetStatusAndReturn;
  3542. }
  3543. }
  3544. IoCopyCurrentIrpStackLocationToNext(Irp);
  3545. nextStack = IoGetNextIrpStackLocation(Irp);
  3546. nextStack->MinorFunction = 1;
  3547. ClassReleaseRemoveLock(DeviceObject, Irp);
  3548. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  3549. goto SetStatusAndReturn;
  3550. }
  3551. Irp->IoStatus.Information = 0;
  3552. switch (controlCode) {
  3553. case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: {
  3554. PMOUNTDEV_UNIQUE_ID uniqueId;
  3555. if (!commonExtension->MountedDeviceInterfaceName.Buffer) {
  3556. status = STATUS_INVALID_PARAMETER;
  3557. break;
  3558. }
  3559. if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3560. sizeof(MOUNTDEV_UNIQUE_ID)) {
  3561. status = STATUS_BUFFER_TOO_SMALL;
  3562. Irp->IoStatus.Information = sizeof(MOUNTDEV_UNIQUE_ID);
  3563. break;
  3564. }
  3565. uniqueId = Irp->AssociatedIrp.SystemBuffer;
  3566. uniqueId->UniqueIdLength =
  3567. commonExtension->MountedDeviceInterfaceName.Length;
  3568. if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3569. sizeof(USHORT) + uniqueId->UniqueIdLength) {
  3570. status = STATUS_BUFFER_OVERFLOW;
  3571. Irp->IoStatus.Information = sizeof(MOUNTDEV_UNIQUE_ID);
  3572. break;
  3573. }
  3574. RtlCopyMemory(uniqueId->UniqueId,
  3575. commonExtension->MountedDeviceInterfaceName.Buffer,
  3576. uniqueId->UniqueIdLength);
  3577. status = STATUS_SUCCESS;
  3578. Irp->IoStatus.Information = sizeof(USHORT) +
  3579. uniqueId->UniqueIdLength;
  3580. break;
  3581. }
  3582. case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: {
  3583. PMOUNTDEV_NAME name;
  3584. ASSERT(commonExtension->DeviceName.Buffer);
  3585. if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3586. sizeof(MOUNTDEV_NAME)) {
  3587. status = STATUS_BUFFER_TOO_SMALL;
  3588. Irp->IoStatus.Information = sizeof(MOUNTDEV_NAME);
  3589. break;
  3590. }
  3591. name = Irp->AssociatedIrp.SystemBuffer;
  3592. name->NameLength = commonExtension->DeviceName.Length;
  3593. if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3594. sizeof(USHORT) + name->NameLength) {
  3595. status = STATUS_BUFFER_OVERFLOW;
  3596. Irp->IoStatus.Information = sizeof(MOUNTDEV_NAME);
  3597. break;
  3598. }
  3599. RtlCopyMemory(name->Name, commonExtension->DeviceName.Buffer,
  3600. name->NameLength);
  3601. status = STATUS_SUCCESS;
  3602. Irp->IoStatus.Information = sizeof(USHORT) + name->NameLength;
  3603. break;
  3604. }
  3605. case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: {
  3606. PMOUNTDEV_SUGGESTED_LINK_NAME suggestedName;
  3607. WCHAR driveLetterNameBuffer[10];
  3608. RTL_QUERY_REGISTRY_TABLE queryTable[2];
  3609. PWSTR valueName;
  3610. UNICODE_STRING driveLetterName;
  3611. if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3612. sizeof(MOUNTDEV_SUGGESTED_LINK_NAME)) {
  3613. status = STATUS_BUFFER_TOO_SMALL;
  3614. Irp->IoStatus.Information = sizeof(MOUNTDEV_SUGGESTED_LINK_NAME);
  3615. break;
  3616. }
  3617. valueName = ExAllocatePoolWithTag(
  3618. PagedPool,
  3619. commonExtension->DeviceName.Length + sizeof(WCHAR),
  3620. '8CcS');
  3621. if (!valueName) {
  3622. status = STATUS_INSUFFICIENT_RESOURCES;
  3623. break;
  3624. }
  3625. RtlCopyMemory(valueName, commonExtension->DeviceName.Buffer,
  3626. commonExtension->DeviceName.Length);
  3627. valueName[commonExtension->DeviceName.Length/sizeof(WCHAR)] = 0;
  3628. driveLetterName.Buffer = driveLetterNameBuffer;
  3629. driveLetterName.MaximumLength = 20;
  3630. driveLetterName.Length = 0;
  3631. RtlZeroMemory(queryTable, 2*sizeof(RTL_QUERY_REGISTRY_TABLE));
  3632. queryTable[0].Flags = RTL_QUERY_REGISTRY_REQUIRED |
  3633. RTL_QUERY_REGISTRY_DIRECT;
  3634. queryTable[0].Name = valueName;
  3635. queryTable[0].EntryContext = &driveLetterName;
  3636. status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE,
  3637. L"\\Registry\\Machine\\System\\DISK",
  3638. queryTable, NULL, NULL);
  3639. if (!NT_SUCCESS(status)) {
  3640. ExFreePool(valueName);
  3641. break;
  3642. }
  3643. if (driveLetterName.Length == 4 &&
  3644. driveLetterName.Buffer[0] == '%' &&
  3645. driveLetterName.Buffer[1] == ':') {
  3646. driveLetterName.Buffer[0] = 0xFF;
  3647. } else if (driveLetterName.Length != 4 ||
  3648. driveLetterName.Buffer[0] < FirstDriveLetter ||
  3649. driveLetterName.Buffer[0] > LastDriveLetter ||
  3650. driveLetterName.Buffer[1] != ':') {
  3651. status = STATUS_NOT_FOUND;
  3652. ExFreePool(valueName);
  3653. break;
  3654. }
  3655. suggestedName = Irp->AssociatedIrp.SystemBuffer;
  3656. suggestedName->UseOnlyIfThereAreNoOtherLinks = TRUE;
  3657. suggestedName->NameLength = 28;
  3658. Irp->IoStatus.Information =
  3659. FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME, Name) + 28;
  3660. if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3661. Irp->IoStatus.Information) {
  3662. Irp->IoStatus.Information =
  3663. sizeof(MOUNTDEV_SUGGESTED_LINK_NAME);
  3664. status = STATUS_BUFFER_OVERFLOW;
  3665. ExFreePool(valueName);
  3666. break;
  3667. }
  3668. RtlDeleteRegistryValue(RTL_REGISTRY_ABSOLUTE,
  3669. L"\\Registry\\Machine\\System\\DISK",
  3670. valueName);
  3671. ExFreePool(valueName);
  3672. RtlCopyMemory(suggestedName->Name, L"\\DosDevices\\", 24);
  3673. suggestedName->Name[12] = driveLetterName.Buffer[0];
  3674. suggestedName->Name[13] = ':';
  3675. //
  3676. // NT_SUCCESS(status) based on RtlQueryRegistryValues
  3677. //
  3678. status = STATUS_SUCCESS;
  3679. break;
  3680. }
  3681. default:
  3682. status = STATUS_PENDING;
  3683. break;
  3684. }
  3685. if (status != STATUS_PENDING) {
  3686. ClassReleaseRemoveLock(DeviceObject, Irp);
  3687. Irp->IoStatus.Status = status;
  3688. IoCompleteRequest(Irp, IO_NO_INCREMENT);
  3689. return status;
  3690. }
  3691. if (commonExtension->IsFdo){
  3692. PULONG_PTR function;
  3693. srb = ExAllocatePoolWithTag(NonPagedPool,
  3694. sizeof(SCSI_REQUEST_BLOCK) +
  3695. (sizeof(ULONG_PTR) * 2),
  3696. '9CcS');
  3697. if (srb == NULL) {
  3698. Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
  3699. ClassReleaseRemoveLock(DeviceObject, Irp);
  3700. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3701. status = STATUS_INSUFFICIENT_RESOURCES;
  3702. goto SetStatusAndReturn;
  3703. }
  3704. RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK));
  3705. cdb = (PCDB)srb->Cdb;
  3706. //
  3707. // Save the function code and the device object in the memory after
  3708. // the SRB.
  3709. //
  3710. function = (PULONG_PTR) ((PSCSI_REQUEST_BLOCK) (srb + 1));
  3711. *function = (ULONG_PTR) DeviceObject;
  3712. function++;
  3713. *function = (ULONG_PTR) controlCode;
  3714. } else {
  3715. srb = NULL;
  3716. }
  3717. //
  3718. // Change the device type to storage for the switch statement, but only
  3719. // if from a legacy device type
  3720. //
  3721. if (((controlCode & 0xffff0000) == (IOCTL_DISK_BASE << 16)) ||
  3722. ((controlCode & 0xffff0000) == (IOCTL_TAPE_BASE << 16)) ||
  3723. ((controlCode & 0xffff0000) == (IOCTL_CDROM_BASE << 16))
  3724. ) {
  3725. modifiedIoControlCode = (controlCode & ~0xffff0000);
  3726. modifiedIoControlCode |= (IOCTL_STORAGE_BASE << 16);
  3727. } else {
  3728. modifiedIoControlCode = controlCode;
  3729. }
  3730. DBGTRACE(ClassDebugTrace, ("> ioctl %xh (%s)", modifiedIoControlCode, DBGGETIOCTLSTR(modifiedIoControlCode)));
  3731. switch (modifiedIoControlCode) {
  3732. case IOCTL_STORAGE_GET_HOTPLUG_INFO: {
  3733. if (srb) {
  3734. ExFreePool(srb);
  3735. srb = NULL;
  3736. }
  3737. if(irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3738. sizeof(STORAGE_HOTPLUG_INFO)) {
  3739. //
  3740. // Indicate unsuccessful status and no data transferred.
  3741. //
  3742. Irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL;
  3743. Irp->IoStatus.Information = sizeof(STORAGE_HOTPLUG_INFO);
  3744. ClassReleaseRemoveLock(DeviceObject, Irp);
  3745. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3746. status = STATUS_BUFFER_TOO_SMALL;
  3747. } else if(!commonExtension->IsFdo) {
  3748. //
  3749. // Just forward this down and return
  3750. //
  3751. IoCopyCurrentIrpStackLocationToNext(Irp);
  3752. ClassReleaseRemoveLock(DeviceObject, Irp);
  3753. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  3754. } else {
  3755. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
  3756. PSTORAGE_HOTPLUG_INFO info;
  3757. fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)commonExtension;
  3758. info = Irp->AssociatedIrp.SystemBuffer;
  3759. *info = fdoExtension->PrivateFdoData->HotplugInfo;
  3760. Irp->IoStatus.Status = STATUS_SUCCESS;
  3761. Irp->IoStatus.Information = sizeof(STORAGE_HOTPLUG_INFO);
  3762. ClassReleaseRemoveLock(DeviceObject, Irp);
  3763. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3764. status = STATUS_SUCCESS;
  3765. }
  3766. break;
  3767. }
  3768. case IOCTL_STORAGE_SET_HOTPLUG_INFO: {
  3769. if (srb)
  3770. {
  3771. ExFreePool(srb);
  3772. srb = NULL;
  3773. }
  3774. if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
  3775. sizeof(STORAGE_HOTPLUG_INFO)) {
  3776. //
  3777. // Indicate unsuccessful status and no data transferred.
  3778. //
  3779. Irp->IoStatus.Status = STATUS_INFO_LENGTH_MISMATCH;
  3780. ClassReleaseRemoveLock(DeviceObject, Irp);
  3781. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3782. status = STATUS_INFO_LENGTH_MISMATCH;
  3783. goto SetStatusAndReturn;
  3784. }
  3785. if(!commonExtension->IsFdo) {
  3786. //
  3787. // Just forward this down and return
  3788. //
  3789. IoCopyCurrentIrpStackLocationToNext(Irp);
  3790. ClassReleaseRemoveLock(DeviceObject, Irp);
  3791. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  3792. } else {
  3793. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)commonExtension;
  3794. PSTORAGE_HOTPLUG_INFO info = Irp->AssociatedIrp.SystemBuffer;
  3795. status = STATUS_SUCCESS;
  3796. if (info->Size != fdoExtension->PrivateFdoData->HotplugInfo.Size)
  3797. {
  3798. status = STATUS_INVALID_PARAMETER_1;
  3799. }
  3800. if (info->MediaRemovable != fdoExtension->PrivateFdoData->HotplugInfo.MediaRemovable)
  3801. {
  3802. status = STATUS_INVALID_PARAMETER_2;
  3803. }
  3804. if (info->MediaHotplug != fdoExtension->PrivateFdoData->HotplugInfo.MediaHotplug)
  3805. {
  3806. status = STATUS_INVALID_PARAMETER_3;
  3807. }
  3808. if (info->WriteCacheEnableOverride != fdoExtension->PrivateFdoData->HotplugInfo.WriteCacheEnableOverride)
  3809. {
  3810. status = STATUS_INVALID_PARAMETER_5;
  3811. }
  3812. if (NT_SUCCESS(status))
  3813. {
  3814. fdoExtension->PrivateFdoData->HotplugInfo.DeviceHotplug = info->DeviceHotplug;
  3815. //
  3816. // Store the user-defined override in the registry
  3817. //
  3818. ClassSetDeviceParameter(fdoExtension,
  3819. CLASSP_REG_SUBKEY_NAME,
  3820. CLASSP_REG_REMOVAL_POLICY_VALUE_NAME,
  3821. (info->DeviceHotplug) ? RemovalPolicyExpectSurpriseRemoval : RemovalPolicyExpectOrderlyRemoval);
  3822. }
  3823. Irp->IoStatus.Status = status;
  3824. ClassReleaseRemoveLock(DeviceObject, Irp);
  3825. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3826. }
  3827. break;
  3828. }
  3829. case IOCTL_STORAGE_CHECK_VERIFY:
  3830. case IOCTL_STORAGE_CHECK_VERIFY2: {
  3831. PIRP irp2 = NULL;
  3832. PIO_STACK_LOCATION newStack;
  3833. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = NULL;
  3834. DebugPrint((1,"DeviceIoControl: Check verify\n"));
  3835. //
  3836. // If a buffer for a media change count was provided, make sure it's
  3837. // big enough to hold the result
  3838. //
  3839. if(irpStack->Parameters.DeviceIoControl.OutputBufferLength) {
  3840. //
  3841. // If the buffer is too small to hold the media change count
  3842. // then return an error to the caller
  3843. //
  3844. if(irpStack->Parameters.DeviceIoControl.OutputBufferLength <
  3845. sizeof(ULONG)) {
  3846. DebugPrint((3,"DeviceIoControl: media count "
  3847. "buffer too small\n"));
  3848. Irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL;
  3849. Irp->IoStatus.Information = sizeof(ULONG);
  3850. if(srb != NULL) {
  3851. ExFreePool(srb);
  3852. }
  3853. ClassReleaseRemoveLock(DeviceObject, Irp);
  3854. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3855. status = STATUS_BUFFER_TOO_SMALL;
  3856. goto SetStatusAndReturn;
  3857. }
  3858. }
  3859. if(!commonExtension->IsFdo) {
  3860. //
  3861. // If this is a PDO then we should just forward the request down
  3862. //
  3863. ASSERT(!srb);
  3864. IoCopyCurrentIrpStackLocationToNext(Irp);
  3865. ClassReleaseRemoveLock(DeviceObject, Irp);
  3866. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  3867. goto SetStatusAndReturn;
  3868. } else {
  3869. fdoExtension = DeviceObject->DeviceExtension;
  3870. }
  3871. if(irpStack->Parameters.DeviceIoControl.OutputBufferLength) {
  3872. //
  3873. // The caller has provided a valid buffer. Allocate an additional
  3874. // irp and stick the CheckVerify completion routine on it. We will
  3875. // then send this down to the port driver instead of the irp the
  3876. // caller sent in
  3877. //
  3878. DebugPrint((2,"DeviceIoControl: Check verify wants "
  3879. "media count\n"));
  3880. //
  3881. // Allocate a new irp to send the TestUnitReady to the port driver
  3882. //
  3883. irp2 = IoAllocateIrp((CCHAR) (DeviceObject->StackSize + 3), FALSE);
  3884. if(irp2 == NULL) {
  3885. Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
  3886. Irp->IoStatus.Information = 0;
  3887. ASSERT(srb);
  3888. ExFreePool(srb);
  3889. ClassReleaseRemoveLock(DeviceObject, Irp);
  3890. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3891. status = STATUS_INSUFFICIENT_RESOURCES;
  3892. goto SetStatusAndReturn;
  3893. break;
  3894. }
  3895. //
  3896. // Make sure to acquire the lock for the new irp.
  3897. //
  3898. ClassAcquireRemoveLock(DeviceObject, irp2);
  3899. irp2->Tail.Overlay.Thread = Irp->Tail.Overlay.Thread;
  3900. IoSetNextIrpStackLocation(irp2);
  3901. //
  3902. // Set the top stack location and shove the master Irp into the
  3903. // top location
  3904. //
  3905. newStack = IoGetCurrentIrpStackLocation(irp2);
  3906. newStack->Parameters.Others.Argument1 = Irp;
  3907. newStack->DeviceObject = DeviceObject;
  3908. //
  3909. // Stick the check verify completion routine onto the stack
  3910. // and prepare the irp for the port driver
  3911. //
  3912. IoSetCompletionRoutine(irp2,
  3913. ClassCheckVerifyComplete,
  3914. NULL,
  3915. TRUE,
  3916. TRUE,
  3917. TRUE);
  3918. IoSetNextIrpStackLocation(irp2);
  3919. newStack = IoGetCurrentIrpStackLocation(irp2);
  3920. newStack->DeviceObject = DeviceObject;
  3921. newStack->MajorFunction = irpStack->MajorFunction;
  3922. newStack->MinorFunction = irpStack->MinorFunction;
  3923. //
  3924. // Mark the master irp as pending - whether the lower level
  3925. // driver completes it immediately or not this should allow it
  3926. // to go all the way back up.
  3927. //
  3928. IoMarkIrpPending(Irp);
  3929. Irp = irp2;
  3930. }
  3931. //
  3932. // Test Unit Ready
  3933. //
  3934. srb->CdbLength = 6;
  3935. cdb->CDB6GENERIC.OperationCode = SCSIOP_TEST_UNIT_READY;
  3936. //
  3937. // Set timeout value.
  3938. //
  3939. srb->TimeOutValue = fdoExtension->TimeOutValue;
  3940. //
  3941. // If this was a CV2 then mark the request as low-priority so we don't
  3942. // spin up the drive just to satisfy it.
  3943. //
  3944. if(controlCode == IOCTL_STORAGE_CHECK_VERIFY2) {
  3945. SET_FLAG(srb->SrbFlags, SRB_CLASS_FLAGS_LOW_PRIORITY);
  3946. }
  3947. //
  3948. // Since this routine will always hand the request to the
  3949. // port driver if there isn't a data transfer to be done
  3950. // we don't have to worry about completing the request here
  3951. // on an error
  3952. //
  3953. //
  3954. // This routine uses a completion routine so we don't want to release
  3955. // the remove lock until then.
  3956. //
  3957. status = ClassSendSrbAsynchronous(DeviceObject,
  3958. srb,
  3959. Irp,
  3960. NULL,
  3961. 0,
  3962. FALSE);
  3963. break;
  3964. }
  3965. case IOCTL_STORAGE_MEDIA_REMOVAL:
  3966. case IOCTL_STORAGE_EJECTION_CONTROL: {
  3967. PPREVENT_MEDIA_REMOVAL mediaRemoval = Irp->AssociatedIrp.SystemBuffer;
  3968. DebugPrint((3, "DiskIoControl: ejection control\n"));
  3969. if(srb) {
  3970. ExFreePool(srb);
  3971. }
  3972. if(irpStack->Parameters.DeviceIoControl.InputBufferLength <
  3973. sizeof(PREVENT_MEDIA_REMOVAL)) {
  3974. //
  3975. // Indicate unsuccessful status and no data transferred.
  3976. //
  3977. Irp->IoStatus.Status = STATUS_INFO_LENGTH_MISMATCH;
  3978. ClassReleaseRemoveLock(DeviceObject, Irp);
  3979. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  3980. status = STATUS_INFO_LENGTH_MISMATCH;
  3981. goto SetStatusAndReturn;
  3982. }
  3983. if(!commonExtension->IsFdo) {
  3984. //
  3985. // Just forward this down and return
  3986. //
  3987. IoCopyCurrentIrpStackLocationToNext(Irp);
  3988. ClassReleaseRemoveLock(DeviceObject, Irp);
  3989. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  3990. }
  3991. else {
  3992. // i don't believe this assertion is valid. this is a request
  3993. // from user-mode, so they could request this for any device
  3994. // they want? also, we handle it properly.
  3995. // ASSERT(TEST_FLAG(DeviceObject->Characteristics, FILE_REMOVABLE_MEDIA));
  3996. status = ClasspEjectionControl(
  3997. DeviceObject,
  3998. Irp,
  3999. ((modifiedIoControlCode ==
  4000. IOCTL_STORAGE_EJECTION_CONTROL) ? SecureMediaLock :
  4001. SimpleMediaLock),
  4002. mediaRemoval->PreventMediaRemoval);
  4003. Irp->IoStatus.Status = status;
  4004. ClassReleaseRemoveLock(DeviceObject, Irp);
  4005. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4006. }
  4007. break;
  4008. }
  4009. case IOCTL_STORAGE_MCN_CONTROL: {
  4010. DebugPrint((3, "DiskIoControl: MCN control\n"));
  4011. if(irpStack->Parameters.DeviceIoControl.InputBufferLength <
  4012. sizeof(PREVENT_MEDIA_REMOVAL)) {
  4013. //
  4014. // Indicate unsuccessful status and no data transferred.
  4015. //
  4016. Irp->IoStatus.Status = STATUS_INFO_LENGTH_MISMATCH;
  4017. Irp->IoStatus.Information = 0;
  4018. if(srb) {
  4019. ExFreePool(srb);
  4020. }
  4021. ClassReleaseRemoveLock(DeviceObject, Irp);
  4022. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4023. status = STATUS_INFO_LENGTH_MISMATCH;
  4024. goto SetStatusAndReturn;
  4025. }
  4026. if(!commonExtension->IsFdo) {
  4027. //
  4028. // Just forward this down and return
  4029. //
  4030. if(srb) {
  4031. ExFreePool(srb);
  4032. }
  4033. IoCopyCurrentIrpStackLocationToNext(Irp);
  4034. ClassReleaseRemoveLock(DeviceObject, Irp);
  4035. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  4036. } else {
  4037. //
  4038. // Call to the FDO - handle the ejection control.
  4039. //
  4040. status = ClasspMcnControl(DeviceObject->DeviceExtension,
  4041. Irp,
  4042. srb);
  4043. }
  4044. goto SetStatusAndReturn;
  4045. }
  4046. case IOCTL_STORAGE_RESERVE:
  4047. case IOCTL_STORAGE_RELEASE: {
  4048. //
  4049. // Reserve logical unit.
  4050. //
  4051. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = NULL;
  4052. if(!commonExtension->IsFdo) {
  4053. IoCopyCurrentIrpStackLocationToNext(Irp);
  4054. ClassReleaseRemoveLock(DeviceObject, Irp);
  4055. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  4056. goto SetStatusAndReturn;
  4057. } else {
  4058. fdoExtension = DeviceObject->DeviceExtension;
  4059. }
  4060. srb->CdbLength = 6;
  4061. if(modifiedIoControlCode == IOCTL_STORAGE_RESERVE) {
  4062. cdb->CDB6GENERIC.OperationCode = SCSIOP_RESERVE_UNIT;
  4063. } else {
  4064. cdb->CDB6GENERIC.OperationCode = SCSIOP_RELEASE_UNIT;
  4065. }
  4066. //
  4067. // Set timeout value.
  4068. //
  4069. srb->TimeOutValue = fdoExtension->TimeOutValue;
  4070. status = ClassSendSrbAsynchronous(DeviceObject,
  4071. srb,
  4072. Irp,
  4073. NULL,
  4074. 0,
  4075. FALSE);
  4076. break;
  4077. }
  4078. case IOCTL_STORAGE_EJECT_MEDIA:
  4079. case IOCTL_STORAGE_LOAD_MEDIA:
  4080. case IOCTL_STORAGE_LOAD_MEDIA2:{
  4081. //
  4082. // Eject media.
  4083. //
  4084. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = NULL;
  4085. if(!commonExtension->IsFdo) {
  4086. IoCopyCurrentIrpStackLocationToNext(Irp);
  4087. ClassReleaseRemoveLock(DeviceObject, Irp);
  4088. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  4089. goto SetStatusAndReturn;
  4090. } else {
  4091. fdoExtension = DeviceObject->DeviceExtension;
  4092. }
  4093. if(commonExtension->PagingPathCount != 0) {
  4094. DebugPrint((1, "ClassDeviceControl: call to eject paging device - "
  4095. "failure\n"));
  4096. status = STATUS_FILES_OPEN;
  4097. Irp->IoStatus.Status = status;
  4098. Irp->IoStatus.Information = 0;
  4099. if(srb) {
  4100. ExFreePool(srb);
  4101. }
  4102. ClassReleaseRemoveLock(DeviceObject, Irp);
  4103. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4104. goto SetStatusAndReturn;
  4105. }
  4106. //
  4107. // Synchronize with ejection control and ejection cleanup code as
  4108. // well as other eject/load requests.
  4109. //
  4110. KeEnterCriticalRegion();
  4111. KeWaitForSingleObject(&(fdoExtension->EjectSynchronizationEvent),
  4112. UserRequest,
  4113. UserMode,
  4114. FALSE,
  4115. NULL);
  4116. if(fdoExtension->ProtectedLockCount != 0) {
  4117. DebugPrint((1, "ClassDeviceControl: call to eject protected locked "
  4118. "device - failure\n"));
  4119. status = STATUS_DEVICE_BUSY;
  4120. Irp->IoStatus.Status = status;
  4121. Irp->IoStatus.Information = 0;
  4122. if(srb) {
  4123. ExFreePool(srb);
  4124. }
  4125. ClassReleaseRemoveLock(DeviceObject, Irp);
  4126. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4127. KeSetEvent(&fdoExtension->EjectSynchronizationEvent,
  4128. IO_NO_INCREMENT,
  4129. FALSE);
  4130. KeLeaveCriticalRegion();
  4131. goto SetStatusAndReturn;
  4132. }
  4133. srb->CdbLength = 6;
  4134. cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
  4135. cdb->START_STOP.LoadEject = 1;
  4136. if(modifiedIoControlCode == IOCTL_STORAGE_EJECT_MEDIA) {
  4137. cdb->START_STOP.Start = 0;
  4138. } else {
  4139. cdb->START_STOP.Start = 1;
  4140. }
  4141. //
  4142. // Set timeout value.
  4143. //
  4144. srb->TimeOutValue = fdoExtension->TimeOutValue;
  4145. status = ClassSendSrbAsynchronous(DeviceObject,
  4146. srb,
  4147. Irp,
  4148. NULL,
  4149. 0,
  4150. FALSE);
  4151. KeSetEvent(&fdoExtension->EjectSynchronizationEvent, IO_NO_INCREMENT, FALSE);
  4152. KeLeaveCriticalRegion();
  4153. break;
  4154. }
  4155. case IOCTL_STORAGE_FIND_NEW_DEVICES: {
  4156. if(srb) {
  4157. ExFreePool(srb);
  4158. }
  4159. if(commonExtension->IsFdo) {
  4160. IoInvalidateDeviceRelations(
  4161. ((PFUNCTIONAL_DEVICE_EXTENSION) commonExtension)->LowerPdo,
  4162. BusRelations);
  4163. status = STATUS_SUCCESS;
  4164. Irp->IoStatus.Status = status;
  4165. ClassReleaseRemoveLock(DeviceObject, Irp);
  4166. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4167. }
  4168. else {
  4169. IoCopyCurrentIrpStackLocationToNext(Irp);
  4170. ClassReleaseRemoveLock(DeviceObject, Irp);
  4171. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  4172. }
  4173. break;
  4174. }
  4175. case IOCTL_STORAGE_GET_DEVICE_NUMBER: {
  4176. if(srb) {
  4177. ExFreePool(srb);
  4178. }
  4179. if(irpStack->Parameters.DeviceIoControl.OutputBufferLength >=
  4180. sizeof(STORAGE_DEVICE_NUMBER)) {
  4181. PSTORAGE_DEVICE_NUMBER deviceNumber =
  4182. Irp->AssociatedIrp.SystemBuffer;
  4183. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension =
  4184. commonExtension->PartitionZeroExtension;
  4185. deviceNumber->DeviceType = fdoExtension->CommonExtension.DeviceObject->DeviceType;
  4186. deviceNumber->DeviceNumber = fdoExtension->DeviceNumber;
  4187. deviceNumber->PartitionNumber = commonExtension->PartitionNumber;
  4188. status = STATUS_SUCCESS;
  4189. Irp->IoStatus.Information = sizeof(STORAGE_DEVICE_NUMBER);
  4190. } else {
  4191. status = STATUS_BUFFER_TOO_SMALL;
  4192. Irp->IoStatus.Information = sizeof(STORAGE_DEVICE_NUMBER);
  4193. }
  4194. Irp->IoStatus.Status = status;
  4195. ClassReleaseRemoveLock(DeviceObject, Irp);
  4196. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4197. break;
  4198. }
  4199. default: {
  4200. DebugPrint((4, "IoDeviceControl: Unsupported device IOCTL %x for %p\n",
  4201. controlCode, DeviceObject));
  4202. //
  4203. // Pass the device control to the next driver.
  4204. //
  4205. if(srb) {
  4206. ExFreePool(srb);
  4207. }
  4208. //
  4209. // Copy the Irp stack parameters to the next stack location.
  4210. //
  4211. IoCopyCurrentIrpStackLocationToNext(Irp);
  4212. ClassReleaseRemoveLock(DeviceObject, Irp);
  4213. status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  4214. break;
  4215. }
  4216. } // end switch( ...
  4217. SetStatusAndReturn:
  4218. DBGTRACE(ClassDebugTrace, ("< ioctl %xh (%s): status %xh.", modifiedIoControlCode, DBGGETIOCTLSTR(modifiedIoControlCode), status));
  4219. return status;
  4220. } // end ClassDeviceControl()
  4221. /*++////////////////////////////////////////////////////////////////////////////
  4222. ClassShutdownFlush()
  4223. Routine Description:
  4224. This routine is called for a shutdown and flush IRPs. These are sent by the
  4225. system before it actually shuts down or when the file system does a flush.
  4226. If it exists, the device-specific driver's routine will be invoked. If there
  4227. wasn't one specified, the Irp will be completed with an Invalid device request.
  4228. Arguments:
  4229. DriverObject - Pointer to device object to being shutdown by system.
  4230. Irp - IRP involved.
  4231. Return Value:
  4232. NT Status
  4233. --*/
  4234. NTSTATUS
  4235. ClassShutdownFlush(
  4236. IN PDEVICE_OBJECT DeviceObject,
  4237. IN PIRP Irp
  4238. )
  4239. {
  4240. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  4241. ULONG isRemoved;
  4242. NTSTATUS status;
  4243. isRemoved = ClassAcquireRemoveLock(DeviceObject, Irp);
  4244. if(isRemoved) {
  4245. ClassReleaseRemoveLock(DeviceObject, Irp);
  4246. Irp->IoStatus.Status = STATUS_DEVICE_DOES_NOT_EXIST;
  4247. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4248. return STATUS_DEVICE_DOES_NOT_EXIST;
  4249. }
  4250. if (commonExtension->DevInfo->ClassShutdownFlush) {
  4251. //
  4252. // Call the device-specific driver's routine.
  4253. //
  4254. return commonExtension->DevInfo->ClassShutdownFlush(DeviceObject, Irp);
  4255. }
  4256. //
  4257. // Device-specific driver doesn't support this.
  4258. //
  4259. Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
  4260. ClassReleaseRemoveLock(DeviceObject, Irp);
  4261. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4262. return STATUS_INVALID_DEVICE_REQUEST;
  4263. } // end ClassShutdownFlush()
  4264. /*++////////////////////////////////////////////////////////////////////////////
  4265. ClassCreateDeviceObject()
  4266. Routine Description:
  4267. This routine creates an object for the physical device specified and
  4268. sets up the deviceExtension's function pointers for each entry point
  4269. in the device-specific driver.
  4270. Arguments:
  4271. DriverObject - Pointer to driver object created by system.
  4272. ObjectNameBuffer - Dir. name of the object to create.
  4273. LowerDeviceObject - Pointer to the lower device object
  4274. IsFdo - should this be an fdo or a pdo
  4275. DeviceObject - Pointer to the device object pointer we will return.
  4276. Return Value:
  4277. NTSTATUS
  4278. --*/
  4279. NTSTATUS
  4280. ClassCreateDeviceObject(
  4281. IN PDRIVER_OBJECT DriverObject,
  4282. IN PCCHAR ObjectNameBuffer,
  4283. IN PDEVICE_OBJECT LowerDevice,
  4284. IN BOOLEAN IsFdo,
  4285. IN OUT PDEVICE_OBJECT *DeviceObject
  4286. )
  4287. {
  4288. BOOLEAN isPartitionable;
  4289. STRING ntNameString;
  4290. UNICODE_STRING ntUnicodeString;
  4291. NTSTATUS status, status2;
  4292. PDEVICE_OBJECT deviceObject = NULL;
  4293. ULONG characteristics;
  4294. PCLASS_DRIVER_EXTENSION
  4295. driverExtension = IoGetDriverObjectExtension(DriverObject,
  4296. CLASS_DRIVER_EXTENSION_KEY);
  4297. PCLASS_DEV_INFO devInfo;
  4298. PAGED_CODE();
  4299. *DeviceObject = NULL;
  4300. RtlInitUnicodeString(&ntUnicodeString, NULL);
  4301. DebugPrint((2, "ClassCreateFdo: Create device object\n"));
  4302. ASSERT(LowerDevice);
  4303. //
  4304. // Make sure that if we're making PDO's we have an enumeration routine
  4305. //
  4306. isPartitionable = (driverExtension->InitData.ClassEnumerateDevice != NULL);
  4307. ASSERT(IsFdo || isPartitionable);
  4308. //
  4309. // Grab the correct dev-info structure out of the init data
  4310. //
  4311. if(IsFdo) {
  4312. devInfo = &(driverExtension->InitData.FdoData);
  4313. } else {
  4314. devInfo = &(driverExtension->InitData.PdoData);
  4315. }
  4316. characteristics = devInfo->DeviceCharacteristics;
  4317. if(ARGUMENT_PRESENT(ObjectNameBuffer)) {
  4318. DebugPrint((2, "ClassCreateFdo: Name is %s\n", ObjectNameBuffer));
  4319. RtlInitString(&ntNameString, ObjectNameBuffer);
  4320. status = RtlAnsiStringToUnicodeString(&ntUnicodeString, &ntNameString, TRUE);
  4321. if (!NT_SUCCESS(status)) {
  4322. DebugPrint((1,
  4323. "ClassCreateFdo: Cannot convert string %s\n",
  4324. ObjectNameBuffer));
  4325. ntUnicodeString.Buffer = NULL;
  4326. return status;
  4327. }
  4328. } else {
  4329. DebugPrint((2, "ClassCreateFdo: Object will be unnamed\n"));
  4330. if(IsFdo == FALSE) {
  4331. //
  4332. // PDO's have to have some sort of name.
  4333. //
  4334. SET_FLAG(characteristics, FILE_AUTOGENERATED_DEVICE_NAME);
  4335. }
  4336. RtlInitUnicodeString(&ntUnicodeString, NULL);
  4337. }
  4338. status = IoCreateDevice(DriverObject,
  4339. devInfo->DeviceExtensionSize,
  4340. &ntUnicodeString,
  4341. devInfo->DeviceType,
  4342. devInfo->DeviceCharacteristics,
  4343. FALSE,
  4344. &deviceObject);
  4345. if (!NT_SUCCESS(status)) {
  4346. DebugPrint((1, "ClassCreateFdo: Can not create device object %lx\n",
  4347. status));
  4348. ASSERT(deviceObject == NULL);
  4349. //
  4350. // buffer is not used any longer here.
  4351. //
  4352. if (ntUnicodeString.Buffer != NULL) {
  4353. DebugPrint((1, "ClassCreateFdo: Freeing unicode name buffer\n"));
  4354. ExFreePool(ntUnicodeString.Buffer);
  4355. RtlInitUnicodeString(&ntUnicodeString, NULL);
  4356. }
  4357. } else {
  4358. PCOMMON_DEVICE_EXTENSION commonExtension = deviceObject->DeviceExtension;
  4359. RtlZeroMemory(
  4360. deviceObject->DeviceExtension,
  4361. devInfo->DeviceExtensionSize);
  4362. //
  4363. // Setup version code
  4364. //
  4365. commonExtension->Version = 0x03;
  4366. //
  4367. // Setup the remove lock and event
  4368. //
  4369. commonExtension->IsRemoved = NO_REMOVE;
  4370. commonExtension->RemoveLock = 0;
  4371. KeInitializeEvent(&commonExtension->RemoveEvent,
  4372. SynchronizationEvent,
  4373. FALSE);
  4374. #if DBG
  4375. KeInitializeSpinLock(&commonExtension->RemoveTrackingSpinlock);
  4376. commonExtension->RemoveTrackingList = NULL;
  4377. #else
  4378. commonExtension->RemoveTrackingSpinlock = (ULONG_PTR) -1;
  4379. commonExtension->RemoveTrackingList = (PVOID) -1;
  4380. #endif
  4381. //
  4382. // Acquire the lock once. This reference will be released when the
  4383. // remove IRP has been received.
  4384. //
  4385. ClassAcquireRemoveLock(deviceObject, (PIRP) deviceObject);
  4386. //
  4387. // Store a pointer to the driver extension so we don't have to do
  4388. // lookups to get it.
  4389. //
  4390. commonExtension->DriverExtension = driverExtension;
  4391. //
  4392. // Fill in entry points
  4393. //
  4394. commonExtension->DevInfo = devInfo;
  4395. //
  4396. // Initialize some of the common values in the structure
  4397. //
  4398. commonExtension->DeviceObject = deviceObject;
  4399. commonExtension->LowerDeviceObject = NULL;
  4400. if(IsFdo) {
  4401. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PVOID) commonExtension;
  4402. commonExtension->PartitionZeroExtension = deviceObject->DeviceExtension;
  4403. //
  4404. // Set the initial device object flags.
  4405. //
  4406. SET_FLAG(deviceObject->Flags, DO_POWER_PAGABLE);
  4407. //
  4408. // Clear the PDO list
  4409. //
  4410. commonExtension->ChildList = NULL;
  4411. commonExtension->DriverData =
  4412. ((PFUNCTIONAL_DEVICE_EXTENSION) deviceObject->DeviceExtension + 1);
  4413. if(isPartitionable) {
  4414. commonExtension->PartitionNumber = 0;
  4415. } else {
  4416. commonExtension->PartitionNumber = (ULONG) (-1L);
  4417. }
  4418. fdoExtension->DevicePowerState = PowerDeviceD0;
  4419. KeInitializeEvent(&fdoExtension->EjectSynchronizationEvent,
  4420. SynchronizationEvent,
  4421. TRUE);
  4422. KeInitializeEvent(&fdoExtension->ChildLock,
  4423. SynchronizationEvent,
  4424. TRUE);
  4425. status = ClasspAllocateReleaseRequest(deviceObject);
  4426. if(!NT_SUCCESS(status)) {
  4427. IoDeleteDevice(deviceObject);
  4428. *DeviceObject = NULL;
  4429. if (ntUnicodeString.Buffer != NULL) {
  4430. DebugPrint((1, "ClassCreateFdo: Freeing unicode name buffer\n"));
  4431. ExFreePool(ntUnicodeString.Buffer);
  4432. RtlInitUnicodeString(&ntUnicodeString, NULL);
  4433. }
  4434. return status;
  4435. }
  4436. } else {
  4437. PPHYSICAL_DEVICE_EXTENSION pdoExtension =
  4438. deviceObject->DeviceExtension;
  4439. PFUNCTIONAL_DEVICE_EXTENSION p0Extension =
  4440. LowerDevice->DeviceExtension;
  4441. SET_FLAG(deviceObject->Flags, DO_POWER_PAGABLE);
  4442. commonExtension->PartitionZeroExtension = p0Extension;
  4443. //
  4444. // Stick this onto the PDO list
  4445. //
  4446. ClassAddChild(p0Extension, pdoExtension, TRUE);
  4447. commonExtension->DriverData = (PVOID) (pdoExtension + 1);
  4448. //
  4449. // Get the top of stack for the lower device - this allows
  4450. // filters to get stuck in between the partitions and the
  4451. // physical disk.
  4452. //
  4453. commonExtension->LowerDeviceObject =
  4454. IoGetAttachedDeviceReference(LowerDevice);
  4455. //
  4456. // Pnp will keep a reference to the lower device object long
  4457. // after this partition has been deleted. Dereference now so
  4458. // we don't have to deal with it later.
  4459. //
  4460. ObDereferenceObject(commonExtension->LowerDeviceObject);
  4461. }
  4462. KeInitializeEvent(&commonExtension->PathCountEvent, SynchronizationEvent, TRUE);
  4463. commonExtension->IsFdo = IsFdo;
  4464. commonExtension->DeviceName = ntUnicodeString;
  4465. commonExtension->PreviousState = 0xff;
  4466. InitializeDictionary(&(commonExtension->FileObjectDictionary));
  4467. commonExtension->CurrentState = IRP_MN_STOP_DEVICE;
  4468. }
  4469. *DeviceObject = deviceObject;
  4470. return status;
  4471. } // end ClassCreateDeviceObject()
  4472. /*++////////////////////////////////////////////////////////////////////////////
  4473. ClassClaimDevice()
  4474. Routine Description:
  4475. This function claims a device in the port driver. The port driver object
  4476. is updated with the correct driver object if the device is successfully
  4477. claimed.
  4478. Arguments:
  4479. LowerDeviceObject - Supplies the base port device object.
  4480. Release - Indicates the logical unit should be released rather than claimed.
  4481. Return Value:
  4482. Returns a status indicating success or failure of the operation.
  4483. --*/
  4484. NTSTATUS
  4485. ClassClaimDevice(
  4486. IN PDEVICE_OBJECT LowerDeviceObject,
  4487. IN BOOLEAN Release
  4488. )
  4489. {
  4490. IO_STATUS_BLOCK ioStatus;
  4491. PIRP irp;
  4492. PIO_STACK_LOCATION irpStack;
  4493. KEVENT event;
  4494. NTSTATUS status;
  4495. SCSI_REQUEST_BLOCK srb;
  4496. PAGED_CODE();
  4497. //
  4498. // Clear the SRB fields.
  4499. //
  4500. RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK));
  4501. //
  4502. // Write length to SRB.
  4503. //
  4504. srb.Length = sizeof(SCSI_REQUEST_BLOCK);
  4505. srb.Function = Release ? SRB_FUNCTION_RELEASE_DEVICE :
  4506. SRB_FUNCTION_CLAIM_DEVICE;
  4507. //
  4508. // Set the event object to the unsignaled state.
  4509. // It will be used to signal request completion
  4510. //
  4511. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  4512. //
  4513. // Build synchronous request with no transfer.
  4514. //
  4515. irp = IoBuildDeviceIoControlRequest(IOCTL_SCSI_EXECUTE_NONE,
  4516. LowerDeviceObject,
  4517. NULL,
  4518. 0,
  4519. NULL,
  4520. 0,
  4521. TRUE,
  4522. &event,
  4523. &ioStatus);
  4524. if (irp == NULL) {
  4525. DebugPrint((1, "ClassClaimDevice: Can't allocate Irp\n"));
  4526. return STATUS_INSUFFICIENT_RESOURCES;
  4527. }
  4528. irpStack = IoGetNextIrpStackLocation(irp);
  4529. //
  4530. // Save SRB address in next stack for port driver.
  4531. //
  4532. irpStack->Parameters.Scsi.Srb = &srb;
  4533. //
  4534. // Set up IRP Address.
  4535. //
  4536. srb.OriginalRequest = irp;
  4537. //
  4538. // Call the port driver with the request and wait for it to complete.
  4539. //
  4540. status = IoCallDriver(LowerDeviceObject, irp);
  4541. if (status == STATUS_PENDING) {
  4542. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  4543. status = ioStatus.Status;
  4544. }
  4545. //
  4546. // If this is a release request, then just decrement the reference count
  4547. // and return. The status does not matter.
  4548. //
  4549. if (Release) {
  4550. // ObDereferenceObject(LowerDeviceObject);
  4551. return STATUS_SUCCESS;
  4552. }
  4553. if (!NT_SUCCESS(status)) {
  4554. return status;
  4555. }
  4556. ASSERT(srb.DataBuffer != NULL);
  4557. ASSERT(!TEST_FLAG(srb.SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
  4558. return status;
  4559. } // end ClassClaimDevice()
  4560. /*++////////////////////////////////////////////////////////////////////////////
  4561. ClassInternalIoControl()
  4562. Routine Description:
  4563. This routine passes internal device controls to the port driver.
  4564. Internal device controls are used by higher level drivers both for ioctls
  4565. and to pass through scsi requests.
  4566. If the IoControlCode does not match any of the handled ioctls and is
  4567. a valid system address then the request will be treated as an SRB and
  4568. passed down to the lower driver. If the IoControlCode is not a valid
  4569. system address the ioctl will be failed.
  4570. Callers must therefore be extremely cautious to pass correct, initialized
  4571. values to this function.
  4572. Arguments:
  4573. DeviceObject - Supplies a pointer to the device object for this request.
  4574. Irp - Supplies the Irp making the request.
  4575. Return Value:
  4576. Returns back a STATUS_PENDING or a completion status.
  4577. --*/
  4578. NTSTATUS
  4579. ClassInternalIoControl(
  4580. IN PDEVICE_OBJECT DeviceObject,
  4581. IN PIRP Irp
  4582. )
  4583. {
  4584. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  4585. PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
  4586. PIO_STACK_LOCATION nextStack = IoGetNextIrpStackLocation(Irp);
  4587. ULONG isRemoved;
  4588. PSCSI_REQUEST_BLOCK srb;
  4589. isRemoved = ClassAcquireRemoveLock(DeviceObject, Irp);
  4590. if(isRemoved) {
  4591. Irp->IoStatus.Status = STATUS_DEVICE_DOES_NOT_EXIST;
  4592. ClassReleaseRemoveLock(DeviceObject, Irp);
  4593. ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
  4594. return STATUS_DEVICE_DOES_NOT_EXIST;
  4595. }
  4596. //
  4597. // Get a pointer to the SRB.
  4598. //
  4599. srb = irpStack->Parameters.Scsi.Srb;
  4600. //
  4601. // Set the parameters in the next stack location.
  4602. //
  4603. if(commonExtension->IsFdo) {
  4604. nextStack->Parameters.Scsi.Srb = srb;
  4605. nextStack->MajorFunction = IRP_MJ_SCSI;
  4606. nextStack->MinorFunction = IRP_MN_SCSI_CLASS;
  4607. } else {
  4608. IoCopyCurrentIrpStackLocationToNext(Irp);
  4609. }
  4610. ClassReleaseRemoveLock(DeviceObject, Irp);
  4611. return IoCallDriver(commonExtension->LowerDeviceObject, Irp);
  4612. } // end ClassInternalIoControl()
  4613. /*++////////////////////////////////////////////////////////////////////////////
  4614. ClassQueryTimeOutRegistryValue()
  4615. Routine Description:
  4616. This routine determines whether a reg key for a user-specified timeout
  4617. value exists. This should be called at initialization time.
  4618. Arguments:
  4619. DeviceObject - Pointer to the device object we are retrieving the timeout
  4620. value for
  4621. Return Value:
  4622. None, but it sets a new default timeout for a class of devices.
  4623. --*/
  4624. ULONG
  4625. ClassQueryTimeOutRegistryValue(
  4626. IN PDEVICE_OBJECT DeviceObject
  4627. )
  4628. {
  4629. //
  4630. // Find the appropriate reg. key
  4631. //
  4632. PCLASS_DRIVER_EXTENSION
  4633. driverExtension = IoGetDriverObjectExtension(DeviceObject->DriverObject,
  4634. CLASS_DRIVER_EXTENSION_KEY);
  4635. PUNICODE_STRING registryPath = &(driverExtension->RegistryPath);
  4636. PRTL_QUERY_REGISTRY_TABLE parameters = NULL;
  4637. PWSTR path;
  4638. NTSTATUS status;
  4639. LONG timeOut = 0;
  4640. ULONG zero = 0;
  4641. ULONG size;
  4642. PAGED_CODE();
  4643. if (!registryPath) {
  4644. return 0;
  4645. }
  4646. parameters = ExAllocatePoolWithTag(NonPagedPool,
  4647. sizeof(RTL_QUERY_REGISTRY_TABLE)*2,
  4648. '1BcS');
  4649. if (!parameters) {
  4650. return 0;
  4651. }
  4652. size = registryPath->MaximumLength + sizeof(WCHAR);
  4653. path = ExAllocatePoolWithTag(NonPagedPool, size, '2BcS');
  4654. if (!path) {
  4655. ExFreePool(parameters);
  4656. return 0;
  4657. }
  4658. RtlZeroMemory(path,size);
  4659. RtlCopyMemory(path, registryPath->Buffer, size - sizeof(WCHAR));
  4660. //
  4661. // Check for the Timeout value.
  4662. //
  4663. RtlZeroMemory(parameters,
  4664. (sizeof(RTL_QUERY_REGISTRY_TABLE)*2));
  4665. parameters[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
  4666. parameters[0].Name = L"TimeOutValue";
  4667. parameters[0].EntryContext = &timeOut;
  4668. parameters[0].DefaultType = REG_DWORD;
  4669. parameters[0].DefaultData = &zero;
  4670. parameters[0].DefaultLength = sizeof(ULONG);
  4671. status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE | RTL_REGISTRY_OPTIONAL,
  4672. path,
  4673. parameters,
  4674. NULL,
  4675. NULL);
  4676. if (!(NT_SUCCESS(status))) {
  4677. timeOut = 0;
  4678. }
  4679. ExFreePool(parameters);
  4680. ExFreePool(path);
  4681. DebugPrint((2,
  4682. "ClassQueryTimeOutRegistryValue: Timeout value %d\n",
  4683. timeOut));
  4684. return timeOut;
  4685. } // end ClassQueryTimeOutRegistryValue()
  4686. /*++////////////////////////////////////////////////////////////////////////////
  4687. ClassCheckVerifyComplete() ISSUE-2000/02/18-henrygab - why public?!
  4688. Routine Description:
  4689. This routine executes when the port driver has completed a check verify
  4690. ioctl. It will set the status of the master Irp, copy the media change
  4691. count and complete the request.
  4692. Arguments:
  4693. Fdo - Supplies the functional device object which represents the logical unit.
  4694. Irp - Supplies the Irp which has completed.
  4695. Context - NULL
  4696. Return Value:
  4697. NT status
  4698. --*/
  4699. NTSTATUS
  4700. ClassCheckVerifyComplete(
  4701. IN PDEVICE_OBJECT Fdo,
  4702. IN PIRP Irp,
  4703. IN PVOID Context
  4704. )
  4705. {
  4706. PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
  4707. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  4708. PIRP originalIrp;
  4709. ASSERT_FDO(Fdo);
  4710. originalIrp = irpStack->Parameters.Others.Argument1;
  4711. //
  4712. // Copy the media change count and status
  4713. //
  4714. *((PULONG) (originalIrp->AssociatedIrp.SystemBuffer)) =
  4715. fdoExtension->MediaChangeCount;
  4716. DebugPrint((2, "ClassCheckVerifyComplete - Media change count for"
  4717. "device %d is %lx - saved as %lx\n",
  4718. fdoExtension->DeviceNumber,
  4719. fdoExtension->MediaChangeCount,
  4720. *((PULONG) originalIrp->AssociatedIrp.SystemBuffer)));
  4721. originalIrp->IoStatus.Status = Irp->IoStatus.Status;
  4722. originalIrp->IoStatus.Information = sizeof(ULONG);
  4723. ClassReleaseRemoveLock(Fdo, originalIrp);
  4724. ClassCompleteRequest(Fdo, originalIrp, IO_DISK_INCREMENT);
  4725. IoFreeIrp(Irp);
  4726. return STATUS_MORE_PROCESSING_REQUIRED;
  4727. } // end ClassCheckVerifyComplete()
  4728. /*++////////////////////////////////////////////////////////////////////////////
  4729. ClassGetDescriptor()
  4730. Routine Description:
  4731. This routine will perform a query for the specified property id and will
  4732. allocate a non-paged buffer to store the data in. It is the responsibility
  4733. of the caller to ensure that this buffer is freed.
  4734. This routine must be run at IRQL_PASSIVE_LEVEL
  4735. Arguments:
  4736. DeviceObject - the device to query
  4737. DeviceInfo - a location to store a pointer to the buffer we allocate
  4738. Return Value:
  4739. status
  4740. if status is unsuccessful *DeviceInfo will be set to NULL, else the
  4741. buffer allocated on behalf of the caller.
  4742. --*/
  4743. NTSTATUS
  4744. ClassGetDescriptor(
  4745. IN PDEVICE_OBJECT DeviceObject,
  4746. IN PSTORAGE_PROPERTY_ID PropertyId,
  4747. OUT PSTORAGE_DESCRIPTOR_HEADER *Descriptor
  4748. )
  4749. {
  4750. STORAGE_PROPERTY_QUERY query;
  4751. IO_STATUS_BLOCK ioStatus;
  4752. PSTORAGE_DESCRIPTOR_HEADER descriptor = NULL;
  4753. ULONG length;
  4754. UCHAR pass = 0;
  4755. PAGED_CODE();
  4756. //
  4757. // Set the passed-in descriptor pointer to NULL as default
  4758. //
  4759. *Descriptor = NULL;
  4760. RtlZeroMemory(&query, sizeof(STORAGE_PROPERTY_QUERY));
  4761. query.PropertyId = *PropertyId;
  4762. query.QueryType = PropertyStandardQuery;
  4763. //
  4764. // On the first pass we just want to get the first few
  4765. // bytes of the descriptor so we can read it's size
  4766. //
  4767. descriptor = (PVOID)&query;
  4768. ASSERT(sizeof(STORAGE_PROPERTY_QUERY) >= (sizeof(ULONG)*2));
  4769. ClassSendDeviceIoControlSynchronous(
  4770. IOCTL_STORAGE_QUERY_PROPERTY,
  4771. DeviceObject,
  4772. &query,
  4773. sizeof(STORAGE_PROPERTY_QUERY),
  4774. sizeof(ULONG) * 2,
  4775. FALSE,
  4776. &ioStatus
  4777. );
  4778. if(!NT_SUCCESS(ioStatus.Status)) {
  4779. DebugPrint((1, "ClassGetDescriptor: error %lx trying to "
  4780. "query properties #1\n", ioStatus.Status));
  4781. return ioStatus.Status;
  4782. }
  4783. if (descriptor->Size == 0) {
  4784. //
  4785. // This DebugPrint is to help third-party driver writers
  4786. //
  4787. DebugPrint((0, "ClassGetDescriptor: size returned was zero?! (status "
  4788. "%x\n", ioStatus.Status));
  4789. return STATUS_UNSUCCESSFUL;
  4790. }
  4791. //
  4792. // This time we know how much data there is so we can
  4793. // allocate a buffer of the correct size
  4794. //
  4795. length = descriptor->Size;
  4796. descriptor = ExAllocatePoolWithTag(NonPagedPool, length, '4BcS');
  4797. if(descriptor == NULL) {
  4798. DebugPrint((1, "ClassGetDescriptor: unable to memory for descriptor "
  4799. "(%d bytes)\n", length));
  4800. return STATUS_INSUFFICIENT_RESOURCES;
  4801. }
  4802. //
  4803. // setup the query again, as it was overwritten above
  4804. //
  4805. RtlZeroMemory(&query, sizeof(STORAGE_PROPERTY_QUERY));
  4806. query.PropertyId = *PropertyId;
  4807. query.QueryType = PropertyStandardQuery;
  4808. //
  4809. // copy the input to the new outputbuffer
  4810. //
  4811. RtlCopyMemory(descriptor,
  4812. &query,
  4813. sizeof(STORAGE_PROPERTY_QUERY)
  4814. );
  4815. ClassSendDeviceIoControlSynchronous(
  4816. IOCTL_STORAGE_QUERY_PROPERTY,
  4817. DeviceObject,
  4818. descriptor,
  4819. sizeof(STORAGE_PROPERTY_QUERY),
  4820. length,
  4821. FALSE,
  4822. &ioStatus
  4823. );
  4824. if(!NT_SUCCESS(ioStatus.Status)) {
  4825. DebugPrint((1, "ClassGetDescriptor: error %lx trying to "
  4826. "query properties #1\n", ioStatus.Status));
  4827. ExFreePool(descriptor);
  4828. return ioStatus.Status;
  4829. }
  4830. //
  4831. // return the memory we've allocated to the caller
  4832. //
  4833. *Descriptor = descriptor;
  4834. return ioStatus.Status;
  4835. } // end ClassGetDescriptor()
  4836. /*++////////////////////////////////////////////////////////////////////////////
  4837. ClassSignalCompletion()
  4838. Routine Description:
  4839. This completion routine will signal the event given as context and then
  4840. return STATUS_MORE_PROCESSING_REQUIRED to stop event completion. It is
  4841. the responsibility of the routine waiting on the event to complete the
  4842. request and free the event.
  4843. Arguments:
  4844. DeviceObject - a pointer to the device object
  4845. Irp - a pointer to the irp
  4846. Event - a pointer to the event to signal
  4847. Return Value:
  4848. STATUS_MORE_PROCESSING_REQUIRED
  4849. --*/
  4850. NTSTATUS
  4851. ClassSignalCompletion(
  4852. IN PDEVICE_OBJECT DeviceObject,
  4853. IN PIRP Irp,
  4854. IN PKEVENT Event
  4855. )
  4856. {
  4857. KeSetEvent(Event, IO_NO_INCREMENT, FALSE);
  4858. return STATUS_MORE_PROCESSING_REQUIRED;
  4859. } // end ClassSignalCompletion()
  4860. /*++////////////////////////////////////////////////////////////////////////////
  4861. ClassPnpQueryFdoRelations()
  4862. Routine Description:
  4863. This routine will call the driver's enumeration routine to update the
  4864. list of PDO's. It will then build a response to the
  4865. IRP_MN_QUERY_DEVICE_RELATIONS and place it into the information field in
  4866. the irp.
  4867. Arguments:
  4868. Fdo - a pointer to the functional device object we are enumerating
  4869. Irp - a pointer to the enumeration request
  4870. Return Value:
  4871. status
  4872. --*/
  4873. NTSTATUS
  4874. ClassPnpQueryFdoRelations(
  4875. IN PDEVICE_OBJECT Fdo,
  4876. IN PIRP Irp
  4877. )
  4878. {
  4879. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  4880. PCLASS_DRIVER_EXTENSION
  4881. driverExtension = IoGetDriverObjectExtension(Fdo->DriverObject,
  4882. CLASS_DRIVER_EXTENSION_KEY);
  4883. NTSTATUS status;
  4884. PAGED_CODE();
  4885. //
  4886. // If there's already an enumeration in progress then don't start another
  4887. // one.
  4888. //
  4889. if(InterlockedIncrement(&(fdoExtension->EnumerationInterlock)) == 1) {
  4890. status = driverExtension->InitData.ClassEnumerateDevice(Fdo);
  4891. }
  4892. Irp->IoStatus.Information = (ULONG_PTR) NULL;
  4893. Irp->IoStatus.Status = ClassRetrieveDeviceRelations(
  4894. Fdo,
  4895. BusRelations,
  4896. &((PDEVICE_RELATIONS) Irp->IoStatus.Information));
  4897. InterlockedDecrement(&(fdoExtension->EnumerationInterlock));
  4898. return Irp->IoStatus.Status;
  4899. } // end ClassPnpQueryFdoRelations()
  4900. /*++////////////////////////////////////////////////////////////////////////////
  4901. ClassMarkChildrenMissing()
  4902. Routine Description:
  4903. This routine will call ClassMarkChildMissing() for all children.
  4904. It acquires the ChildLock before calling ClassMarkChildMissing().
  4905. Arguments:
  4906. Fdo - the "bus's" device object, such as the disk FDO for non-removable
  4907. disks with multiple partitions.
  4908. Return Value:
  4909. None
  4910. --*/
  4911. VOID
  4912. ClassMarkChildrenMissing(
  4913. IN PFUNCTIONAL_DEVICE_EXTENSION Fdo
  4914. )
  4915. {
  4916. PCOMMON_DEVICE_EXTENSION commonExtension = &(Fdo->CommonExtension);
  4917. PPHYSICAL_DEVICE_EXTENSION nextChild = commonExtension->ChildList;
  4918. PAGED_CODE();
  4919. ClassAcquireChildLock(Fdo);
  4920. while (nextChild){
  4921. PPHYSICAL_DEVICE_EXTENSION tmpChild;
  4922. /*
  4923. * ClassMarkChildMissing will also dequeue the child extension.
  4924. * So get the next pointer before calling ClassMarkChildMissing.
  4925. */
  4926. tmpChild = nextChild;
  4927. nextChild = tmpChild->CommonExtension.ChildList;
  4928. ClassMarkChildMissing(tmpChild, FALSE);
  4929. }
  4930. ClassReleaseChildLock(Fdo);
  4931. return;
  4932. } // end ClassMarkChildrenMissing()
  4933. /*++////////////////////////////////////////////////////////////////////////////
  4934. ClassMarkChildMissing()
  4935. Routine Description:
  4936. This routine will make an active child "missing." If the device has never
  4937. been enumerated then it will be deleted on the spot. If the device has
  4938. not been enumerated then it will be marked as missing so that we can
  4939. not report it in the next device enumeration.
  4940. Arguments:
  4941. Child - the child device to be marked as missing.
  4942. AcquireChildLock - TRUE if the child lock should be acquired before removing
  4943. the missing child. FALSE if the child lock is already
  4944. acquired by this thread.
  4945. Return Value:
  4946. returns whether or not the child device object has previously been reported
  4947. to PNP.
  4948. --*/
  4949. BOOLEAN
  4950. ClassMarkChildMissing(
  4951. IN PPHYSICAL_DEVICE_EXTENSION Child,
  4952. IN BOOLEAN AcquireChildLock
  4953. )
  4954. {
  4955. BOOLEAN returnValue = Child->IsEnumerated;
  4956. PAGED_CODE();
  4957. ASSERT_PDO(Child->DeviceObject);
  4958. Child->IsMissing = TRUE;
  4959. //
  4960. // Make sure this child is not in the active list.
  4961. //
  4962. ClassRemoveChild(Child->CommonExtension.PartitionZeroExtension,
  4963. Child,
  4964. AcquireChildLock);
  4965. if(Child->IsEnumerated == FALSE) {
  4966. ClassRemoveDevice(Child->DeviceObject, IRP_MN_REMOVE_DEVICE);
  4967. }
  4968. return returnValue;
  4969. } // end ClassMarkChildMissing()
  4970. /*++////////////////////////////////////////////////////////////////////////////
  4971. ClassRetrieveDeviceRelations()
  4972. Routine Description:
  4973. This routine will allocate a buffer to hold the specified list of
  4974. relations. It will then fill in the list with referenced device pointers
  4975. and will return the request.
  4976. Arguments:
  4977. Fdo - pointer to the FDO being queried
  4978. RelationType - what type of relations are being queried
  4979. DeviceRelations - a location to store a pointer to the response
  4980. Return Value:
  4981. status
  4982. --*/
  4983. NTSTATUS
  4984. ClassRetrieveDeviceRelations(
  4985. IN PDEVICE_OBJECT Fdo,
  4986. IN DEVICE_RELATION_TYPE RelationType,
  4987. OUT PDEVICE_RELATIONS *DeviceRelations
  4988. )
  4989. {
  4990. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  4991. ULONG count = 0;
  4992. ULONG i;
  4993. PPHYSICAL_DEVICE_EXTENSION nextChild;
  4994. ULONG relationsSize;
  4995. PDEVICE_RELATIONS deviceRelations = NULL;
  4996. NTSTATUS status;
  4997. PAGED_CODE();
  4998. ClassAcquireChildLock(fdoExtension);
  4999. nextChild = fdoExtension->CommonExtension.ChildList;
  5000. //
  5001. // Count the number of PDO's attached to this disk
  5002. //
  5003. while(nextChild != NULL) {
  5004. PCOMMON_DEVICE_EXTENSION commonExtension;
  5005. commonExtension = &(nextChild->CommonExtension);
  5006. ASSERTMSG("ClassPnp internal error: missing child on active list\n",
  5007. (nextChild->IsMissing == FALSE));
  5008. nextChild = commonExtension->ChildList;
  5009. count++;
  5010. };
  5011. relationsSize = (sizeof(DEVICE_RELATIONS) +
  5012. (count * sizeof(PDEVICE_OBJECT)));
  5013. deviceRelations = ExAllocatePoolWithTag(PagedPool, relationsSize, '5BcS');
  5014. if(deviceRelations == NULL) {
  5015. DebugPrint((1, "ClassRetrieveDeviceRelations: unable to allocate "
  5016. "%d bytes for device relations\n", relationsSize));
  5017. ClassReleaseChildLock(fdoExtension);
  5018. return STATUS_INSUFFICIENT_RESOURCES;
  5019. }
  5020. RtlZeroMemory(deviceRelations, relationsSize);
  5021. nextChild = fdoExtension->CommonExtension.ChildList;
  5022. i = count - 1;
  5023. while(nextChild != NULL) {
  5024. PCOMMON_DEVICE_EXTENSION commonExtension;
  5025. commonExtension = &(nextChild->CommonExtension);
  5026. ASSERTMSG("ClassPnp internal error: missing child on active list\n",
  5027. (nextChild->IsMissing == FALSE));
  5028. deviceRelations->Objects[i--] = nextChild->DeviceObject;
  5029. status = ObReferenceObjectByPointer(
  5030. nextChild->DeviceObject,
  5031. 0,
  5032. NULL,
  5033. KernelMode);
  5034. ASSERT(NT_SUCCESS(status));
  5035. nextChild->IsEnumerated = TRUE;
  5036. nextChild = commonExtension->ChildList;
  5037. }
  5038. ASSERTMSG("Child list has changed: ", i == -1);
  5039. deviceRelations->Count = count;
  5040. *DeviceRelations = deviceRelations;
  5041. ClassReleaseChildLock(fdoExtension);
  5042. return STATUS_SUCCESS;
  5043. } // end ClassRetrieveDeviceRelations()
  5044. /*++////////////////////////////////////////////////////////////////////////////
  5045. ClassGetPdoId()
  5046. Routine Description:
  5047. This routine will call into the driver to retrieve a copy of one of it's
  5048. id strings.
  5049. Arguments:
  5050. Pdo - a pointer to the pdo being queried
  5051. IdType - which type of id string is being queried
  5052. IdString - an allocated unicode string structure which the driver
  5053. can fill in.
  5054. Return Value:
  5055. status
  5056. --*/
  5057. NTSTATUS
  5058. ClassGetPdoId(
  5059. IN PDEVICE_OBJECT Pdo,
  5060. IN BUS_QUERY_ID_TYPE IdType,
  5061. IN PUNICODE_STRING IdString
  5062. )
  5063. {
  5064. PCLASS_DRIVER_EXTENSION
  5065. driverExtension = IoGetDriverObjectExtension(Pdo->DriverObject,
  5066. CLASS_DRIVER_EXTENSION_KEY);
  5067. ASSERT_PDO(Pdo);
  5068. ASSERT(driverExtension->InitData.ClassQueryId);
  5069. PAGED_CODE();
  5070. return driverExtension->InitData.ClassQueryId( Pdo, IdType, IdString);
  5071. } // end ClassGetPdoId()
  5072. /*++////////////////////////////////////////////////////////////////////////////
  5073. ClassQueryPnpCapabilities()
  5074. Routine Description:
  5075. This routine will call into the class driver to retrieve it's pnp
  5076. capabilities.
  5077. Arguments:
  5078. PhysicalDeviceObject - The physical device object to retrieve properties
  5079. for.
  5080. Return Value:
  5081. status
  5082. --*/
  5083. NTSTATUS
  5084. ClassQueryPnpCapabilities(
  5085. IN PDEVICE_OBJECT DeviceObject,
  5086. IN PDEVICE_CAPABILITIES Capabilities
  5087. )
  5088. {
  5089. PCLASS_DRIVER_EXTENSION driverExtension =
  5090. ClassGetDriverExtension(DeviceObject->DriverObject);
  5091. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  5092. PCLASS_QUERY_PNP_CAPABILITIES queryRoutine = NULL;
  5093. PAGED_CODE();
  5094. ASSERT(DeviceObject);
  5095. ASSERT(Capabilities);
  5096. if(commonExtension->IsFdo) {
  5097. queryRoutine = driverExtension->InitData.FdoData.ClassQueryPnpCapabilities;
  5098. } else {
  5099. queryRoutine = driverExtension->InitData.PdoData.ClassQueryPnpCapabilities;
  5100. }
  5101. if(queryRoutine) {
  5102. return queryRoutine(DeviceObject,
  5103. Capabilities);
  5104. } else {
  5105. return STATUS_NOT_IMPLEMENTED;
  5106. }
  5107. } // end ClassQueryPnpCapabilities()
  5108. /*++////////////////////////////////////////////////////////////////////////////
  5109. ClassInvalidateBusRelations()
  5110. Routine Description:
  5111. This routine re-enumerates the devices on the "bus". It will call into
  5112. the driver's ClassEnumerate routine to update the device objects
  5113. immediately. It will then schedule a bus re-enumeration for pnp by calling
  5114. IoInvalidateDeviceRelations.
  5115. Arguments:
  5116. Fdo - a pointer to the functional device object for this bus
  5117. Return Value:
  5118. none
  5119. --*/
  5120. VOID
  5121. ClassInvalidateBusRelations(
  5122. IN PDEVICE_OBJECT Fdo
  5123. )
  5124. {
  5125. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  5126. PCLASS_DRIVER_EXTENSION
  5127. driverExtension = IoGetDriverObjectExtension(Fdo->DriverObject,
  5128. CLASS_DRIVER_EXTENSION_KEY);
  5129. NTSTATUS status = STATUS_SUCCESS;
  5130. PAGED_CODE();
  5131. ASSERT_FDO(Fdo);
  5132. ASSERT(driverExtension->InitData.ClassEnumerateDevice != NULL);
  5133. if(InterlockedIncrement(&(fdoExtension->EnumerationInterlock)) == 1) {
  5134. status = driverExtension->InitData.ClassEnumerateDevice(Fdo);
  5135. }
  5136. InterlockedDecrement(&(fdoExtension->EnumerationInterlock));
  5137. if(!NT_SUCCESS(status)) {
  5138. DebugPrint((1, "ClassInvalidateBusRelations: EnumerateDevice routine "
  5139. "returned %lx\n", status));
  5140. }
  5141. IoInvalidateDeviceRelations(fdoExtension->LowerPdo, BusRelations);
  5142. return;
  5143. } // end ClassInvalidateBusRelations()
  5144. /*++////////////////////////////////////////////////////////////////////////////
  5145. ClassRemoveDevice() ISSUE-2000/02/18-henrygab - why public?!
  5146. Routine Description:
  5147. This routine is called to handle the "removal" of a device. It will
  5148. forward the request downwards if necesssary, call into the driver
  5149. to release any necessary resources (memory, events, etc) and then
  5150. will delete the device object.
  5151. Arguments:
  5152. DeviceObject - a pointer to the device object being removed
  5153. RemoveType - indicates what type of remove this is (regular or surprise).
  5154. Return Value:
  5155. status
  5156. --*/
  5157. NTSTATUS
  5158. ClassRemoveDevice(
  5159. IN PDEVICE_OBJECT DeviceObject,
  5160. IN UCHAR RemoveType
  5161. )
  5162. {
  5163. PCLASS_DRIVER_EXTENSION
  5164. driverExtension = IoGetDriverObjectExtension(DeviceObject->DriverObject,
  5165. CLASS_DRIVER_EXTENSION_KEY);
  5166. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  5167. PDEVICE_OBJECT lowerDeviceObject = commonExtension->LowerDeviceObject;
  5168. PCLASS_WMI_INFO classWmiInfo;
  5169. BOOLEAN proceedWithRemove = TRUE;
  5170. NTSTATUS status;
  5171. PAGED_CODE();
  5172. commonExtension->IsRemoved = REMOVE_PENDING;
  5173. /*
  5174. * Deregister from WMI.
  5175. */
  5176. classWmiInfo = commonExtension->IsFdo ?
  5177. &driverExtension->InitData.FdoData.ClassWmiInfo :
  5178. &driverExtension->InitData.PdoData.ClassWmiInfo;
  5179. if (classWmiInfo->GuidRegInfo){
  5180. status = IoWMIRegistrationControl(DeviceObject, WMIREG_ACTION_DEREGISTER);
  5181. DBGTRACE(ClassDebugInfo, ("ClassRemoveDevice: IoWMIRegistrationControl(%p, WMI_ACTION_DEREGISTER) --> %lx", DeviceObject, status));
  5182. }
  5183. /*
  5184. * If we exposed a "shingle" (a named device interface openable by CreateFile)
  5185. * then delete it now.
  5186. */
  5187. if (commonExtension->MountedDeviceInterfaceName.Buffer){
  5188. IoSetDeviceInterfaceState(&commonExtension->MountedDeviceInterfaceName, FALSE);
  5189. RtlFreeUnicodeString(&commonExtension->MountedDeviceInterfaceName);
  5190. RtlInitUnicodeString(&commonExtension->MountedDeviceInterfaceName, NULL);
  5191. }
  5192. //
  5193. // If this is a surprise removal we leave the device around - which means
  5194. // we don't have to (or want to) drop the remove lock and wait for pending
  5195. // requests to complete.
  5196. //
  5197. if (RemoveType == IRP_MN_REMOVE_DEVICE){
  5198. //
  5199. // Release the lock we acquired when the device object was created.
  5200. //
  5201. ClassReleaseRemoveLock(DeviceObject, (PIRP) DeviceObject);
  5202. DebugPrint((1, "ClasspRemoveDevice - Reference count is now %d\n",
  5203. commonExtension->RemoveLock));
  5204. KeWaitForSingleObject(&commonExtension->RemoveEvent,
  5205. Executive,
  5206. KernelMode,
  5207. FALSE,
  5208. NULL);
  5209. DebugPrint((1, "ClasspRemoveDevice - removing device %p\n", DeviceObject));
  5210. if(commonExtension->IsFdo) {
  5211. DebugPrint((1, "ClasspRemoveDevice - FDO %p has received a "
  5212. "remove request.\n", DeviceObject));
  5213. }
  5214. else {
  5215. PPHYSICAL_DEVICE_EXTENSION pdoExtension = DeviceObject->DeviceExtension;
  5216. if (pdoExtension->IsMissing){
  5217. /*
  5218. * The child partition PDO is missing, so we are going to go ahead
  5219. * and delete it for the remove.
  5220. */
  5221. DBGTRACE(ClassDebugWarning, ("ClasspRemoveDevice - PDO %p is missing and will be removed", DeviceObject));
  5222. }
  5223. else {
  5224. /*
  5225. * We got a remove for a child partition PDO which is not actually missing.
  5226. * So we will NOT actually delete it.
  5227. */
  5228. DBGTRACE(ClassDebugWarning, ("ClasspRemoveDevice - PDO %p still exists and will be removed when it disappears", DeviceObject));
  5229. //
  5230. // Reacquire the remove lock for the next time this comes around.
  5231. //
  5232. ClassAcquireRemoveLock(DeviceObject, (PIRP) DeviceObject);
  5233. //
  5234. // the device wasn't missing so it's not really been removed.
  5235. //
  5236. commonExtension->IsRemoved = NO_REMOVE;
  5237. IoInvalidateDeviceRelations(
  5238. commonExtension->PartitionZeroExtension->LowerPdo,
  5239. BusRelations);
  5240. proceedWithRemove = FALSE;
  5241. }
  5242. }
  5243. }
  5244. if (proceedWithRemove){
  5245. /*
  5246. * Call the class driver's remove handler.
  5247. * All this is supposed to do is clean up its data and device interfaces.
  5248. */
  5249. ASSERT(commonExtension->DevInfo->ClassRemoveDevice);
  5250. status = commonExtension->DevInfo->ClassRemoveDevice(DeviceObject, RemoveType);
  5251. ASSERT(NT_SUCCESS(status));
  5252. status = STATUS_SUCCESS;
  5253. if (commonExtension->IsFdo){
  5254. PDEVICE_OBJECT pdo;
  5255. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
  5256. ClasspDisableTimer(fdoExtension->DeviceObject);
  5257. if (RemoveType == IRP_MN_REMOVE_DEVICE){
  5258. PPHYSICAL_DEVICE_EXTENSION child;
  5259. //
  5260. // Cleanup the media detection resources now that the class driver
  5261. // has stopped it's timer (if any) and we can be sure they won't
  5262. // call us to do detection again.
  5263. //
  5264. ClassCleanupMediaChangeDetection(fdoExtension);
  5265. //
  5266. // Cleanup any Failure Prediction stuff
  5267. //
  5268. if (fdoExtension->FailurePredictionInfo) {
  5269. ExFreePool(fdoExtension->FailurePredictionInfo);
  5270. fdoExtension->FailurePredictionInfo = NULL;
  5271. }
  5272. /*
  5273. * Ordinarily all child PDOs will be removed by the time
  5274. * that the parent gets the REMOVE_DEVICE.
  5275. * However, if a child PDO has been created but has not
  5276. * been announced in a QueryDeviceRelations, then it is
  5277. * just a private data structure unknown to pnp, and we have
  5278. * to delete it ourselves.
  5279. */
  5280. ClassAcquireChildLock(fdoExtension);
  5281. while (child = ClassRemoveChild(fdoExtension, NULL, FALSE)){
  5282. //
  5283. // Yank the pdo. This routine will unlink the device from the
  5284. // pdo list so NextPdo will point to the next one when it's
  5285. // complete.
  5286. //
  5287. child->IsMissing = TRUE;
  5288. ClassRemoveDevice(child->DeviceObject, IRP_MN_REMOVE_DEVICE);
  5289. }
  5290. ClassReleaseChildLock(fdoExtension);
  5291. }
  5292. else if (RemoveType == IRP_MN_SURPRISE_REMOVAL){
  5293. /*
  5294. * This is a surprise-remove on the parent FDO.
  5295. * We will mark the child PDOs as missing so that they
  5296. * will actually get deleted when they get a REMOVE_DEVICE.
  5297. */
  5298. ClassMarkChildrenMissing(fdoExtension);
  5299. }
  5300. ClasspFreeReleaseRequest(DeviceObject);
  5301. if (RemoveType == IRP_MN_REMOVE_DEVICE){
  5302. //
  5303. // Free FDO-specific data structs
  5304. //
  5305. if (fdoExtension->PrivateFdoData){
  5306. DestroyAllTransferPackets(DeviceObject);
  5307. ExFreePool(fdoExtension->PrivateFdoData);
  5308. fdoExtension->PrivateFdoData = NULL;
  5309. }
  5310. if (commonExtension->DeviceName.Buffer) {
  5311. ExFreePool(commonExtension->DeviceName.Buffer);
  5312. RtlInitUnicodeString(&commonExtension->DeviceName, NULL);
  5313. }
  5314. if (fdoExtension->AdapterDescriptor) {
  5315. ExFreePool(fdoExtension->AdapterDescriptor);
  5316. fdoExtension->AdapterDescriptor = NULL;
  5317. }
  5318. if (fdoExtension->DeviceDescriptor) {
  5319. ExFreePool(fdoExtension->DeviceDescriptor);
  5320. fdoExtension->DeviceDescriptor = NULL;
  5321. }
  5322. //
  5323. // Detach our device object from the stack - there's no reason
  5324. // to hold off our cleanup any longer.
  5325. //
  5326. IoDetachDevice(lowerDeviceObject);
  5327. }
  5328. }
  5329. else {
  5330. /*
  5331. * This is a child partition PDO.
  5332. * We have already determined that it was previously marked
  5333. * as missing. So if this is a REMOVE_DEVICE, we will actually
  5334. * delete it.
  5335. */
  5336. if (RemoveType == IRP_MN_REMOVE_DEVICE){
  5337. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension =
  5338. commonExtension->PartitionZeroExtension;
  5339. PPHYSICAL_DEVICE_EXTENSION pdoExtension =
  5340. (PPHYSICAL_DEVICE_EXTENSION) commonExtension;
  5341. //
  5342. // See if this device is in the child list (if this was a suprise
  5343. // removal it might be) and remove it.
  5344. //
  5345. ClassRemoveChild(fdoExtension, pdoExtension, TRUE);
  5346. }
  5347. }
  5348. commonExtension->PartitionLength.QuadPart = 0;
  5349. if (RemoveType == IRP_MN_REMOVE_DEVICE){
  5350. IoDeleteDevice(DeviceObject);
  5351. }
  5352. }
  5353. return STATUS_SUCCESS;
  5354. } // end ClassRemoveDevice()
  5355. /*++////////////////////////////////////////////////////////////////////////////
  5356. ClassGetDriverExtension()
  5357. Routine Description:
  5358. This routine will return the classpnp's driver extension.
  5359. Arguments:
  5360. DriverObject - the driver object for which to get classpnp's extension
  5361. Return Value:
  5362. Either NULL if none, or a pointer to the driver extension
  5363. --*/
  5364. PCLASS_DRIVER_EXTENSION
  5365. ClassGetDriverExtension(
  5366. IN PDRIVER_OBJECT DriverObject
  5367. )
  5368. {
  5369. return IoGetDriverObjectExtension(DriverObject, CLASS_DRIVER_EXTENSION_KEY);
  5370. } // end ClassGetDriverExtension()
  5371. /*++////////////////////////////////////////////////////////////////////////////
  5372. ClasspStartIo()
  5373. Routine Description:
  5374. This routine wraps the class driver's start io routine. If the device
  5375. is being removed it will complete any requests with
  5376. STATUS_DEVICE_DOES_NOT_EXIST and fire up the next packet.
  5377. Arguments:
  5378. Return Value:
  5379. none
  5380. --*/
  5381. VOID
  5382. ClasspStartIo(
  5383. IN PDEVICE_OBJECT DeviceObject,
  5384. IN PIRP Irp
  5385. )
  5386. {
  5387. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  5388. //
  5389. // We're already holding the remove lock so just check the variable and
  5390. // see what's going on.
  5391. //
  5392. if(commonExtension->IsRemoved) {
  5393. Irp->IoStatus.Status = STATUS_DEVICE_DOES_NOT_EXIST;
  5394. ClassAcquireRemoveLock(DeviceObject, (PIRP) ClasspStartIo);
  5395. ClassReleaseRemoveLock(DeviceObject, Irp);
  5396. ClassCompleteRequest(DeviceObject, Irp, IO_DISK_INCREMENT);
  5397. IoStartNextPacket(DeviceObject, FALSE);
  5398. ClassReleaseRemoveLock(DeviceObject, (PIRP) ClasspStartIo);
  5399. return;
  5400. }
  5401. commonExtension->DriverExtension->InitData.ClassStartIo(
  5402. DeviceObject,
  5403. Irp);
  5404. return;
  5405. } // ClasspStartIo()
  5406. /*++////////////////////////////////////////////////////////////////////////////
  5407. ClassUpdateInformationInRegistry()
  5408. Routine Description:
  5409. This routine has knowledge about the layout of the device map information
  5410. in the registry. It will update this information to include a value
  5411. entry specifying the dos device name that is assumed to get assigned
  5412. to this NT device name. For more information on this assigning of the
  5413. dos device name look in the drive support routine in the hal that assigns
  5414. all dos names.
  5415. Since some versions of some device's firmware did not work and some
  5416. vendors did not bother to follow the specification, the entire inquiry
  5417. information must also be stored in the registry so than someone can
  5418. figure out the firmware version.
  5419. Arguments:
  5420. DeviceObject - A pointer to the device object for the tape device.
  5421. Return Value:
  5422. None
  5423. --*/
  5424. VOID
  5425. ClassUpdateInformationInRegistry(
  5426. IN PDEVICE_OBJECT Fdo,
  5427. IN PCHAR DeviceName,
  5428. IN ULONG DeviceNumber,
  5429. IN PINQUIRYDATA InquiryData,
  5430. IN ULONG InquiryDataLength
  5431. )
  5432. {
  5433. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
  5434. NTSTATUS status;
  5435. SCSI_ADDRESS scsiAddress;
  5436. OBJECT_ATTRIBUTES objectAttributes;
  5437. PUCHAR buffer;
  5438. STRING string;
  5439. UNICODE_STRING unicodeName;
  5440. UNICODE_STRING unicodeRegistryPath;
  5441. UNICODE_STRING unicodeData;
  5442. HANDLE targetKey;
  5443. IO_STATUS_BLOCK ioStatus;
  5444. PAGED_CODE();
  5445. ASSERT(DeviceName);
  5446. fdoExtension = Fdo->DeviceExtension;
  5447. buffer = NULL;
  5448. targetKey = NULL;
  5449. RtlZeroMemory(&unicodeName, sizeof(UNICODE_STRING));
  5450. RtlZeroMemory(&unicodeData, sizeof(UNICODE_STRING));
  5451. RtlZeroMemory(&unicodeRegistryPath, sizeof(UNICODE_STRING));
  5452. TRY {
  5453. //
  5454. // Issue GET_ADDRESS Ioctl to determine path, target, and lun information.
  5455. //
  5456. ClassSendDeviceIoControlSynchronous(
  5457. IOCTL_SCSI_GET_ADDRESS,
  5458. Fdo,
  5459. &scsiAddress,
  5460. 0,
  5461. sizeof(SCSI_ADDRESS),
  5462. FALSE,
  5463. &ioStatus
  5464. );
  5465. if (!NT_SUCCESS(ioStatus.Status)) {
  5466. status = ioStatus.Status;
  5467. DebugPrint((1,
  5468. "UpdateInformationInRegistry: Get Address failed %lx\n",
  5469. status));
  5470. LEAVE;
  5471. } else {
  5472. DebugPrint((1,
  5473. "GetAddress: Port %x, Path %x, Target %x, Lun %x\n",
  5474. scsiAddress.PortNumber,
  5475. scsiAddress.PathId,
  5476. scsiAddress.TargetId,
  5477. scsiAddress.Lun));
  5478. }
  5479. //
  5480. // Allocate a buffer for the reg. spooge.
  5481. //
  5482. buffer = ExAllocatePoolWithTag(PagedPool, 1024, '6BcS');
  5483. if (buffer == NULL) {
  5484. //
  5485. // There is not return value for this. Since this is done at
  5486. // claim device time (currently only system initialization) getting
  5487. // the registry information correct will be the least of the worries.
  5488. //
  5489. LEAVE;
  5490. }
  5491. sprintf(buffer,
  5492. "\\Registry\\Machine\\Hardware\\DeviceMap\\Scsi\\Scsi Port %d\\Scsi Bus %d\\Target Id %d\\Logical Unit Id %d",
  5493. scsiAddress.PortNumber,
  5494. scsiAddress.PathId,
  5495. scsiAddress.TargetId,
  5496. scsiAddress.Lun);
  5497. RtlInitString(&string, buffer);
  5498. status = RtlAnsiStringToUnicodeString(&unicodeRegistryPath,
  5499. &string,
  5500. TRUE);
  5501. if (!NT_SUCCESS(status)) {
  5502. LEAVE;
  5503. }
  5504. //
  5505. // Open the registry key for the scsi information for this
  5506. // scsibus, target, lun.
  5507. //
  5508. InitializeObjectAttributes(&objectAttributes,
  5509. &unicodeRegistryPath,
  5510. OBJ_CASE_INSENSITIVE,
  5511. NULL,
  5512. NULL);
  5513. status = ZwOpenKey(&targetKey,
  5514. KEY_READ | KEY_WRITE,
  5515. &objectAttributes);
  5516. if (!NT_SUCCESS(status)) {
  5517. LEAVE;
  5518. }
  5519. //
  5520. // Now construct and attempt to create the registry value
  5521. // specifying the device name in the appropriate place in the
  5522. // device map.
  5523. //
  5524. RtlInitUnicodeString(&unicodeName, L"DeviceName");
  5525. sprintf(buffer, "%s%d", DeviceName, DeviceNumber);
  5526. RtlInitString(&string, buffer);
  5527. status = RtlAnsiStringToUnicodeString(&unicodeData,
  5528. &string,
  5529. TRUE);
  5530. if (NT_SUCCESS(status)) {
  5531. status = ZwSetValueKey(targetKey,
  5532. &unicodeName,
  5533. 0,
  5534. REG_SZ,
  5535. unicodeData.Buffer,
  5536. unicodeData.Length);
  5537. }
  5538. //
  5539. // if they sent in data, update the registry
  5540. //
  5541. if (InquiryDataLength) {
  5542. ASSERT(InquiryData);
  5543. RtlInitUnicodeString(&unicodeName, L"InquiryData");
  5544. status = ZwSetValueKey(targetKey,
  5545. &unicodeName,
  5546. 0,
  5547. REG_BINARY,
  5548. InquiryData,
  5549. InquiryDataLength);
  5550. }
  5551. // that's all, except to clean up.
  5552. } FINALLY {
  5553. if (unicodeData.Buffer) {
  5554. RtlFreeUnicodeString(&unicodeData);
  5555. }
  5556. if (unicodeRegistryPath.Buffer) {
  5557. RtlFreeUnicodeString(&unicodeRegistryPath);
  5558. }
  5559. if (targetKey) {
  5560. ZwClose(targetKey);
  5561. }
  5562. if (buffer) {
  5563. ExFreePool(buffer);
  5564. }
  5565. }
  5566. } // end ClassUpdateInformationInRegistry()
  5567. /*++////////////////////////////////////////////////////////////////////////////
  5568. ClasspSendSynchronousCompletion()
  5569. Routine Description:
  5570. This completion routine will set the user event in the irp after
  5571. freeing the irp and the associated MDL (if any).
  5572. Arguments:
  5573. DeviceObject - the device object which requested the completion routine
  5574. Irp - the irp being completed
  5575. Context - unused
  5576. Return Value:
  5577. STATUS_MORE_PROCESSING_REQUIRED
  5578. --*/
  5579. NTSTATUS
  5580. ClasspSendSynchronousCompletion(
  5581. IN PDEVICE_OBJECT DeviceObject,
  5582. IN PIRP Irp,
  5583. IN PVOID Context
  5584. )
  5585. {
  5586. DebugPrint((3, "ClasspSendSynchronousCompletion: %p %p %p\n",
  5587. DeviceObject, Irp, Context));
  5588. //
  5589. // First set the status and information fields in the io status block
  5590. // provided by the caller.
  5591. //
  5592. *(Irp->UserIosb) = Irp->IoStatus;
  5593. //
  5594. // Unlock the pages for the data buffer.
  5595. //
  5596. if(Irp->MdlAddress) {
  5597. MmUnlockPages(Irp->MdlAddress);
  5598. IoFreeMdl(Irp->MdlAddress);
  5599. }
  5600. //
  5601. // Signal the caller's event.
  5602. //
  5603. KeSetEvent(Irp->UserEvent, IO_NO_INCREMENT, FALSE);
  5604. //
  5605. // Free the MDL and the IRP.
  5606. //
  5607. IoFreeIrp(Irp);
  5608. return STATUS_MORE_PROCESSING_REQUIRED;
  5609. } // end ClasspSendSynchronousCompletion()
  5610. /*++
  5611. ISSUE-2000/02/20-henrygab Not documented ClasspRegisterMountedDeviceInterface
  5612. --*/
  5613. VOID
  5614. ClasspRegisterMountedDeviceInterface(
  5615. IN PDEVICE_OBJECT DeviceObject
  5616. )
  5617. {
  5618. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  5619. BOOLEAN isFdo = commonExtension->IsFdo;
  5620. PDEVICE_OBJECT pdo;
  5621. UNICODE_STRING interfaceName;
  5622. NTSTATUS status;
  5623. if(isFdo) {
  5624. PFUNCTIONAL_DEVICE_EXTENSION functionalExtension;
  5625. functionalExtension =
  5626. (PFUNCTIONAL_DEVICE_EXTENSION) commonExtension;
  5627. pdo = functionalExtension->LowerPdo;
  5628. } else {
  5629. pdo = DeviceObject;
  5630. }
  5631. status = IoRegisterDeviceInterface(
  5632. pdo,
  5633. &MOUNTDEV_MOUNTED_DEVICE_GUID,
  5634. NULL,
  5635. &interfaceName
  5636. );
  5637. if(NT_SUCCESS(status)) {
  5638. //
  5639. // Copy the interface name before setting the interface state - the
  5640. // name is needed by the components we notify.
  5641. //
  5642. commonExtension->MountedDeviceInterfaceName = interfaceName;
  5643. status = IoSetDeviceInterfaceState(&interfaceName, TRUE);
  5644. if(!NT_SUCCESS(status)) {
  5645. RtlFreeUnicodeString(&interfaceName);
  5646. }
  5647. }
  5648. if(!NT_SUCCESS(status)) {
  5649. RtlInitUnicodeString(&(commonExtension->MountedDeviceInterfaceName),
  5650. NULL);
  5651. }
  5652. return;
  5653. } // end ClasspRegisterMountedDeviceInterface()
  5654. /*++////////////////////////////////////////////////////////////////////////////
  5655. ClassSendDeviceIoControlSynchronous()
  5656. Routine Description:
  5657. This routine is based upon IoBuildDeviceIoControlRequest(). It has been
  5658. modified to reduce code and memory by not double-buffering the io, using
  5659. the same buffer for both input and output, allocating and deallocating
  5660. the mdl on behalf of the caller, and waiting for the io to complete.
  5661. This routine also works around the rare cases in which APC's are disabled.
  5662. Since IoBuildDeviceIoControl() used APC's to signal completion, this had
  5663. led to a number of difficult-to-detect hangs, where the irp was completed,
  5664. but the event passed to IoBuild..() was still being waited upon by the
  5665. caller.
  5666. Arguments:
  5667. IoControlCode - the IOCTL to send
  5668. TargetDeviceObject - the device object that should handle the ioctl
  5669. Buffer - the input and output buffer, or NULL if no input/output
  5670. InputBufferLength - the number of bytes prepared for the IOCTL in Buffer
  5671. OutputBufferLength - the number of bytes to be filled in upon success
  5672. InternalDeviceIoControl - if TRUE, uses IRP_MJ_INTERNAL_DEVICE_CONTROL
  5673. IoStatus - the status block that contains the results of the operation
  5674. Return Value:
  5675. --*/
  5676. VOID
  5677. ClassSendDeviceIoControlSynchronous(
  5678. IN ULONG IoControlCode,
  5679. IN PDEVICE_OBJECT TargetDeviceObject,
  5680. IN OUT PVOID Buffer OPTIONAL,
  5681. IN ULONG InputBufferLength,
  5682. IN ULONG OutputBufferLength,
  5683. IN BOOLEAN InternalDeviceIoControl,
  5684. OUT PIO_STATUS_BLOCK IoStatus
  5685. )
  5686. {
  5687. PIRP irp;
  5688. PIO_STACK_LOCATION irpSp;
  5689. ULONG method;
  5690. PAGED_CODE();
  5691. irp = NULL;
  5692. method = IoControlCode & 3;
  5693. #if DBG // Begin Argument Checking (nop in fre version)
  5694. ASSERT(ARGUMENT_PRESENT(IoStatus));
  5695. if ((InputBufferLength != 0) || (OutputBufferLength != 0)) {
  5696. ASSERT(ARGUMENT_PRESENT(Buffer));
  5697. }
  5698. else {
  5699. ASSERT(!ARGUMENT_PRESENT(Buffer));
  5700. }
  5701. #endif
  5702. //
  5703. // Begin by allocating the IRP for this request. Do not charge quota to
  5704. // the current process for this IRP.
  5705. //
  5706. irp = IoAllocateIrp(TargetDeviceObject->StackSize, FALSE);
  5707. if (!irp) {
  5708. (*IoStatus).Information = 0;
  5709. (*IoStatus).Status = STATUS_INSUFFICIENT_RESOURCES;
  5710. return;
  5711. }
  5712. //
  5713. // Get a pointer to the stack location of the first driver which will be
  5714. // invoked. This is where the function codes and the parameters are set.
  5715. //
  5716. irpSp = IoGetNextIrpStackLocation(irp);
  5717. //
  5718. // Set the major function code based on the type of device I/O control
  5719. // function the caller has specified.
  5720. //
  5721. if (InternalDeviceIoControl) {
  5722. irpSp->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
  5723. } else {
  5724. irpSp->MajorFunction = IRP_MJ_DEVICE_CONTROL;
  5725. }
  5726. //
  5727. // Copy the caller's parameters to the service-specific portion of the
  5728. // IRP for those parameters that are the same for all four methods.
  5729. //
  5730. irpSp->Parameters.DeviceIoControl.OutputBufferLength = OutputBufferLength;
  5731. irpSp->Parameters.DeviceIoControl.InputBufferLength = InputBufferLength;
  5732. irpSp->Parameters.DeviceIoControl.IoControlCode = IoControlCode;
  5733. //
  5734. // Get the method bits from the I/O control code to determine how the
  5735. // buffers are to be passed to the driver.
  5736. //
  5737. switch (method) {
  5738. // case 0
  5739. case METHOD_BUFFERED: {
  5740. if ((InputBufferLength != 0) || (OutputBufferLength != 0)) {
  5741. irp->AssociatedIrp.SystemBuffer =
  5742. ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
  5743. max(InputBufferLength, OutputBufferLength),
  5744. CLASS_TAG_DEVICE_CONTROL
  5745. );
  5746. if (irp->AssociatedIrp.SystemBuffer == NULL) {
  5747. IoFreeIrp(irp);
  5748. (*IoStatus).Information = 0;
  5749. (*IoStatus).Status = STATUS_INSUFFICIENT_RESOURCES;
  5750. return;
  5751. }
  5752. if (InputBufferLength != 0) {
  5753. RtlCopyMemory(irp->AssociatedIrp.SystemBuffer,
  5754. Buffer,
  5755. InputBufferLength);
  5756. }
  5757. } // end of buffering
  5758. irp->UserBuffer = Buffer;
  5759. break;
  5760. }
  5761. // case 1, case 2
  5762. case METHOD_IN_DIRECT:
  5763. case METHOD_OUT_DIRECT: {
  5764. if (InputBufferLength != 0) {
  5765. irp->AssociatedIrp.SystemBuffer = Buffer;
  5766. }
  5767. if (OutputBufferLength != 0) {
  5768. irp->MdlAddress = IoAllocateMdl(Buffer,
  5769. OutputBufferLength,
  5770. FALSE, FALSE,
  5771. (PIRP) NULL);
  5772. if (irp->MdlAddress == NULL) {
  5773. IoFreeIrp(irp);
  5774. (*IoStatus).Information = 0;
  5775. (*IoStatus).Status = STATUS_INSUFFICIENT_RESOURCES;
  5776. return;
  5777. }
  5778. if (method == METHOD_IN_DIRECT) {
  5779. MmProbeAndLockPages(irp->MdlAddress,
  5780. KernelMode,
  5781. IoReadAccess);
  5782. } else if (method == METHOD_OUT_DIRECT) {
  5783. MmProbeAndLockPages(irp->MdlAddress,
  5784. KernelMode,
  5785. IoWriteAccess);
  5786. } else {
  5787. ASSERT(!"If other methods reach here, code is out of date");
  5788. }
  5789. }
  5790. break;
  5791. }
  5792. // case 3
  5793. case METHOD_NEITHER: {
  5794. ASSERT(!"This routine does not support METHOD_NEITHER ioctls");
  5795. IoStatus->Information = 0;
  5796. IoStatus->Status = STATUS_NOT_SUPPORTED;
  5797. return;
  5798. break;
  5799. }
  5800. } // end of switch(method)
  5801. irp->Tail.Overlay.Thread = PsGetCurrentThread();
  5802. //
  5803. // send the irp synchronously
  5804. //
  5805. ClassSendIrpSynchronous(TargetDeviceObject, irp);
  5806. //
  5807. // copy the iostatus block for the caller
  5808. //
  5809. *IoStatus = irp->IoStatus;
  5810. //
  5811. // free any allocated resources
  5812. //
  5813. switch (method) {
  5814. case METHOD_BUFFERED: {
  5815. ASSERT(irp->UserBuffer == Buffer);
  5816. //
  5817. // first copy the buffered result, if any
  5818. // Note that there are no security implications in
  5819. // not checking for success since only drivers can
  5820. // call into this routine anyways...
  5821. //
  5822. if (OutputBufferLength != 0) {
  5823. RtlCopyMemory(Buffer, // irp->UserBuffer
  5824. irp->AssociatedIrp.SystemBuffer,
  5825. OutputBufferLength
  5826. );
  5827. }
  5828. //
  5829. // then free the memory allocated to buffer the io
  5830. //
  5831. if ((InputBufferLength !=0) || (OutputBufferLength != 0)) {
  5832. ExFreePool(irp->AssociatedIrp.SystemBuffer);
  5833. irp->AssociatedIrp.SystemBuffer = NULL;
  5834. }
  5835. break;
  5836. }
  5837. case METHOD_IN_DIRECT:
  5838. case METHOD_OUT_DIRECT: {
  5839. //
  5840. // we alloc a mdl if there is an output buffer specified
  5841. // free it here after unlocking the pages
  5842. //
  5843. if (OutputBufferLength != 0) {
  5844. ASSERT(irp->MdlAddress != NULL);
  5845. MmUnlockPages(irp->MdlAddress);
  5846. IoFreeMdl(irp->MdlAddress);
  5847. irp->MdlAddress = (PMDL) NULL;
  5848. }
  5849. break;
  5850. }
  5851. case METHOD_NEITHER: {
  5852. ASSERT(!"Code is out of date");
  5853. break;
  5854. }
  5855. }
  5856. //
  5857. // we always have allocated an irp. free it here.
  5858. //
  5859. IoFreeIrp(irp);
  5860. irp = (PIRP) NULL;
  5861. //
  5862. // return the io status block's status to the caller
  5863. //
  5864. return;
  5865. } // end ClassSendDeviceIoControlSynchronous()
  5866. /*++////////////////////////////////////////////////////////////////////////////
  5867. ClassForwardIrpSynchronous()
  5868. Routine Description:
  5869. Forwards a given irp to the next lower device object.
  5870. Arguments:
  5871. CommonExtension - the common class extension
  5872. Irp - the request to forward down the stack
  5873. Return Value:
  5874. --*/
  5875. NTSTATUS
  5876. ClassForwardIrpSynchronous(
  5877. IN PCOMMON_DEVICE_EXTENSION CommonExtension,
  5878. IN PIRP Irp
  5879. )
  5880. {
  5881. IoCopyCurrentIrpStackLocationToNext(Irp);
  5882. return ClassSendIrpSynchronous(CommonExtension->LowerDeviceObject, Irp);
  5883. } // end ClassForwardIrpSynchronous()
  5884. /*++////////////////////////////////////////////////////////////////////////////
  5885. ClassSendIrpSynchronous()
  5886. Routine Description:
  5887. This routine sends the given irp to the given device object, and waits for
  5888. it to complete. On debug versions, will print out a debug message and
  5889. optionally assert for "lost" irps based upon classpnp's globals
  5890. Arguments:
  5891. TargetDeviceObject - the device object to handle this irp
  5892. Irp - the request to be sent
  5893. Return Value:
  5894. --*/
  5895. NTSTATUS
  5896. ClassSendIrpSynchronous(
  5897. IN PDEVICE_OBJECT TargetDeviceObject,
  5898. IN PIRP Irp
  5899. )
  5900. {
  5901. KEVENT event;
  5902. NTSTATUS status;
  5903. ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
  5904. ASSERT(TargetDeviceObject != NULL);
  5905. ASSERT(Irp != NULL);
  5906. ASSERT(Irp->StackCount >= TargetDeviceObject->StackSize);
  5907. //
  5908. // ISSUE-2000/02/20-henrygab What if APCs are disabled?
  5909. // May need to enter critical section before IoCallDriver()
  5910. // until the event is hit?
  5911. //
  5912. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  5913. IoSetCompletionRoutine(Irp, ClassSignalCompletion, &event,
  5914. TRUE, TRUE, TRUE);
  5915. status = IoCallDriver(TargetDeviceObject, Irp);
  5916. if (status == STATUS_PENDING) {
  5917. #if DBG
  5918. LARGE_INTEGER timeout;
  5919. timeout.QuadPart = (LONGLONG)(-1 * 10 * 1000 * (LONGLONG)1000 *
  5920. ClasspnpGlobals.SecondsToWaitForIrps);
  5921. do {
  5922. status = KeWaitForSingleObject(&event,
  5923. Executive,
  5924. KernelMode,
  5925. FALSE,
  5926. &timeout);
  5927. if (status == STATUS_TIMEOUT) {
  5928. //
  5929. // This DebugPrint should almost always be investigated by the
  5930. // party who sent the irp and/or the current owner of the irp.
  5931. // Synchronous Irps should not take this long (currently 30
  5932. // seconds) without good reason. This points to a potentially
  5933. // serious problem in the underlying device stack.
  5934. //
  5935. DebugPrint((0, "ClassSendIrpSynchronous: (%p) irp %p did not "
  5936. "complete within %x seconds\n",
  5937. TargetDeviceObject, Irp,
  5938. ClasspnpGlobals.SecondsToWaitForIrps
  5939. ));
  5940. if (ClasspnpGlobals.BreakOnLostIrps != 0) {
  5941. ASSERT(!" - Irp failed to complete within 30 seconds - ");
  5942. }
  5943. }
  5944. } while (status==STATUS_TIMEOUT);
  5945. #else
  5946. KeWaitForSingleObject(&event,
  5947. Executive,
  5948. KernelMode,
  5949. FALSE,
  5950. NULL);
  5951. #endif
  5952. status = Irp->IoStatus.Status;
  5953. }
  5954. return status;
  5955. } // end ClassSendIrpSynchronous()
  5956. /*++////////////////////////////////////////////////////////////////////////////
  5957. ClassGetVpb()
  5958. Routine Description:
  5959. This routine returns the current VPB (Volume Parameter Block) for the
  5960. given device object.
  5961. The Vpb field is only visible in the ntddk.h (not the wdm.h) definition
  5962. of DEVICE_OBJECT; hence this exported function.
  5963. Arguments:
  5964. DeviceObject - the device to get the VPB for
  5965. Return Value:
  5966. the VPB, or NULL if none.
  5967. --*/
  5968. PVPB
  5969. ClassGetVpb(
  5970. IN PDEVICE_OBJECT DeviceObject
  5971. )
  5972. {
  5973. return DeviceObject->Vpb;
  5974. } // end ClassGetVpb()
  5975. /*++
  5976. ISSUE-2000/02/20-henrygab Not documented ClasspAllocateReleaseRequest
  5977. --*/
  5978. NTSTATUS
  5979. ClasspAllocateReleaseRequest(
  5980. IN PDEVICE_OBJECT Fdo
  5981. )
  5982. {
  5983. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  5984. PIO_STACK_LOCATION irpStack;
  5985. KeInitializeSpinLock(&(fdoExtension->ReleaseQueueSpinLock));
  5986. fdoExtension->ReleaseQueueNeeded = FALSE;
  5987. fdoExtension->ReleaseQueueInProgress = FALSE;
  5988. fdoExtension->ReleaseQueueIrpFromPool = FALSE;
  5989. //
  5990. // The class driver is responsible for allocating a properly sized irp,
  5991. // or ClassReleaseQueue will attempt to do it on the first error.
  5992. //
  5993. fdoExtension->ReleaseQueueIrp = NULL;
  5994. //
  5995. // Write length to SRB.
  5996. //
  5997. fdoExtension->ReleaseQueueSrb.Length = sizeof(SCSI_REQUEST_BLOCK);
  5998. return STATUS_SUCCESS;
  5999. } // end ClasspAllocateReleaseRequest()
  6000. /*++
  6001. ISSUE-2000/02/20-henrygab Not documented ClasspFreeReleaseRequest
  6002. --*/
  6003. VOID
  6004. ClasspFreeReleaseRequest(
  6005. IN PDEVICE_OBJECT Fdo
  6006. )
  6007. {
  6008. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  6009. //KIRQL oldIrql;
  6010. ASSERT(fdoExtension->CommonExtension.IsRemoved != NO_REMOVE);
  6011. //
  6012. // free anything the driver allocated
  6013. //
  6014. if (fdoExtension->ReleaseQueueIrp) {
  6015. if (fdoExtension->ReleaseQueueIrpFromPool) {
  6016. ExFreePool(fdoExtension->ReleaseQueueIrp);
  6017. } else {
  6018. IoFreeIrp(fdoExtension->ReleaseQueueIrp);
  6019. }
  6020. fdoExtension->ReleaseQueueIrp = NULL;
  6021. }
  6022. //
  6023. // free anything that we allocated
  6024. //
  6025. if ((fdoExtension->PrivateFdoData) &&
  6026. (fdoExtension->PrivateFdoData->ReleaseQueueIrpAllocated)) {
  6027. ExFreePool(fdoExtension->PrivateFdoData->ReleaseQueueIrp);
  6028. fdoExtension->PrivateFdoData->ReleaseQueueIrpAllocated = FALSE;
  6029. fdoExtension->PrivateFdoData->ReleaseQueueIrp = NULL;
  6030. }
  6031. return;
  6032. } // end ClasspFreeReleaseRequest()
  6033. /*++////////////////////////////////////////////////////////////////////////////
  6034. ClassReleaseQueue()
  6035. Routine Description:
  6036. This routine issues an internal device control command
  6037. to the port driver to release a frozen queue. The call
  6038. is issued asynchronously as ClassReleaseQueue will be invoked
  6039. from the IO completion DPC (and will have no context to
  6040. wait for a synchronous call to complete).
  6041. This routine must be called with the remove lock held.
  6042. Arguments:
  6043. Fdo - The functional device object for the device with the frozen queue.
  6044. Return Value:
  6045. None.
  6046. --*/
  6047. VOID
  6048. ClassReleaseQueue(
  6049. IN PDEVICE_OBJECT Fdo
  6050. )
  6051. {
  6052. ClasspReleaseQueue(Fdo, NULL);
  6053. return;
  6054. } // end ClassReleaseQueue()
  6055. /*++////////////////////////////////////////////////////////////////////////////
  6056. ClasspAllocateReleaseQueueIrp()
  6057. Routine Description:
  6058. This routine allocates the release queue irp held in classpnp's private
  6059. extension. This was added to allow no-memory conditions to be more
  6060. survivable.
  6061. Return Value:
  6062. NT_SUCCESS value.
  6063. Notes:
  6064. Does not grab the spinlock. Should only be called from StartDevice()
  6065. routine. May be called elsewhere for poorly-behaved drivers that cause
  6066. the queue to lockup before the device is started. This should *never*
  6067. occur, since it's illegal to send a request to a non-started PDO. This
  6068. condition is checked for in ClasspReleaseQueue().
  6069. --*/
  6070. NTSTATUS
  6071. ClasspAllocateReleaseQueueIrp(
  6072. PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  6073. )
  6074. {
  6075. KIRQL oldIrql;
  6076. UCHAR lowerStackSize;
  6077. //
  6078. // do an initial check w/o the spinlock
  6079. //
  6080. if (FdoExtension->PrivateFdoData->ReleaseQueueIrpAllocated) {
  6081. return STATUS_SUCCESS;
  6082. }
  6083. lowerStackSize = FdoExtension->CommonExtension.LowerDeviceObject->StackSize;
  6084. //
  6085. // don't allocate one if one is in progress! this means whoever called
  6086. // this routine didn't check if one was in progress.
  6087. //
  6088. ASSERT(!(FdoExtension->ReleaseQueueInProgress));
  6089. FdoExtension->PrivateFdoData->ReleaseQueueIrp =
  6090. ExAllocatePoolWithTag(NonPagedPool,
  6091. IoSizeOfIrp(lowerStackSize),
  6092. CLASS_TAG_RELEASE_QUEUE
  6093. );
  6094. if (FdoExtension->PrivateFdoData->ReleaseQueueIrp == NULL) {
  6095. DebugPrint((0, "ClassPnpStartDevice: Cannot allocate for "
  6096. "release queue irp\n"));
  6097. return STATUS_INSUFFICIENT_RESOURCES;
  6098. }
  6099. IoInitializeIrp(FdoExtension->PrivateFdoData->ReleaseQueueIrp,
  6100. IoSizeOfIrp(lowerStackSize),
  6101. lowerStackSize);
  6102. FdoExtension->PrivateFdoData->ReleaseQueueIrpAllocated = TRUE;
  6103. return STATUS_SUCCESS;
  6104. }
  6105. /*++////////////////////////////////////////////////////////////////////////////
  6106. ClasspReleaseQueue()
  6107. Routine Description:
  6108. This routine issues an internal device control command
  6109. to the port driver to release a frozen queue. The call
  6110. is issued asynchronously as ClassReleaseQueue will be invoked
  6111. from the IO completion DPC (and will have no context to
  6112. wait for a synchronous call to complete).
  6113. This routine must be called with the remove lock held.
  6114. Arguments:
  6115. Fdo - The functional device object for the device with the frozen queue.
  6116. ReleaseQueueIrp - If this irp is supplied then the test to determine whether
  6117. a release queue request is in progress will be ignored.
  6118. The irp provided must be the IRP originally allocated
  6119. for release queue requests (so this parameter can only
  6120. really be provided by the release queue completion
  6121. routine.)
  6122. Return Value:
  6123. None.
  6124. --*/
  6125. VOID
  6126. ClasspReleaseQueue(
  6127. IN PDEVICE_OBJECT Fdo,
  6128. IN PIRP ReleaseQueueIrp OPTIONAL
  6129. )
  6130. {
  6131. PIO_STACK_LOCATION irpStack;
  6132. PIRP irp;
  6133. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
  6134. PDEVICE_OBJECT lowerDevice;
  6135. PSCSI_REQUEST_BLOCK srb;
  6136. KIRQL currentIrql;
  6137. lowerDevice = fdoExtension->CommonExtension.LowerDeviceObject;
  6138. //
  6139. // we raise irql seperately so we're not swapped out or suspended
  6140. // while holding the release queue irp in this routine. this lets
  6141. // us release the spin lock before lowering irql.
  6142. //
  6143. KeRaiseIrql(DISPATCH_LEVEL, &currentIrql);
  6144. KeAcquireSpinLockAtDpcLevel(&(fdoExtension->ReleaseQueueSpinLock));
  6145. //
  6146. // make sure that if they passed us an irp, it matches our allocated irp.
  6147. //
  6148. ASSERT((ReleaseQueueIrp == NULL) ||
  6149. (ReleaseQueueIrp == fdoExtension->PrivateFdoData->ReleaseQueueIrp));
  6150. //
  6151. // ASSERT that we've already allocated this. (should not occur)
  6152. // try to allocate it anyways, then finally bugcheck if
  6153. // there's still no memory...
  6154. //
  6155. ASSERT(fdoExtension->PrivateFdoData->ReleaseQueueIrpAllocated);
  6156. if (!fdoExtension->PrivateFdoData->ReleaseQueueIrpAllocated) {
  6157. ClasspAllocateReleaseQueueIrp(fdoExtension);
  6158. }
  6159. if (!fdoExtension->PrivateFdoData->ReleaseQueueIrpAllocated) {
  6160. KeBugCheckEx(SCSI_DISK_DRIVER_INTERNAL, 0x12, (ULONG_PTR)Fdo, 0x0, 0x0);
  6161. }
  6162. if ((fdoExtension->ReleaseQueueInProgress) && (ReleaseQueueIrp == NULL)) {
  6163. //
  6164. // Someone is already using the irp - just set the flag to indicate that
  6165. // we need to release the queue again.
  6166. //
  6167. fdoExtension->ReleaseQueueNeeded = TRUE;
  6168. KeReleaseSpinLockFromDpcLevel(&(fdoExtension->ReleaseQueueSpinLock));
  6169. KeLowerIrql(currentIrql);
  6170. return;
  6171. }
  6172. //
  6173. // Mark that there is a release queue in progress and drop the spinlock.
  6174. //
  6175. fdoExtension->ReleaseQueueInProgress = TRUE;
  6176. if (ReleaseQueueIrp) {
  6177. irp = ReleaseQueueIrp;
  6178. } else {
  6179. irp = fdoExtension->PrivateFdoData->ReleaseQueueIrp;
  6180. }
  6181. srb = &(fdoExtension->ReleaseQueueSrb);
  6182. KeReleaseSpinLockFromDpcLevel(&(fdoExtension->ReleaseQueueSpinLock));
  6183. ASSERT(irp != NULL);
  6184. irpStack = IoGetNextIrpStackLocation(irp);
  6185. irpStack->MajorFunction = IRP_MJ_SCSI;
  6186. srb->OriginalRequest = irp;
  6187. //
  6188. // Store the SRB address in next stack for port driver.
  6189. //
  6190. irpStack->Parameters.Scsi.Srb = srb;
  6191. //
  6192. // If this device is removable then flush the queue. This will also
  6193. // release it.
  6194. //
  6195. if (TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)){
  6196. srb->Function = SRB_FUNCTION_FLUSH_QUEUE;
  6197. }
  6198. else {
  6199. srb->Function = SRB_FUNCTION_RELEASE_QUEUE;
  6200. }
  6201. ClassAcquireRemoveLock(Fdo, irp);
  6202. IoSetCompletionRoutine(irp,
  6203. ClassReleaseQueueCompletion,
  6204. Fdo,
  6205. TRUE,
  6206. TRUE,
  6207. TRUE);
  6208. IoCallDriver(lowerDevice, irp);
  6209. KeLowerIrql(currentIrql);
  6210. return;
  6211. } // end ClassReleaseQueue()
  6212. /*++////////////////////////////////////////////////////////////////////////////
  6213. ClassReleaseQueueCompletion()
  6214. Routine Description:
  6215. This routine is called when an asynchronous I/O request
  6216. which was issused by the class driver completes. Examples of such requests
  6217. are release queue or START UNIT. This routine releases the queue if
  6218. necessary. It then frees the context and the IRP.
  6219. Arguments:
  6220. DeviceObject - The device object for the logical unit; however since this
  6221. is the top stack location the value is NULL.
  6222. Irp - Supplies a pointer to the Irp to be processed.
  6223. Context - Supplies the context to be used to process this request.
  6224. Return Value:
  6225. None.
  6226. --*/
  6227. NTSTATUS
  6228. ClassReleaseQueueCompletion(
  6229. PDEVICE_OBJECT DeviceObject,
  6230. PIRP Irp,
  6231. PVOID Context
  6232. )
  6233. {
  6234. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
  6235. KIRQL oldIrql;
  6236. BOOLEAN releaseQueueNeeded;
  6237. DeviceObject = Context;
  6238. fdoExtension = DeviceObject->DeviceExtension;
  6239. ClassReleaseRemoveLock(DeviceObject, Irp);
  6240. //
  6241. // Grab the spinlock and clear the release queue in progress flag so others
  6242. // can run. Save (and clear) the state of the release queue needed flag
  6243. // so that we can issue a new release queue outside the spinlock.
  6244. //
  6245. KeAcquireSpinLock(&(fdoExtension->ReleaseQueueSpinLock), &oldIrql);
  6246. releaseQueueNeeded = fdoExtension->ReleaseQueueNeeded;
  6247. fdoExtension->ReleaseQueueNeeded = FALSE;
  6248. fdoExtension->ReleaseQueueInProgress = FALSE;
  6249. KeReleaseSpinLock(&(fdoExtension->ReleaseQueueSpinLock), oldIrql);
  6250. //
  6251. // If we need a release queue then issue one now. Another processor may
  6252. // have already started one in which case we'll try to issue this one after
  6253. // it is done - but we should never recurse more than one deep.
  6254. //
  6255. if(releaseQueueNeeded) {
  6256. ClasspReleaseQueue(DeviceObject, Irp);
  6257. }
  6258. //
  6259. // Indicate the I/O system should stop processing the Irp completion.
  6260. //
  6261. return STATUS_MORE_PROCESSING_REQUIRED;
  6262. } // ClassAsynchronousCompletion()
  6263. /*++////////////////////////////////////////////////////////////////////////////
  6264. ClassAcquireChildLock()
  6265. Routine Description:
  6266. This routine acquires the lock protecting children PDOs. It may be
  6267. acquired recursively by the same thread, but must be release by the
  6268. thread once for each acquisition.
  6269. Arguments:
  6270. FdoExtension - the device whose child list is protected.
  6271. Return Value:
  6272. None
  6273. --*/
  6274. VOID
  6275. ClassAcquireChildLock(
  6276. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  6277. )
  6278. {
  6279. PAGED_CODE();
  6280. if(FdoExtension->ChildLockOwner != KeGetCurrentThread()) {
  6281. KeWaitForSingleObject(&FdoExtension->ChildLock,
  6282. Executive, KernelMode,
  6283. FALSE, NULL);
  6284. ASSERT(FdoExtension->ChildLockOwner == NULL);
  6285. ASSERT(FdoExtension->ChildLockAcquisitionCount == 0);
  6286. FdoExtension->ChildLockOwner = KeGetCurrentThread();
  6287. } else {
  6288. ASSERT(FdoExtension->ChildLockAcquisitionCount != 0);
  6289. }
  6290. FdoExtension->ChildLockAcquisitionCount++;
  6291. return;
  6292. }
  6293. /*++////////////////////////////////////////////////////////////////////////////
  6294. ClassReleaseChildLock() ISSUE-2000/02/18-henrygab - not documented
  6295. Routine Description:
  6296. This routine releases the lock protecting children PDOs. It must be
  6297. called once for each time ClassAcquireChildLock was called.
  6298. Arguments:
  6299. FdoExtension - the device whose child list is protected
  6300. Return Value:
  6301. None.
  6302. --*/
  6303. VOID
  6304. ClassReleaseChildLock(
  6305. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  6306. )
  6307. {
  6308. ASSERT(FdoExtension->ChildLockOwner == KeGetCurrentThread());
  6309. ASSERT(FdoExtension->ChildLockAcquisitionCount != 0);
  6310. FdoExtension->ChildLockAcquisitionCount -= 1;
  6311. if(FdoExtension->ChildLockAcquisitionCount == 0) {
  6312. FdoExtension->ChildLockOwner = NULL;
  6313. KeSetEvent(&FdoExtension->ChildLock, IO_NO_INCREMENT, FALSE);
  6314. }
  6315. return;
  6316. } // end ClassReleaseChildLock(
  6317. /*++////////////////////////////////////////////////////////////////////////////
  6318. ClassAddChild()
  6319. Routine Description:
  6320. This routine will insert a new child into the head of the child list.
  6321. Arguments:
  6322. Parent - the child's parent (contains the head of the list)
  6323. Child - the child to be inserted.
  6324. AcquireLock - whether the child lock should be acquired (TRUE) or whether
  6325. it's already been acquired by or on behalf of the caller
  6326. (FALSE).
  6327. Return Value:
  6328. None.
  6329. --*/
  6330. VOID
  6331. ClassAddChild(
  6332. IN PFUNCTIONAL_DEVICE_EXTENSION Parent,
  6333. IN PPHYSICAL_DEVICE_EXTENSION Child,
  6334. IN BOOLEAN AcquireLock
  6335. )
  6336. {
  6337. if(AcquireLock) {
  6338. ClassAcquireChildLock(Parent);
  6339. }
  6340. #if DBG
  6341. //
  6342. // Make sure this child's not already in the list.
  6343. //
  6344. {
  6345. PPHYSICAL_DEVICE_EXTENSION testChild;
  6346. for (testChild = Parent->CommonExtension.ChildList;
  6347. testChild != NULL;
  6348. testChild = testChild->CommonExtension.ChildList) {
  6349. ASSERT(testChild != Child);
  6350. }
  6351. }
  6352. #endif
  6353. Child->CommonExtension.ChildList = Parent->CommonExtension.ChildList;
  6354. Parent->CommonExtension.ChildList = Child;
  6355. if(AcquireLock) {
  6356. ClassReleaseChildLock(Parent);
  6357. }
  6358. return;
  6359. } // end ClassAddChild()
  6360. /*++////////////////////////////////////////////////////////////////////////////
  6361. ClassRemoveChild()
  6362. Routine Description:
  6363. This routine will remove a child from the child list.
  6364. Arguments:
  6365. Parent - the parent to be removed from.
  6366. Child - the child to be removed or NULL if the first child should be
  6367. removed.
  6368. AcquireLock - whether the child lock should be acquired (TRUE) or whether
  6369. it's already been acquired by or on behalf of the caller
  6370. (FALSE).
  6371. Return Value:
  6372. A pointer to the child which was removed or NULL if no such child could
  6373. be found in the list (or if Child was NULL but the list is empty).
  6374. --*/
  6375. PPHYSICAL_DEVICE_EXTENSION
  6376. ClassRemoveChild(
  6377. IN PFUNCTIONAL_DEVICE_EXTENSION Parent,
  6378. IN PPHYSICAL_DEVICE_EXTENSION Child,
  6379. IN BOOLEAN AcquireLock
  6380. )
  6381. {
  6382. if(AcquireLock) {
  6383. ClassAcquireChildLock(Parent);
  6384. }
  6385. TRY {
  6386. PCOMMON_DEVICE_EXTENSION previousChild = &Parent->CommonExtension;
  6387. //
  6388. // If the list is empty then bail out now.
  6389. //
  6390. if(Parent->CommonExtension.ChildList == NULL) {
  6391. Child = NULL;
  6392. LEAVE;
  6393. }
  6394. //
  6395. // If the caller specified a child then find the child object before
  6396. // it. If none was specified then the FDO is the child object before
  6397. // the one we want to remove.
  6398. //
  6399. if(Child != NULL) {
  6400. //
  6401. // Scan through the child list to find the entry which points to
  6402. // this one.
  6403. //
  6404. do {
  6405. ASSERT(previousChild != &Child->CommonExtension);
  6406. if(previousChild->ChildList == Child) {
  6407. break;
  6408. }
  6409. previousChild = &previousChild->ChildList->CommonExtension;
  6410. } while(previousChild != NULL);
  6411. if(previousChild == NULL) {
  6412. Child = NULL;
  6413. LEAVE;
  6414. }
  6415. }
  6416. //
  6417. // Save the next child away then unlink it from the list.
  6418. //
  6419. Child = previousChild->ChildList;
  6420. previousChild->ChildList = Child->CommonExtension.ChildList;
  6421. Child->CommonExtension.ChildList = NULL;
  6422. } FINALLY {
  6423. if(AcquireLock) {
  6424. ClassReleaseChildLock(Parent);
  6425. }
  6426. }
  6427. return Child;
  6428. } // end ClassRemoveChild()
  6429. /*++
  6430. ISSUE-2000/02/20-henrygab Not documented ClasspRetryRequestDpc
  6431. --*/
  6432. VOID
  6433. ClasspRetryRequestDpc(
  6434. IN PKDPC Dpc,
  6435. IN PDEVICE_OBJECT DeviceObject,
  6436. IN PVOID Arg1,
  6437. IN PVOID Arg2
  6438. )
  6439. {
  6440. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
  6441. PCOMMON_DEVICE_EXTENSION commonExtension;
  6442. PCLASS_PRIVATE_FDO_DATA fdoData;
  6443. PCLASS_RETRY_INFO retryList;
  6444. KIRQL irql;
  6445. commonExtension = DeviceObject->DeviceExtension;
  6446. ASSERT(commonExtension->IsFdo);
  6447. fdoExtension = DeviceObject->DeviceExtension;
  6448. fdoData = fdoExtension->PrivateFdoData;
  6449. KeAcquireSpinLock(&fdoData->Retry.Lock, &irql);
  6450. {
  6451. LARGE_INTEGER now;
  6452. KeQueryTickCount(&now);
  6453. //
  6454. // if CurrentTick is less than now
  6455. // fire another DPC
  6456. // else
  6457. // retry entire list
  6458. // endif
  6459. //
  6460. if (now.QuadPart < fdoData->Retry.Tick.QuadPart) {
  6461. ClasspRetryDpcTimer(fdoData);
  6462. retryList = NULL;
  6463. } else {
  6464. retryList = fdoData->Retry.ListHead;
  6465. fdoData->Retry.ListHead = NULL;
  6466. fdoData->Retry.Delta.QuadPart = (LONGLONG)0;
  6467. fdoData->Retry.Tick.QuadPart = (LONGLONG)0;
  6468. }
  6469. }
  6470. KeReleaseSpinLock(&fdoData->Retry.Lock, irql);
  6471. while (retryList != NULL) {
  6472. PIRP irp;
  6473. irp = CONTAINING_RECORD(retryList, IRP, Tail.Overlay.DriverContext[0]);
  6474. DebugPrint((ClassDebugDelayedRetry, "ClassRetry: -- %p\n", irp));
  6475. retryList = retryList->Next;
  6476. #if DBG
  6477. irp->Tail.Overlay.DriverContext[0] = ULongToPtr(0xdddddddd); // invalidate data
  6478. irp->Tail.Overlay.DriverContext[1] = ULongToPtr(0xdddddddd); // invalidate data
  6479. irp->Tail.Overlay.DriverContext[2] = ULongToPtr(0xdddddddd); // invalidate data
  6480. irp->Tail.Overlay.DriverContext[3] = ULongToPtr(0xdddddddd); // invalidate data
  6481. #endif
  6482. IoCallDriver(commonExtension->LowerDeviceObject, irp);
  6483. }
  6484. return;
  6485. } // end ClasspRetryRequestDpc()
  6486. /*++
  6487. ISSUE-2000/02/20-henrygab Not documented ClassRetryRequest
  6488. --*/
  6489. VOID
  6490. ClassRetryRequest(
  6491. IN PDEVICE_OBJECT SelfDeviceObject,
  6492. IN PIRP Irp,
  6493. IN LARGE_INTEGER TimeDelta100ns // in 100ns units
  6494. )
  6495. {
  6496. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
  6497. PCLASS_PRIVATE_FDO_DATA fdoData;
  6498. PCLASS_RETRY_INFO retryInfo;
  6499. PCLASS_RETRY_INFO *previousNext;
  6500. LARGE_INTEGER delta;
  6501. KIRQL irql;
  6502. //
  6503. // this checks we aren't destroying irps
  6504. //
  6505. ASSERT(sizeof(CLASS_RETRY_INFO) <= (4*sizeof(PVOID)));
  6506. fdoExtension = SelfDeviceObject->DeviceExtension;
  6507. fdoData = fdoExtension->PrivateFdoData;
  6508. if (!fdoExtension->CommonExtension.IsFdo) {
  6509. //
  6510. // this debug print/assertion should ALWAYS be investigated.
  6511. // ClassRetryRequest can currently only be used by FDO's
  6512. //
  6513. DebugPrint((ClassDebugError, "ClassRetryRequestEx: LOST IRP %p\n", Irp));
  6514. ASSERT(!"ClassRetryRequestEx Called From PDO? LOST IRP");
  6515. return;
  6516. }
  6517. if (TimeDelta100ns.QuadPart < 0) {
  6518. ASSERT(!"ClassRetryRequest - must use positive delay");
  6519. TimeDelta100ns.QuadPart *= -1;
  6520. }
  6521. //
  6522. // prepare what we can out of the loop
  6523. //
  6524. retryInfo = (PCLASS_RETRY_INFO)(&Irp->Tail.Overlay.DriverContext[0]);
  6525. RtlZeroMemory(retryInfo, sizeof(CLASS_RETRY_INFO));
  6526. delta.QuadPart = (TimeDelta100ns.QuadPart / fdoData->Retry.Granularity);
  6527. if (TimeDelta100ns.QuadPart % fdoData->Retry.Granularity) {
  6528. delta.QuadPart ++; // round up to next tick
  6529. }
  6530. if (delta.QuadPart == (LONGLONG)0) {
  6531. delta.QuadPart = MINIMUM_RETRY_UNITS;
  6532. }
  6533. //
  6534. // now determine if we should fire another DPC or not
  6535. //
  6536. KeAcquireSpinLock(&fdoData->Retry.Lock, &irql);
  6537. //
  6538. // always add request to the list
  6539. //
  6540. retryInfo->Next = fdoData->Retry.ListHead;
  6541. fdoData->Retry.ListHead = retryInfo;
  6542. if (fdoData->Retry.Delta.QuadPart == (LONGLONG)0) {
  6543. DebugPrint((ClassDebugDelayedRetry, "ClassRetry: +++ %p\n", Irp));
  6544. //
  6545. // must be exactly one item on list
  6546. //
  6547. ASSERT(fdoData->Retry.ListHead != NULL);
  6548. ASSERT(fdoData->Retry.ListHead->Next == NULL);
  6549. //
  6550. // if currentDelta is zero, always fire a DPC
  6551. //
  6552. KeQueryTickCount(&fdoData->Retry.Tick);
  6553. fdoData->Retry.Tick.QuadPart += delta.QuadPart;
  6554. fdoData->Retry.Delta.QuadPart = delta.QuadPart;
  6555. ClasspRetryDpcTimer(fdoData);
  6556. } else if (delta.QuadPart > fdoData->Retry.Delta.QuadPart) {
  6557. //
  6558. // if delta is greater than the list's current delta,
  6559. // increase the DPC handling time by difference
  6560. // and update the delta to new larger value
  6561. // allow the DPC to re-fire itself if needed
  6562. //
  6563. DebugPrint((ClassDebugDelayedRetry, "ClassRetry: ++ %p\n", Irp));
  6564. //
  6565. // must be at least two items on list
  6566. //
  6567. ASSERT(fdoData->Retry.ListHead != NULL);
  6568. ASSERT(fdoData->Retry.ListHead->Next != NULL);
  6569. fdoData->Retry.Tick.QuadPart -= fdoData->Retry.Delta.QuadPart;
  6570. fdoData->Retry.Tick.QuadPart += delta.QuadPart;
  6571. fdoData->Retry.Delta.QuadPart = delta.QuadPart;
  6572. } else {
  6573. //
  6574. // just inserting it on the list was enough
  6575. //
  6576. DebugPrint((ClassDebugDelayedRetry, "ClassRetry: ++ %p\n", Irp));
  6577. }
  6578. KeReleaseSpinLock(&fdoData->Retry.Lock, irql);
  6579. } // end ClassRetryRequest()
  6580. /*++
  6581. ISSUE-2000/02/20-henrygab Not documented ClasspRetryDpcTimer
  6582. --*/
  6583. VOID
  6584. ClasspRetryDpcTimer(
  6585. IN PCLASS_PRIVATE_FDO_DATA FdoData
  6586. )
  6587. {
  6588. LARGE_INTEGER fire;
  6589. ASSERT(FdoData->Retry.Tick.QuadPart != (LONGLONG)0);
  6590. ASSERT(FdoData->Retry.ListHead != NULL); // never fire an empty list
  6591. //
  6592. // fire == (CurrentTick - now) * (100ns per tick)
  6593. //
  6594. // NOTE: Overflow is nearly impossible and is ignored here
  6595. //
  6596. KeQueryTickCount(&fire);
  6597. fire.QuadPart = FdoData->Retry.Tick.QuadPart - fire.QuadPart;
  6598. fire.QuadPart *= FdoData->Retry.Granularity;
  6599. //
  6600. // fire is now multiples of 100ns until should fire the timer.
  6601. // if timer should already have expired, or would fire too quickly,
  6602. // fire it in some arbitrary number of ticks to prevent infinitely
  6603. // recursing.
  6604. //
  6605. if (fire.QuadPart < MINIMUM_RETRY_UNITS) {
  6606. fire.QuadPart = MINIMUM_RETRY_UNITS;
  6607. }
  6608. DebugPrint((ClassDebugDelayedRetry,
  6609. "ClassRetry: ======= %I64x ticks\n",
  6610. fire.QuadPart));
  6611. //
  6612. // must use negative to specify relative time to fire
  6613. //
  6614. fire.QuadPart = fire.QuadPart * ((LONGLONG)-1);
  6615. //
  6616. // set the timer, since this is the first addition
  6617. //
  6618. KeSetTimerEx(&FdoData->Retry.Timer, fire, 0, &FdoData->Retry.Dpc);
  6619. return;
  6620. } // end ClasspRetryDpcTimer()
  6621. NTSTATUS
  6622. ClasspInitializeHotplugInfo(
  6623. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  6624. )
  6625. {
  6626. PCLASS_PRIVATE_FDO_DATA fdoData = FdoExtension->PrivateFdoData;
  6627. DEVICE_REMOVAL_POLICY deviceRemovalPolicy;
  6628. NTSTATUS status;
  6629. ULONG resultLength = 0;
  6630. ULONG writeCacheOverride;
  6631. PAGED_CODE();
  6632. //
  6633. // start with some default settings
  6634. //
  6635. RtlZeroMemory(&(fdoData->HotplugInfo), sizeof(STORAGE_HOTPLUG_INFO));
  6636. //
  6637. // set the size (aka version)
  6638. //
  6639. fdoData->HotplugInfo.Size = sizeof(STORAGE_HOTPLUG_INFO);
  6640. //
  6641. // set if the device has removable media
  6642. //
  6643. if (FdoExtension->DeviceDescriptor->RemovableMedia) {
  6644. fdoData->HotplugInfo.MediaRemovable = TRUE;
  6645. } else {
  6646. fdoData->HotplugInfo.MediaRemovable = FALSE;
  6647. }
  6648. //
  6649. // this refers to devices which, for reasons not yet understood,
  6650. // do not fail PREVENT_MEDIA_REMOVAL requests even though they
  6651. // have no way to lock the media into the drive. this allows
  6652. // the filesystems to turn off delayed-write caching for these
  6653. // devices as well.
  6654. //
  6655. if (TEST_FLAG(FdoExtension->PrivateFdoData->HackFlags,
  6656. FDO_HACK_CANNOT_LOCK_MEDIA)) {
  6657. fdoData->HotplugInfo.MediaHotplug = TRUE;
  6658. } else {
  6659. fdoData->HotplugInfo.MediaHotplug = FALSE;
  6660. }
  6661. //
  6662. // Look into the registry to see if the user has chosen
  6663. // to override the default setting for the removal policy
  6664. //
  6665. RtlZeroMemory(&deviceRemovalPolicy, sizeof(DEVICE_REMOVAL_POLICY));
  6666. ClassGetDeviceParameter(FdoExtension,
  6667. CLASSP_REG_SUBKEY_NAME,
  6668. CLASSP_REG_REMOVAL_POLICY_VALUE_NAME,
  6669. (PULONG)&deviceRemovalPolicy);
  6670. if (deviceRemovalPolicy == 0)
  6671. {
  6672. //
  6673. // Query the default removal policy from the kernel
  6674. //
  6675. status = IoGetDeviceProperty(FdoExtension->LowerPdo,
  6676. DevicePropertyRemovalPolicy,
  6677. sizeof(DEVICE_REMOVAL_POLICY),
  6678. (PVOID)&deviceRemovalPolicy,
  6679. &resultLength);
  6680. if (!NT_SUCCESS(status))
  6681. {
  6682. return status;
  6683. }
  6684. if (resultLength != sizeof(DEVICE_REMOVAL_POLICY))
  6685. {
  6686. return STATUS_UNSUCCESSFUL;
  6687. }
  6688. }
  6689. //
  6690. // use this info to set the DeviceHotplug setting
  6691. // don't rely on DeviceCapabilities, since it can't properly
  6692. // determine device relations, etc. let the kernel figure this
  6693. // stuff out instead.
  6694. //
  6695. if (deviceRemovalPolicy == RemovalPolicyExpectSurpriseRemoval) {
  6696. fdoData->HotplugInfo.DeviceHotplug = TRUE;
  6697. } else {
  6698. fdoData->HotplugInfo.DeviceHotplug = FALSE;
  6699. }
  6700. //
  6701. // this refers to the *filesystem* caching, but has to be included
  6702. // here since it's a per-device setting. this may change to be
  6703. // stored by the system in the future.
  6704. //
  6705. writeCacheOverride = FALSE;
  6706. ClassGetDeviceParameter(FdoExtension,
  6707. CLASSP_REG_SUBKEY_NAME,
  6708. CLASSP_REG_WRITE_CACHE_VALUE_NAME,
  6709. &writeCacheOverride);
  6710. if (writeCacheOverride) {
  6711. fdoData->HotplugInfo.WriteCacheEnableOverride = TRUE;
  6712. } else {
  6713. fdoData->HotplugInfo.WriteCacheEnableOverride = FALSE;
  6714. }
  6715. return STATUS_SUCCESS;
  6716. }
  6717. VOID
  6718. ClasspScanForClassHacks(
  6719. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  6720. IN ULONG_PTR Data
  6721. )
  6722. {
  6723. PAGED_CODE();
  6724. //
  6725. // remove invalid flags and save
  6726. //
  6727. CLEAR_FLAG(Data, FDO_HACK_INVALID_FLAGS);
  6728. SET_FLAG(FdoExtension->PrivateFdoData->HackFlags, Data);
  6729. return;
  6730. }
  6731. VOID
  6732. ClasspScanForSpecialInRegistry(
  6733. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  6734. )
  6735. {
  6736. HANDLE deviceParameterHandle; // device instance key
  6737. HANDLE classParameterHandle; // classpnp subkey
  6738. OBJECT_ATTRIBUTES objectAttributes;
  6739. UNICODE_STRING subkeyName;
  6740. NTSTATUS status;
  6741. //
  6742. // seeded in the ENUM tree by ClassInstaller
  6743. //
  6744. ULONG deviceHacks;
  6745. RTL_QUERY_REGISTRY_TABLE queryTable[2]; // null terminated array
  6746. PAGED_CODE();
  6747. deviceParameterHandle = NULL;
  6748. classParameterHandle = NULL;
  6749. deviceHacks = 0;
  6750. status = IoOpenDeviceRegistryKey(FdoExtension->LowerPdo,
  6751. PLUGPLAY_REGKEY_DEVICE,
  6752. KEY_WRITE,
  6753. &deviceParameterHandle
  6754. );
  6755. if (!NT_SUCCESS(status)) {
  6756. goto cleanupScanForSpecial;
  6757. }
  6758. RtlInitUnicodeString(&subkeyName, CLASSP_REG_SUBKEY_NAME);
  6759. InitializeObjectAttributes(&objectAttributes,
  6760. &subkeyName,
  6761. OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
  6762. deviceParameterHandle,
  6763. NULL
  6764. );
  6765. status = ZwOpenKey( &classParameterHandle,
  6766. KEY_READ,
  6767. &objectAttributes
  6768. );
  6769. if (!NT_SUCCESS(status)) {
  6770. goto cleanupScanForSpecial;
  6771. }
  6772. //
  6773. // Zero out the memory
  6774. //
  6775. RtlZeroMemory(&queryTable[0], 2*sizeof(RTL_QUERY_REGISTRY_TABLE));
  6776. //
  6777. // Setup the structure to read
  6778. //
  6779. queryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
  6780. queryTable[0].Name = CLASSP_REG_HACK_VALUE_NAME;
  6781. queryTable[0].EntryContext = &deviceHacks;
  6782. queryTable[0].DefaultType = REG_DWORD;
  6783. queryTable[0].DefaultData = &deviceHacks;
  6784. queryTable[0].DefaultLength = 0;
  6785. //
  6786. // read values
  6787. //
  6788. status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE,
  6789. (PWSTR)classParameterHandle,
  6790. &queryTable[0],
  6791. NULL,
  6792. NULL
  6793. );
  6794. if (!NT_SUCCESS(status)) {
  6795. goto cleanupScanForSpecial;
  6796. }
  6797. //
  6798. // remove unknown values and save...
  6799. //
  6800. KdPrintEx((DPFLTR_CLASSPNP_ID, DPFLTR_ERROR_LEVEL,
  6801. "Classpnp => ScanForSpecial: HackFlags %#08x\n",
  6802. deviceHacks));
  6803. CLEAR_FLAG(deviceHacks, FDO_HACK_INVALID_FLAGS);
  6804. SET_FLAG(FdoExtension->PrivateFdoData->HackFlags, deviceHacks);
  6805. cleanupScanForSpecial:
  6806. if (deviceParameterHandle) {
  6807. ZwClose(deviceParameterHandle);
  6808. }
  6809. if (classParameterHandle) {
  6810. ZwClose(classParameterHandle);
  6811. }
  6812. //
  6813. // we should modify the system hive to include another key for us to grab
  6814. // settings from. in this case: Classpnp\HackFlags
  6815. //
  6816. // the use of a DWORD value for the HackFlags allows 32 hacks w/o
  6817. // significant use of the registry, and also reduces OEM exposure.
  6818. //
  6819. // definition of bit flags:
  6820. // 0x00000001 -- Device succeeds PREVENT_MEDIUM_REMOVAL, but
  6821. // cannot actually prevent removal.
  6822. // 0x00000002 -- Device hard-hangs or times out for GESN requests.
  6823. // 0xfffffffc -- Currently reserved, may be used later.
  6824. //
  6825. return;
  6826. }