PageRenderTime 95ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 2ms

/drivers/storage/classpnp/class.c

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