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

3703 lines
114 KiB

  1. /*++
  2. Copyright (C) Microsoft Corporation, 1991 - 1999
  3. Module Name:
  4. autorun.c
  5. Abstract:
  6. Code for support of media change detection in the class driver
  7. Environment:
  8. kernel mode only
  9. Notes:
  10. Revision History:
  11. --*/
  12. #include "classp.h"
  13. #include "debug.h"
  14. #define GESN_TIMEOUT_VALUE (0x4)
  15. #define GESN_BUFFER_SIZE (0x8)
  16. #define GESN_DEVICE_BUSY_LOWER_THRESHOLD_MS (200)
  17. #define MAXIMUM_IMMEDIATE_MCN_RETRIES (0x20)
  18. #define MCN_REG_SUBKEY_NAME (L"MediaChangeNotification")
  19. #define MCN_REG_AUTORUN_DISABLE_INSTANCE_NAME (L"AlwaysDisableMCN")
  20. #define MCN_REG_AUTORUN_ENABLE_INSTANCE_NAME (L"AlwaysEnableMCN")
  21. GUID StoragePredictFailureEventGuid = WMI_STORAGE_PREDICT_FAILURE_EVENT_GUID;
  22. //
  23. // Only send polling irp when device is fully powered up and a
  24. // power down irp is not in progress.
  25. //
  26. // NOTE: This helps close a window in time where a polling irp could cause
  27. // a drive to spin up right after it has powered down. The problem is
  28. // that SCSIPORT, ATAPI and SBP2 will be in the process of powering
  29. // down (which may take a few seconds), but won't know that. It would
  30. // then get a polling irp which will be put into its queue since it
  31. // the disk isn't powered down yet. Once the disk is powered down it
  32. // will find the polling irp in the queue and then power up the
  33. // device to do the poll. They do not want to check if the polling
  34. // irp has the SRB_NO_KEEP_AWAKE flag here since it is in a critical
  35. // path and would slow down all I/Os. A better way to fix this
  36. // would be to serialize the polling and power down irps so that
  37. // only one of them is sent to the device at a time.
  38. //
  39. #define ClasspCanSendPollingIrp(fdoExtension) \
  40. ((fdoExtension->DevicePowerState == PowerDeviceD0) && \
  41. (! fdoExtension->PowerDownInProgress) )
  42. BOOLEAN
  43. ClasspIsMediaChangeDisabledDueToHardwareLimitation(
  44. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  45. IN PUNICODE_STRING RegistryPath
  46. );
  47. NTSTATUS
  48. ClasspMediaChangeDeviceInstanceOverride(
  49. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  50. OUT PBOOLEAN Enabled
  51. );
  52. BOOLEAN
  53. ClasspIsMediaChangeDisabledForClass(
  54. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  55. IN PUNICODE_STRING RegistryPath
  56. );
  57. VOID
  58. ClasspSetMediaChangeStateEx(
  59. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  60. IN MEDIA_CHANGE_DETECTION_STATE NewState,
  61. IN BOOLEAN Wait,
  62. IN BOOLEAN KnownStateChange // can ignore oldstate == unknown
  63. );
  64. NTSTATUS
  65. ClasspMediaChangeRegistryCallBack(
  66. IN PWSTR ValueName,
  67. IN ULONG ValueType,
  68. IN PVOID ValueData,
  69. IN ULONG ValueLength,
  70. IN PVOID Context,
  71. IN PVOID EntryContext
  72. );
  73. VOID
  74. ClasspSendMediaStateIrp(
  75. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  76. IN PMEDIA_CHANGE_DETECTION_INFO Info,
  77. IN ULONG CountDown
  78. );
  79. VOID
  80. ClasspFailurePredict(
  81. IN PDEVICE_OBJECT DeviceObject,
  82. IN PFAILURE_PREDICTION_INFO Info
  83. );
  84. NTSTATUS
  85. ClasspInitializePolling(
  86. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  87. IN BOOLEAN AllowDriveToSleep
  88. );
  89. #if ALLOC_PRAGMA
  90. #pragma alloc_text(PAGE, ClassInitializeMediaChangeDetection)
  91. #pragma alloc_text(PAGE, ClassEnableMediaChangeDetection)
  92. #pragma alloc_text(PAGE, ClassDisableMediaChangeDetection)
  93. #pragma alloc_text(PAGE, ClassCleanupMediaChangeDetection)
  94. #pragma alloc_text(PAGE, ClasspMediaChangeRegistryCallBack)
  95. #pragma alloc_text(PAGE, ClasspInitializePolling)
  96. #pragma alloc_text(PAGE, ClasspIsMediaChangeDisabledDueToHardwareLimitation)
  97. #pragma alloc_text(PAGE, ClasspMediaChangeDeviceInstanceOverride)
  98. #pragma alloc_text(PAGE, ClasspIsMediaChangeDisabledForClass)
  99. #pragma alloc_text(PAGE, ClassSetFailurePredictionPoll)
  100. #pragma alloc_text(PAGE, ClasspDisableTimer)
  101. #pragma alloc_text(PAGE, ClasspEnableTimer)
  102. #endif
  103. // ISSUE -- make this public?
  104. VOID
  105. ClassSendEjectionNotification(
  106. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  107. )
  108. {
  109. //
  110. // For post-NT5.1 work, need to move EjectSynchronizationEvent
  111. // to be a MUTEX so we can attempt to grab it here and benefit
  112. // from deadlock detection. This will allow checking if the media
  113. // has been locked by programs before broadcasting these events.
  114. // (what's the point of broadcasting if the media is not locked?)
  115. //
  116. // This would currently only be a slight optimization. For post-NT5.1,
  117. // it would allow us to send a single PERSISTENT_PREVENT to MMC devices,
  118. // thereby cleaning up a lot of the ejection code. Then, when the
  119. // ejection request occured, we could see if any locks for the media
  120. // existed. if locked, broadcast. if not, we send the eject irp.
  121. //
  122. //
  123. // for now, just always broadcast. make this a public routine,
  124. // so class drivers can add special hacks to broadcast this for their
  125. // non-MMC-compliant devices also from sense codes.
  126. //
  127. DBGTRACE(ClassDebugTrace, ("ClassSendEjectionNotification: media EJECT_REQUEST"));
  128. ClasspSendNotification(FdoExtension,
  129. &GUID_IO_MEDIA_EJECT_REQUEST,
  130. 0,
  131. NULL);
  132. return;
  133. }
  134. VOID
  135. ClasspSendNotification(
  136. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  137. IN const GUID * Guid,
  138. IN ULONG ExtraDataSize,
  139. IN PVOID ExtraData
  140. )
  141. {
  142. PTARGET_DEVICE_CUSTOM_NOTIFICATION notification;
  143. ULONG requiredSize;
  144. requiredSize =
  145. (sizeof(TARGET_DEVICE_CUSTOM_NOTIFICATION) - sizeof(UCHAR)) +
  146. ExtraDataSize;
  147. if (requiredSize > 0x0000ffff) {
  148. // MAX_USHORT, max total size for these events!
  149. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugWarning,
  150. "Error sending event: size too large! (%x)\n",
  151. requiredSize));
  152. return;
  153. }
  154. notification = ExAllocatePoolWithTag(NonPagedPool,
  155. requiredSize,
  156. 'oNcS');
  157. //
  158. // if none allocated, exit
  159. //
  160. if (notification == NULL) {
  161. return;
  162. }
  163. //
  164. // Prepare and send the request!
  165. //
  166. RtlZeroMemory(notification, requiredSize);
  167. notification->Version = 1;
  168. notification->Size = (USHORT)(requiredSize);
  169. notification->FileObject = NULL;
  170. notification->NameBufferOffset = -1;
  171. notification->Event = *Guid;
  172. RtlCopyMemory(notification->CustomDataBuffer, ExtraData, ExtraDataSize);
  173. IoReportTargetDeviceChangeAsynchronous(FdoExtension->LowerPdo,
  174. notification,
  175. NULL, NULL);
  176. ExFreePool(notification);
  177. notification = NULL;
  178. return;
  179. }
  180. NTSTATUS
  181. ClasspInterpretGesnData(
  182. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  183. IN PNOTIFICATION_EVENT_STATUS_HEADER Header,
  184. OUT PBOOLEAN ResendImmediately
  185. )
  186. /*++
  187. Routine Description:
  188. This routine will interpret the data returned for a GESN command, and
  189. (if appropriate) set the media change event, and broadcast the
  190. appropriate events to user mode for applications who care.
  191. Arguments:
  192. FdoExtension - the device
  193. DataBuffer - the resulting data from a GESN event.
  194. requires at least EIGHT valid bytes (header == 4, data == 4)
  195. ResendImmediately - whether or not to immediately resend the request.
  196. this should be FALSE if there was no event, FALSE if the reported
  197. event was of the DEVICE BUSY class, else true.
  198. Return Value:
  199. STATUS_SUCCESS if successful, an error code otherwise
  200. Notes:
  201. DataBuffer must be at least four bytes of valid data (header == 4 bytes),
  202. and have at least eight bytes of allocated memory (all events == 4 bytes).
  203. The call to StartNextPacket may occur before this routine is completed.
  204. the operational change notifications are informational in nature, and
  205. while useful, are not neccessary to ensure proper operation. For example,
  206. if the device morphs to no longer supporting WRITE commands, all further
  207. write commands will fail. There exists a small timing window wherein
  208. IOCTL_IS_DISK_WRITABLE may be called and get an incorrect response. If
  209. a device supports software write protect, it is expected that the
  210. application can handle such a case.
  211. NOTE: perhaps setting the updaterequired byte to one should be done here.
  212. if so, it relies upon the setting of a 32-byte value to be an atomic
  213. operation. unfortunately, there is no simple way to notify a class driver
  214. which wants to know that the device behavior requires updating.
  215. Not ready events may be sent every second. For example, if we were
  216. to minimize the number of asynchronous notifications, an application may
  217. register just after a large busy time was reported. This would then
  218. prevent the application from knowing the device was busy until some
  219. arbitrarily chosen timeout has occurred. Also, the GESN request would
  220. have to still occur, since it checks for non-busy events (such as user
  221. keybutton presses and media change events) as well. The specification
  222. states that the lower-numered events get reported first, so busy events,
  223. while repeating, will only be reported when all other events have been
  224. cleared from the device.
  225. --*/
  226. {
  227. PMEDIA_CHANGE_DETECTION_INFO info;
  228. LONG dataLength;
  229. LONG requiredLength;
  230. NTSTATUS status = STATUS_SUCCESS;
  231. info = FdoExtension->MediaChangeDetectionInfo;
  232. //
  233. // note: don't allocate anything in this routine so that we can
  234. // always just 'return'.
  235. //
  236. *ResendImmediately = FALSE;
  237. if (Header->NEA) {
  238. return status;
  239. }
  240. if (Header->NotificationClass == NOTIFICATION_NO_CLASS_EVENTS) {
  241. return status;
  242. }
  243. //
  244. // HACKHACK - REF #0001
  245. // This loop is only taken initially, due to the inability to reliably
  246. // auto-detect drives that report events correctly at boot. When we
  247. // detect this behavior during the normal course of running, we will
  248. // disable the hack, allowing more efficient use of the system. This
  249. // should occur "nearly" instantly, as the drive should have multiple
  250. // events queue'd (ie. power, morphing, media).
  251. //
  252. if (info->Gesn.HackEventMask) {
  253. //
  254. // all events use the low four bytes of zero to indicate
  255. // that there was no change in status.
  256. //
  257. UCHAR thisEvent = Header->ClassEventData[0] & 0xf;
  258. UCHAR lowestSetBit;
  259. UCHAR thisEventBit = (1 << Header->NotificationClass);
  260. if (!TEST_FLAG(info->Gesn.EventMask, thisEventBit)) {
  261. //
  262. // The drive is reporting an event that wasn't requested
  263. //
  264. return STATUS_DEVICE_PROTOCOL_ERROR;
  265. }
  266. //
  267. // some bit magic here... this results in the lowest set bit only
  268. //
  269. lowestSetBit = info->Gesn.EventMask;
  270. lowestSetBit &= (info->Gesn.EventMask - 1);
  271. lowestSetBit ^= (info->Gesn.EventMask);
  272. if (thisEventBit != lowestSetBit) {
  273. //
  274. // HACKHACK - REF #0001
  275. // the first time we ever see an event set that is not the lowest
  276. // set bit in the request (iow, highest priority), we know that the
  277. // hack is no longer required, as the device is ignoring "no change"
  278. // events when a real event is waiting in the other requested queues.
  279. //
  280. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  281. "Classpnp => GESN::NONE: Compliant drive found, "
  282. "removing GESN hack (%x, %x)\n",
  283. thisEventBit, info->Gesn.EventMask));
  284. info->Gesn.HackEventMask = FALSE;
  285. } else if (thisEvent == 0) { // NOTIFICATION_*_EVENT_NO_CHANGE
  286. //
  287. // HACKHACK - REF #0001
  288. // note: this hack prevents poorly implemented firmware from constantly
  289. // returning "No Event". we do this by cycling through the
  290. // supported list of events here.
  291. //
  292. SET_FLAG(info->Gesn.NoChangeEventMask, thisEventBit);
  293. CLEAR_FLAG(info->Gesn.EventMask, thisEventBit);
  294. //
  295. // if we have cycled through all supported event types, then
  296. // we need to reset the events we are asking about. else we
  297. // want to resend this request immediately in case there was
  298. // another event pending.
  299. //
  300. if (info->Gesn.EventMask == 0) {
  301. info->Gesn.EventMask = info->Gesn.NoChangeEventMask;
  302. info->Gesn.NoChangeEventMask = 0;
  303. } else {
  304. *ResendImmediately = TRUE;
  305. }
  306. return status;
  307. }
  308. } // end if (info->Gesn.HackEventMask)
  309. dataLength =
  310. (Header->EventDataLength[0] << 8) |
  311. (Header->EventDataLength[1] & 0xff);
  312. dataLength -= 2;
  313. requiredLength = 4; // all events are four bytes
  314. if (dataLength < requiredLength) {
  315. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugWarning,
  316. "Classpnp => GESN returned only %x bytes data for fdo %p\n",
  317. dataLength, FdoExtension->DeviceObject));
  318. return STATUS_DEVICE_PROTOCOL_ERROR;
  319. }
  320. if (dataLength != requiredLength) {
  321. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugWarning,
  322. "Classpnp => GESN returned too many (%x) bytes data for fdo %p\n",
  323. dataLength, FdoExtension->DeviceObject));
  324. dataLength = 4;
  325. }
  326. if ((Header->ClassEventData[0] & 0xf) == 0)
  327. {
  328. // a zero event is a "no change event, so do not retry
  329. return status;
  330. }
  331. // because a event other than "no change" occurred,
  332. // we should immediately resend this request.
  333. *ResendImmediately = TRUE;
  334. /*
  335. ClasspSendNotification(FdoExtension,
  336. &GUID_IO_GENERIC_GESN_EVENT,
  337. sizeof(NOTIFICATION_EVENT_STATUS_HEADER) + dataLength,
  338. Header)
  339. */
  340. switch (Header->NotificationClass) {
  341. case NOTIFICATION_OPERATIONAL_CHANGE_CLASS_EVENTS: { // 0x01
  342. PNOTIFICATION_OPERATIONAL_STATUS opChangeInfo =
  343. (PNOTIFICATION_OPERATIONAL_STATUS)(Header->ClassEventData);
  344. ULONG event;
  345. if (opChangeInfo->OperationalEvent == NOTIFICATION_OPERATIONAL_EVENT_CHANGE_REQUESTED) {
  346. break;
  347. }
  348. event = (opChangeInfo->Operation[0] << 8) |
  349. (opChangeInfo->Operation[1] ) ;
  350. if ((event == NOTIFICATION_OPERATIONAL_OPCODE_FEATURE_ADDED) |
  351. (event == NOTIFICATION_OPERATIONAL_OPCODE_FEATURE_CHANGE)) {
  352. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  353. "Classpnp => GESN says features added/changedfor fdo %p\n",
  354. FdoExtension->DeviceObject));
  355. // don't notify that new media arrived, just set the
  356. // DO_VERIFY to force a FS reload.
  357. if (TEST_FLAG(FdoExtension->DeviceObject->Characteristics,
  358. FILE_REMOVABLE_MEDIA) &&
  359. (ClassGetVpb(FdoExtension->DeviceObject) != NULL) &&
  360. (ClassGetVpb(FdoExtension->DeviceObject)->Flags & VPB_MOUNTED)
  361. ) {
  362. SET_FLAG(FdoExtension->DeviceObject->Flags, DO_VERIFY_VOLUME);
  363. }
  364. //
  365. // If there is a class specific error handler, call it with
  366. // a "fake" media change error in case it needs to update
  367. // internal structures as though a media change occurred.
  368. //
  369. if (FdoExtension->CommonExtension.DevInfo->ClassError != NULL) {
  370. SCSI_REQUEST_BLOCK srb = {0};
  371. SENSE_DATA sense = {0};
  372. NTSTATUS tempStatus;
  373. BOOLEAN retry;
  374. tempStatus = STATUS_MEDIA_CHANGED;
  375. retry = FALSE;
  376. srb.CdbLength = 6;
  377. srb.Length = sizeof(SCSI_REQUEST_BLOCK);
  378. srb.SrbStatus = SRB_STATUS_AUTOSENSE_VALID | SRB_STATUS_ERROR;
  379. srb.SenseInfoBuffer = &sense;
  380. srb.SenseInfoBufferLength = sizeof(SENSE_DATA);
  381. sense.AdditionalSenseLength = sizeof(SENSE_DATA) -
  382. RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseLength);
  383. sense.SenseKey = SCSI_SENSE_UNIT_ATTENTION;
  384. sense.AdditionalSenseCode = SCSI_ADSENSE_MEDIUM_CHANGED;
  385. FdoExtension->CommonExtension.DevInfo->ClassError(FdoExtension->DeviceObject,
  386. &srb,
  387. &tempStatus,
  388. &retry);
  389. } // end class error handler
  390. }
  391. break;
  392. }
  393. case NOTIFICATION_EXTERNAL_REQUEST_CLASS_EVENTS: { // 0x3
  394. PNOTIFICATION_EXTERNAL_STATUS externalInfo =
  395. (PNOTIFICATION_EXTERNAL_STATUS)(Header->ClassEventData);
  396. DEVICE_EVENT_EXTERNAL_REQUEST externalData = {0};
  397. //
  398. // unfortunately, due to time constraints, we will only notify
  399. // about keys being pressed, and not released. this makes keys
  400. // single-function, but simplifies the code significantly.
  401. //
  402. if (externalInfo->ExternalEvent != NOTIFICATION_EXTERNAL_EVENT_BUTTON_DOWN) {
  403. break;
  404. }
  405. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  406. "Classpnp => GESN::EXTERNAL: Event: %x Status %x Req %x\n",
  407. externalInfo->ExternalEvent, externalInfo->ExternalStatus,
  408. (externalInfo->Request[0] >> 8) | externalInfo->Request[1]
  409. ));
  410. externalData.Version = 1;
  411. externalData.DeviceClass = 0;
  412. externalData.ButtonStatus = externalInfo->ExternalEvent;
  413. externalData.Request =
  414. (externalInfo->Request[0] << 8) |
  415. (externalInfo->Request[1] & 0xff);
  416. KeQuerySystemTime(&(externalData.SystemTime));
  417. externalData.SystemTime.QuadPart *= (LONGLONG)KeQueryTimeIncrement();
  418. DBGTRACE(ClassDebugTrace, ("ClasspInterpretGesnData: media DEVICE_EXTERNAL_REQUEST"));
  419. ClasspSendNotification(FdoExtension,
  420. &GUID_IO_DEVICE_EXTERNAL_REQUEST,
  421. sizeof(DEVICE_EVENT_EXTERNAL_REQUEST),
  422. &externalData);
  423. return status;
  424. }
  425. case NOTIFICATION_MEDIA_STATUS_CLASS_EVENTS: { // 0x4
  426. PNOTIFICATION_MEDIA_STATUS mediaInfo =
  427. (PNOTIFICATION_MEDIA_STATUS)(Header->ClassEventData);
  428. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  429. "Classpnp => GESN::MEDIA: Event: %x Status %x\n",
  430. mediaInfo->MediaEvent, mediaInfo->MediaStatus));
  431. if ((mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_NEW_MEDIA) ||
  432. (mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_MEDIA_CHANGE)) {
  433. if (TEST_FLAG(FdoExtension->DeviceObject->Characteristics,
  434. FILE_REMOVABLE_MEDIA) &&
  435. (ClassGetVpb(FdoExtension->DeviceObject) != NULL) &&
  436. (ClassGetVpb(FdoExtension->DeviceObject)->Flags & VPB_MOUNTED)
  437. ) {
  438. SET_FLAG(FdoExtension->DeviceObject->Flags, DO_VERIFY_VOLUME);
  439. }
  440. InterlockedIncrement(&FdoExtension->MediaChangeCount);
  441. ClasspSetMediaChangeStateEx(FdoExtension,
  442. MediaPresent,
  443. FALSE,
  444. TRUE);
  445. } else if (mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_MEDIA_REMOVAL) {
  446. ClasspSetMediaChangeStateEx(FdoExtension,
  447. MediaNotPresent,
  448. FALSE,
  449. TRUE);
  450. } else if (mediaInfo->MediaEvent == NOTIFICATION_MEDIA_EVENT_EJECT_REQUEST) {
  451. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugError,
  452. "Classpnp => GESN Ejection request received!\n"));
  453. ClassSendEjectionNotification(FdoExtension);
  454. }
  455. break;
  456. }
  457. case NOTIFICATION_DEVICE_BUSY_CLASS_EVENTS: { // lowest priority events...
  458. PNOTIFICATION_BUSY_STATUS busyInfo =
  459. (PNOTIFICATION_BUSY_STATUS)(Header->ClassEventData);
  460. DEVICE_EVENT_BECOMING_READY busyData = {0};
  461. //
  462. // NOTE: we never actually need to immediately retry for these
  463. // events: if one exists, the device is busy, and if not,
  464. // we still don't want to retry.
  465. //
  466. *ResendImmediately = FALSE;
  467. //
  468. // else we want to report the approximated time till it's ready.
  469. //
  470. busyData.Version = 1;
  471. busyData.Reason = busyInfo->DeviceBusyStatus;
  472. busyData.Estimated100msToReady = (busyInfo->Time[0] << 8) |
  473. (busyInfo->Time[1] & 0xff);
  474. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  475. "Classpnp => GESN::BUSY: Event: %x Status %x Time %x\n",
  476. busyInfo->DeviceBusyEvent, busyInfo->DeviceBusyStatus,
  477. busyData.Estimated100msToReady
  478. ));
  479. //
  480. // Ignore the notification if the time is small
  481. //
  482. if (busyData.Estimated100msToReady < GESN_DEVICE_BUSY_LOWER_THRESHOLD_MS) {
  483. break;
  484. }
  485. DBGTRACE(ClassDebugTrace, ("ClasspInterpretGesnData: media BECOMING_READY"));
  486. ClasspSendNotification(FdoExtension,
  487. &GUID_IO_DEVICE_BECOMING_READY,
  488. sizeof(DEVICE_EVENT_BECOMING_READY),
  489. &busyData);
  490. break;
  491. }
  492. default: {
  493. break;
  494. }
  495. } // end switch on notification class
  496. return status;
  497. }
  498. /*++////////////////////////////////////////////////////////////////////////////
  499. ClasspInternalSetMediaChangeState()
  500. Routine Description:
  501. This routine will (if appropriate) set the media change event for the
  502. device. The event will be set if the media state is changed and
  503. media change events are enabled. Otherwise the media state will be
  504. tracked but the event will not be set.
  505. This routine will lock out the other media change routines if possible
  506. but if not a media change notification may be lost after the enable has
  507. been completed.
  508. Arguments:
  509. FdoExtension - the device
  510. MediaPresent - indicates whether the device has media inserted into it
  511. (TRUE) or not (FALSE).
  512. Return Value:
  513. none
  514. --*/
  515. VOID
  516. ClasspInternalSetMediaChangeState(
  517. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  518. IN MEDIA_CHANGE_DETECTION_STATE NewState,
  519. IN BOOLEAN KnownStateChange // can ignore oldstate == unknown
  520. )
  521. {
  522. #if DBG
  523. PUCHAR states[] = {"Unknown", "Present", "Not Present", "Unavailable"};
  524. #endif
  525. MEDIA_CHANGE_DETECTION_STATE oldMediaState;
  526. PMEDIA_CHANGE_DETECTION_INFO info = FdoExtension->MediaChangeDetectionInfo;
  527. CLASS_MEDIA_CHANGE_CONTEXT mcnContext;
  528. NTSTATUS status;
  529. ASSERT((NewState >= MediaUnknown) && (NewState <= MediaUnavailable));
  530. if(info == NULL) {
  531. return;
  532. }
  533. oldMediaState = InterlockedExchange(
  534. (PLONG)(&info->MediaChangeDetectionState),
  535. (LONG)NewState);
  536. if((oldMediaState == MediaUnknown) && (!KnownStateChange)) {
  537. //
  538. // The media was in an indeterminate state before - don't notify for
  539. // this change.
  540. //
  541. DebugPrint((ClassDebugMCN,
  542. "ClassSetMediaChangeState: State was unknown - this may "
  543. "not be a change\n"));
  544. return;
  545. } else if(oldMediaState == NewState) {
  546. //
  547. // Media is in the same state it was before.
  548. //
  549. return;
  550. }
  551. if(info->MediaChangeDetectionDisableCount != 0) {
  552. DBGTRACE(ClassDebugMCN,
  553. ("ClassSetMediaChangeState: MCN not enabled, state "
  554. "changed from %s to %s\n",
  555. states[oldMediaState], states[NewState]));
  556. return;
  557. }
  558. DBGTRACE(ClassDebugMCN,
  559. ("ClassSetMediaChangeState: State change from %s to %s\n",
  560. states[oldMediaState], states[NewState]));
  561. //
  562. // make the data useful -- it used to always be zero.
  563. //
  564. mcnContext.MediaChangeCount = FdoExtension->MediaChangeCount;
  565. mcnContext.NewState = NewState;
  566. if (NewState == MediaPresent) {
  567. DBGTRACE(ClassDebugTrace, ("ClasspInternalSetMediaChangeState: media ARRIVAL"));
  568. ClasspSendNotification(FdoExtension,
  569. &GUID_IO_MEDIA_ARRIVAL,
  570. sizeof(CLASS_MEDIA_CHANGE_CONTEXT),
  571. &mcnContext);
  572. }
  573. else if ((NewState == MediaNotPresent) || (NewState == MediaUnavailable)) {
  574. DBGTRACE(ClassDebugTrace, ("ClasspInternalSetMediaChangeState: media REMOVAL"));
  575. ClasspSendNotification(FdoExtension,
  576. &GUID_IO_MEDIA_REMOVAL,
  577. sizeof(CLASS_MEDIA_CHANGE_CONTEXT),
  578. &mcnContext);
  579. } else {
  580. //
  581. // Don't notify of changed going to unknown.
  582. //
  583. return;
  584. }
  585. return;
  586. } // end ClasspInternalSetMediaChangeState()
  587. /*++////////////////////////////////////////////////////////////////////////////
  588. ClassSetMediaChangeState()
  589. Routine Description:
  590. This routine will (if appropriate) set the media change event for the
  591. device. The event will be set if the media state is changed and
  592. media change events are enabled. Otherwise the media state will be
  593. tracked but the event will not be set.
  594. This routine will lock out the other media change routines if possible
  595. but if not a media change notification may be lost after the enable has
  596. been completed.
  597. Arguments:
  598. FdoExtension - the device
  599. MediaPresent - indicates whether the device has media inserted into it
  600. (TRUE) or not (FALSE).
  601. Wait - indicates whether the function should wait until it can acquire
  602. the synchronization lock or not.
  603. Return Value:
  604. none
  605. --*/
  606. VOID
  607. ClasspSetMediaChangeStateEx(
  608. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  609. IN MEDIA_CHANGE_DETECTION_STATE NewState,
  610. IN BOOLEAN Wait,
  611. IN BOOLEAN KnownStateChange // can ignore oldstate == unknown
  612. )
  613. {
  614. PMEDIA_CHANGE_DETECTION_INFO info = FdoExtension->MediaChangeDetectionInfo;
  615. LARGE_INTEGER zero;
  616. NTSTATUS status;
  617. DBGTRACE(ClassDebugMCN, ("> ClasspSetMediaChangeStateEx"));
  618. //
  619. // Reset SMART status on media removal as the old status may not be
  620. // valid when there is no media in the device or when new media is
  621. // inserted.
  622. //
  623. if (NewState == MediaNotPresent) {
  624. FdoExtension->FailurePredicted = FALSE;
  625. FdoExtension->FailureReason = 0;
  626. }
  627. zero.QuadPart = 0;
  628. if(info == NULL) {
  629. return;
  630. }
  631. status = KeWaitForMutexObject(&info->MediaChangeMutex,
  632. Executive,
  633. KernelMode,
  634. FALSE,
  635. ((Wait == TRUE) ? NULL : &zero));
  636. if(status == STATUS_TIMEOUT) {
  637. //
  638. // Someone else is in the process of setting the media state
  639. //
  640. DBGWARN(("ClasspSetMediaChangeStateEx - timed out waiting for mutex"));
  641. return;
  642. }
  643. //
  644. // Change the media present state and signal an event, if applicable
  645. //
  646. ClasspInternalSetMediaChangeState(FdoExtension, NewState, KnownStateChange);
  647. KeReleaseMutex(&info->MediaChangeMutex, FALSE);
  648. DBGTRACE(ClassDebugMCN, ("< ClasspSetMediaChangeStateEx"));
  649. return;
  650. } // end ClassSetMediaChangeStateEx()
  651. VOID
  652. ClassSetMediaChangeState(
  653. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  654. IN MEDIA_CHANGE_DETECTION_STATE NewState,
  655. IN BOOLEAN Wait
  656. )
  657. {
  658. ClasspSetMediaChangeStateEx(FdoExtension, NewState, Wait, FALSE);
  659. return;
  660. }
  661. /*++////////////////////////////////////////////////////////////////////////////
  662. ClasspMediaChangeDetectionCompletion()
  663. Routine Description:
  664. This routine handles the completion of the test unit ready irps used to
  665. determine if the media has changed. If the media has changed, this code
  666. signals the named event to wake up other system services that react to
  667. media change (aka AutoPlay).
  668. Arguments:
  669. DeviceObject - the object for the completion
  670. Irp - the IRP being completed
  671. Context - the SRB from the IRP
  672. Return Value:
  673. NTSTATUS
  674. --*/
  675. NTSTATUS
  676. ClasspMediaChangeDetectionCompletion(
  677. PDEVICE_OBJECT DeviceObject,
  678. PIRP Irp,
  679. PSCSI_REQUEST_BLOCK Srb
  680. )
  681. {
  682. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
  683. PCLASS_PRIVATE_FDO_DATA fdoData;
  684. PMEDIA_CHANGE_DETECTION_INFO info;
  685. PIO_STACK_LOCATION nextIrpStack;
  686. NTSTATUS status;
  687. BOOLEAN retryImmediately = FALSE;
  688. //
  689. // Since the class driver created this request, it's completion routine
  690. // will not get a valid device object handed in. Use the one in the
  691. // irp stack instead
  692. //
  693. DeviceObject = IoGetCurrentIrpStackLocation(Irp)->DeviceObject;
  694. fdoExtension = DeviceObject->DeviceExtension;
  695. fdoData = fdoExtension->PrivateFdoData;
  696. info = fdoExtension->MediaChangeDetectionInfo;
  697. ASSERT(info->MediaChangeIrp != NULL);
  698. ASSERT(!TEST_FLAG(Srb->SrbStatus, SRB_STATUS_QUEUE_FROZEN));
  699. DBGTRACE(ClassDebugMCN, ("> ClasspMediaChangeDetectionCompletion: Device %p completed MCN irp %p.", DeviceObject, Irp));
  700. /*
  701. * HACK for IoMega 2GB Jaz drive:
  702. * This drive spins down on its own to preserve the media.
  703. * When spun down, TUR fails with 2/4/0 (SCSI_SENSE_NOT_READY/SCSI_ADSENSE_LUN_NOT_READY/?).
  704. * ClassInterpretSenseInfo would then call ClassSendStartUnit to spin the media up, which defeats the
  705. * purpose of the spindown.
  706. * So in this case, make this into a successful TUR.
  707. * This allows the drive to stay spun down until it is actually accessed again.
  708. * (If the media were actually removed, TUR would fail with 2/3a/0 ).
  709. * This hack only applies to drives with the CAUSE_NOT_REPORTABLE_HACK bit set; this
  710. * is set by disk.sys when HackCauseNotReportableHack is set for the drive in its BadControllers list.
  711. */
  712. if ((SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_SUCCESS) &&
  713. TEST_FLAG(fdoExtension->ScanForSpecialFlags, CLASS_SPECIAL_CAUSE_NOT_REPORTABLE_HACK) &&
  714. (Srb->SenseInfoBufferLength >= RTL_SIZEOF_THROUGH_FIELD(SENSE_DATA, AdditionalSenseCode))){
  715. PSENSE_DATA senseData = Srb->SenseInfoBuffer;
  716. if ((senseData->SenseKey == SCSI_SENSE_NOT_READY) &&
  717. (senseData->AdditionalSenseCode == SCSI_ADSENSE_LUN_NOT_READY)){
  718. Srb->SrbStatus = SRB_STATUS_SUCCESS;
  719. }
  720. }
  721. //
  722. // use ClassInterpretSenseInfo() to check for media state, and also
  723. // to call ClassError() with correct parameters.
  724. //
  725. status = STATUS_SUCCESS;
  726. if (SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_SUCCESS) {
  727. DBGTRACE(ClassDebugMCN, ("ClasspMediaChangeDetectionCompletion - failed - srb status=%s, sense=%s/%s/%s.", DBGGETSRBSTATUSSTR(Srb), DBGGETSENSECODESTR(Srb), DBGGETADSENSECODESTR(Srb), DBGGETADSENSEQUALIFIERSTR(Srb)));
  728. ClassInterpretSenseInfo(DeviceObject,
  729. Srb,
  730. IRP_MJ_SCSI,
  731. 0,
  732. 0,
  733. &status,
  734. NULL);
  735. }
  736. else {
  737. fdoData->LoggedTURFailureSinceLastIO = FALSE;
  738. if (!info->Gesn.Supported) {
  739. DBGTRACE(ClassDebugMCN, ("ClasspMediaChangeDetectionCompletion - succeeded and GESN NOT supported, setting MediaPresent."));
  740. //
  741. // success != media for GESN case
  742. //
  743. ClassSetMediaChangeState(fdoExtension, MediaPresent, FALSE);
  744. }
  745. else {
  746. DBGTRACE(ClassDebugMCN, ("ClasspMediaChangeDetectionCompletion - succeeded (GESN supported)."));
  747. }
  748. }
  749. if (info->Gesn.Supported) {
  750. if (status == STATUS_DATA_OVERRUN) {
  751. DBGTRACE(ClassDebugMCN, ("ClasspMediaChangeDetectionCompletion - Overrun"));
  752. status = STATUS_SUCCESS;
  753. }
  754. if (!NT_SUCCESS(status)) {
  755. DBGTRACE(ClassDebugMCN, ("ClasspMediaChangeDetectionCompletion: GESN failed with status %x", status));
  756. } else {
  757. //
  758. // for GESN, need to interpret the results of the data.
  759. // this may also require an immediate retry
  760. //
  761. if (Irp->IoStatus.Information == 8 ) {
  762. ClasspInterpretGesnData(fdoExtension,
  763. (PVOID)info->Gesn.Buffer,
  764. &retryImmediately);
  765. }
  766. } // end of NT_SUCCESS(status)
  767. } // end of Info->Gesn.Supported
  768. //
  769. // free port-allocated sense buffer, if any.
  770. //
  771. if (PORT_ALLOCATED_SENSE(fdoExtension, Srb)) {
  772. FREE_PORT_ALLOCATED_SENSE_BUFFER(fdoExtension, Srb);
  773. }
  774. //
  775. // Remember the IRP and SRB for use the next time.
  776. //
  777. ASSERT(IoGetNextIrpStackLocation(Irp));
  778. IoGetNextIrpStackLocation(Irp)->Parameters.Scsi.Srb = Srb;
  779. //
  780. // Reset the MCN timer.
  781. //
  782. ClassResetMediaChangeTimer(fdoExtension);
  783. //
  784. // run a sanity check to make sure we're not recursing continuously
  785. //
  786. if (retryImmediately) {
  787. info->MediaChangeRetryCount++;
  788. if (info->MediaChangeRetryCount > MAXIMUM_IMMEDIATE_MCN_RETRIES) {
  789. ASSERT(!"Recursing too often in MCN?");
  790. info->MediaChangeRetryCount = 0;
  791. retryImmediately = FALSE;
  792. }
  793. } else {
  794. info->MediaChangeRetryCount = 0;
  795. }
  796. //
  797. // release the remove lock....
  798. //
  799. {
  800. UCHAR uniqueValue;
  801. ClassAcquireRemoveLock(DeviceObject, (PIRP)(&uniqueValue));
  802. ClassReleaseRemoveLock(DeviceObject, Irp);
  803. //
  804. // set the irp as not in use
  805. //
  806. {
  807. volatile LONG irpWasInUse;
  808. irpWasInUse = InterlockedCompareExchange(&info->MediaChangeIrpInUse, 0, 1);
  809. #if _MSC_FULL_VER != 13009111 // This compiler always takes the wrong path here.
  810. ASSERT(irpWasInUse);
  811. #endif
  812. }
  813. //
  814. // now send it again before we release our last remove lock
  815. //
  816. if (retryImmediately) {
  817. ClasspSendMediaStateIrp(fdoExtension, info, 0);
  818. }
  819. else {
  820. DBGTRACE(ClassDebugMCN, ("ClasspMediaChangeDetectionCompletion - not retrying immediately"));
  821. }
  822. //
  823. // release the temporary remove lock
  824. //
  825. ClassReleaseRemoveLock(DeviceObject, (PIRP)(&uniqueValue));
  826. }
  827. DBGTRACE(ClassDebugMCN, ("< ClasspMediaChangeDetectionCompletion"));
  828. return STATUS_MORE_PROCESSING_REQUIRED;
  829. }
  830. /*++////////////////////////////////////////////////////////////////////////////
  831. ClasspSendTestUnitIrp() - ISSUE-2000/02/20-henrygab - not documented
  832. Routine Description:
  833. This routine
  834. Arguments:
  835. DeviceObject -
  836. Irp -
  837. Return Value:
  838. --*/
  839. PIRP
  840. ClasspPrepareMcnIrp(
  841. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  842. IN PMEDIA_CHANGE_DETECTION_INFO Info,
  843. IN BOOLEAN UseGesn
  844. )
  845. {
  846. PSCSI_REQUEST_BLOCK srb;
  847. PIO_STACK_LOCATION irpStack;
  848. PIO_STACK_LOCATION nextIrpStack;
  849. NTSTATUS status;
  850. PCDB cdb;
  851. PIRP irp;
  852. PVOID buffer;
  853. //
  854. // Setup the IRP to perform a test unit ready.
  855. //
  856. irp = Info->MediaChangeIrp;
  857. ASSERT(irp);
  858. if (irp == NULL) {
  859. return NULL;
  860. }
  861. //
  862. // don't keep sending this if the device is being removed.
  863. //
  864. status = ClassAcquireRemoveLock(FdoExtension->DeviceObject, irp);
  865. if (status == REMOVE_COMPLETE) {
  866. ASSERT(status != REMOVE_COMPLETE);
  867. return NULL;
  868. }
  869. else if (status == REMOVE_PENDING) {
  870. ClassReleaseRemoveLock(FdoExtension->DeviceObject, irp);
  871. return NULL;
  872. }
  873. else {
  874. ASSERT(status == NO_REMOVE);
  875. }
  876. IoReuseIrp(irp, STATUS_NOT_SUPPORTED);
  877. /*
  878. * For the driver that creates an IRP, there is no 'current' stack location.
  879. * Step down one IRP stack location so that the extra top one
  880. * becomes our 'current' one.
  881. */
  882. IoSetNextIrpStackLocation(irp);
  883. /*
  884. * Cache our device object in the extra top IRP stack location
  885. * so we have it in our completion routine.
  886. */
  887. irpStack = IoGetCurrentIrpStackLocation(irp);
  888. irpStack->DeviceObject = FdoExtension->DeviceObject;
  889. //
  890. // If the irp is sent down when the volume needs to be
  891. // verified, CdRomUpdateGeometryCompletion won't complete
  892. // it since it's not associated with a thread. Marking
  893. // it to override the verify causes it always be sent
  894. // to the port driver
  895. //
  896. irpStack->Flags |= SL_OVERRIDE_VERIFY_VOLUME;
  897. nextIrpStack = IoGetNextIrpStackLocation(irp);
  898. nextIrpStack->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
  899. nextIrpStack->Parameters.Scsi.Srb = &(Info->MediaChangeSrb);
  900. //
  901. // Prepare the SRB for execution.
  902. //
  903. srb = nextIrpStack->Parameters.Scsi.Srb;
  904. buffer = Info->SenseBuffer;
  905. RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK));
  906. RtlZeroMemory(buffer, SENSE_BUFFER_SIZE);
  907. srb->QueueTag = SP_UNTAGGED;
  908. srb->QueueAction = SRB_SIMPLE_TAG_REQUEST;
  909. srb->Length = sizeof(SCSI_REQUEST_BLOCK);
  910. srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
  911. srb->SenseInfoBuffer = buffer;
  912. srb->SrbStatus = 0;
  913. srb->ScsiStatus = 0;
  914. srb->OriginalRequest = irp;
  915. srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE;
  916. srb->SrbFlags = FdoExtension->SrbFlags;
  917. SET_FLAG(srb->SrbFlags, Info->SrbFlags);
  918. srb->TimeOutValue = FdoExtension->TimeOutValue * 2;
  919. if (srb->TimeOutValue == 0) {
  920. if (FdoExtension->TimeOutValue == 0) {
  921. KdPrintEx((DPFLTR_CLASSPNP_ID, DPFLTR_ERROR_LEVEL,
  922. "ClassSendTestUnitIrp: FdoExtension->TimeOutValue "
  923. "is set to zero?! -- resetting to 10\n"));
  924. srb->TimeOutValue = 10 * 2; // reasonable default
  925. } else {
  926. KdPrintEx((DPFLTR_CLASSPNP_ID, DPFLTR_ERROR_LEVEL,
  927. "ClassSendTestUnitIrp: Someone set "
  928. "srb->TimeOutValue to zero?! -- resetting to %x\n",
  929. FdoExtension->TimeOutValue * 2));
  930. srb->TimeOutValue = FdoExtension->TimeOutValue * 2;
  931. }
  932. }
  933. if (!UseGesn) {
  934. srb->CdbLength = 6;
  935. srb->DataTransferLength = 0;
  936. SET_FLAG(srb->SrbFlags, SRB_FLAGS_NO_DATA_TRANSFER);
  937. nextIrpStack->Parameters.DeviceIoControl.IoControlCode =
  938. IOCTL_SCSI_EXECUTE_NONE;
  939. srb->DataBuffer = NULL;
  940. srb->DataTransferLength = 0;
  941. irp->MdlAddress = NULL;
  942. cdb = (PCDB) &srb->Cdb[0];
  943. cdb->CDB6GENERIC.OperationCode = SCSIOP_TEST_UNIT_READY;
  944. } else {
  945. ASSERT(Info->Gesn.Buffer);
  946. srb->TimeOutValue = GESN_TIMEOUT_VALUE; // much shorter timeout for GESN
  947. srb->CdbLength = 10;
  948. SET_FLAG(srb->SrbFlags, SRB_FLAGS_DATA_IN);
  949. nextIrpStack->Parameters.DeviceIoControl.IoControlCode =
  950. IOCTL_SCSI_EXECUTE_IN;
  951. srb->DataBuffer = Info->Gesn.Buffer;
  952. srb->DataTransferLength = Info->Gesn.BufferSize;
  953. irp->MdlAddress = Info->Gesn.Mdl;
  954. cdb = (PCDB) &srb->Cdb[0];
  955. cdb->GET_EVENT_STATUS_NOTIFICATION.OperationCode =
  956. SCSIOP_GET_EVENT_STATUS;
  957. cdb->GET_EVENT_STATUS_NOTIFICATION.Immediate = 1;
  958. cdb->GET_EVENT_STATUS_NOTIFICATION.EventListLength[0] =
  959. (UCHAR)((Info->Gesn.BufferSize) >> 8);
  960. cdb->GET_EVENT_STATUS_NOTIFICATION.EventListLength[1] =
  961. (UCHAR)((Info->Gesn.BufferSize) & 0xff);
  962. cdb->GET_EVENT_STATUS_NOTIFICATION.NotificationClassRequest =
  963. Info->Gesn.EventMask;
  964. }
  965. IoSetCompletionRoutine(irp,
  966. ClasspMediaChangeDetectionCompletion,
  967. srb,
  968. TRUE,
  969. TRUE,
  970. TRUE);
  971. return irp;
  972. }
  973. /*++////////////////////////////////////////////////////////////////////////////
  974. ClasspSendMediaStateIrp() - ISSUE-2000/02/20-henrygab - not documented
  975. Routine Description:
  976. This routine
  977. Arguments:
  978. DeviceObject -
  979. Irp -
  980. Return Value:
  981. --*/
  982. VOID
  983. ClasspSendMediaStateIrp(
  984. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  985. IN PMEDIA_CHANGE_DETECTION_INFO Info,
  986. IN ULONG CountDown
  987. )
  988. {
  989. BOOLEAN requestPending = FALSE;
  990. LONG irpInUse;
  991. LARGE_INTEGER zero;
  992. NTSTATUS status;
  993. DBGTRACE(ClassDebugMCN, ("> ClasspSendMediaStateIrp"));
  994. if (((FdoExtension->CommonExtension.CurrentState != IRP_MN_START_DEVICE) ||
  995. (FdoExtension->DevicePowerState != PowerDeviceD0)
  996. ) &&
  997. (!Info->MediaChangeIrpLost)) {
  998. //
  999. // the device may be stopped, powered down, or otherwise queueing io,
  1000. // so should not timeout the autorun irp (yet) -- set to zero ticks.
  1001. // scattered code relies upon this to not prematurely "lose" an
  1002. // autoplay irp that was queued.
  1003. //
  1004. Info->MediaChangeIrpTimeInUse = 0;
  1005. }
  1006. //
  1007. // if the irp is not in use, mark it as such.
  1008. //
  1009. irpInUse = InterlockedCompareExchange(&Info->MediaChangeIrpInUse, 1, 0);
  1010. if (irpInUse) {
  1011. LONG timeInUse;
  1012. timeInUse = InterlockedIncrement(&Info->MediaChangeIrpTimeInUse);
  1013. DebugPrint((ClassDebugMCN, "ClasspSendMediaStateIrp: irp in use for "
  1014. "%x seconds when synchronizing for MCD\n", timeInUse));
  1015. if (Info->MediaChangeIrpLost == FALSE) {
  1016. if (timeInUse > MEDIA_CHANGE_TIMEOUT_TIME) {
  1017. //
  1018. // currently set to five minutes. hard to imagine a drive
  1019. // taking that long to spin up.
  1020. //
  1021. DebugPrint((ClassDebugError,
  1022. "CdRom%d: Media Change Notification has lost "
  1023. "it's irp and doesn't know where to find it. "
  1024. "Leave it alone and it'll come home dragging "
  1025. "it's stack behind it.\n",
  1026. FdoExtension->DeviceNumber));
  1027. Info->MediaChangeIrpLost = TRUE;
  1028. }
  1029. }
  1030. DBGTRACE(ClassDebugMCN, ("< ClasspSendMediaStateIrp - irpInUse"));
  1031. return;
  1032. }
  1033. TRY {
  1034. if (Info->MediaChangeDetectionDisableCount != 0) {
  1035. DebugPrint((ClassDebugTrace, "ClassCheckMediaState: device %p has "
  1036. " detection disabled \n", FdoExtension->DeviceObject));
  1037. LEAVE;
  1038. }
  1039. if (FdoExtension->DevicePowerState != PowerDeviceD0) {
  1040. if (TEST_FLAG(Info->SrbFlags, SRB_FLAGS_NO_KEEP_AWAKE)) {
  1041. DebugPrint((ClassDebugMCN,
  1042. "ClassCheckMediaState: device %p is powered "
  1043. "down and flags are set to let it sleep\n",
  1044. FdoExtension->DeviceObject));
  1045. ClassResetMediaChangeTimer(FdoExtension);
  1046. LEAVE;
  1047. }
  1048. //
  1049. // NOTE: we don't increment the time in use until our power state
  1050. // changes above. this way, we won't "lose" the autoplay irp.
  1051. // it's up to the lower driver to determine if powering up is a
  1052. // good idea.
  1053. //
  1054. DebugPrint((ClassDebugMCN,
  1055. "ClassCheckMediaState: device %p needs to powerup "
  1056. "to handle this io (may take a few extra seconds).\n",
  1057. FdoExtension->DeviceObject));
  1058. }
  1059. Info->MediaChangeIrpTimeInUse = 0;
  1060. Info->MediaChangeIrpLost = FALSE;
  1061. if (CountDown == 0) {
  1062. PIRP irp;
  1063. DebugPrint((ClassDebugTrace,
  1064. "ClassCheckMediaState: timer expired\n"));
  1065. if (Info->MediaChangeDetectionDisableCount != 0) {
  1066. DebugPrint((ClassDebugTrace,
  1067. "ClassCheckMediaState: detection disabled\n"));
  1068. LEAVE;
  1069. }
  1070. //
  1071. // Prepare the IRP for the test unit ready
  1072. //
  1073. irp = ClasspPrepareMcnIrp(FdoExtension,
  1074. Info,
  1075. Info->Gesn.Supported);
  1076. //
  1077. // Issue the request.
  1078. //
  1079. DebugPrint((ClassDebugTrace,
  1080. "ClasspSendMediaStateIrp: Device %p getting TUR "
  1081. " irp %p\n", FdoExtension->DeviceObject, irp));
  1082. if (irp == NULL) {
  1083. LEAVE;
  1084. }
  1085. //
  1086. // note: if we send it to the class dispatch routines, there is
  1087. // a timing window here (since they grab the remove lock)
  1088. // where we'd be removed. ELIMINATE the window by grabbing
  1089. // the lock ourselves above and sending it to the lower
  1090. // device object directly or to the device's StartIo
  1091. // routine (which doesn't acquire the lock).
  1092. //
  1093. requestPending = TRUE;
  1094. DBGTRACE(ClassDebugMCN, (" ClasspSendMediaStateIrp - calling IoCallDriver."));
  1095. IoCallDriver(FdoExtension->CommonExtension.LowerDeviceObject, irp);
  1096. }
  1097. } FINALLY {
  1098. if(requestPending == FALSE) {
  1099. irpInUse = InterlockedCompareExchange(&Info->MediaChangeIrpInUse, 0, 1);
  1100. #if _MSC_FULL_VER != 13009111 // This compiler always takes the wrong path here.
  1101. ASSERT(irpInUse);
  1102. #endif
  1103. }
  1104. }
  1105. DBGTRACE(ClassDebugMCN, ("< ClasspSendMediaStateIrp"));
  1106. return;
  1107. } // end ClasspSendMediaStateIrp()
  1108. /*++////////////////////////////////////////////////////////////////////////////
  1109. ClassCheckMediaState()
  1110. Routine Description:
  1111. This routine is called by the class driver to test for a media change
  1112. condition and/or poll for disk failure prediction. It should be called
  1113. from the class driver's IO timer routine once per second.
  1114. Arguments:
  1115. FdoExtension - the device extension
  1116. Return Value:
  1117. none
  1118. --*/
  1119. VOID
  1120. ClassCheckMediaState(
  1121. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  1122. )
  1123. {
  1124. PMEDIA_CHANGE_DETECTION_INFO info = FdoExtension->MediaChangeDetectionInfo;
  1125. LONG countDown;
  1126. if(info == NULL) {
  1127. DebugPrint((ClassDebugTrace,
  1128. "ClassCheckMediaState: detection not enabled\n"));
  1129. return;
  1130. }
  1131. //
  1132. // Media change support is active and the IRP is waiting. Decrement the
  1133. // timer. There is no MP protection on the timer counter. This code
  1134. // is the only code that will manipulate the timer counter and only one
  1135. // instance of it should be running at any given time.
  1136. //
  1137. countDown = InterlockedDecrement(&(info->MediaChangeCountDown));
  1138. //
  1139. // Try to acquire the media change event. If we can't do it immediately
  1140. // then bail out and assume the caller will try again later.
  1141. //
  1142. ClasspSendMediaStateIrp(FdoExtension,
  1143. info,
  1144. countDown);
  1145. return;
  1146. } // end ClassCheckMediaState()
  1147. /*++////////////////////////////////////////////////////////////////////////////
  1148. ClassResetMediaChangeTimer()
  1149. Routine Description:
  1150. Resets the media change count down timer to the default number of seconds.
  1151. Arguments:
  1152. FdoExtension - the device to reset the timer for
  1153. Return Value:
  1154. None
  1155. --*/
  1156. VOID
  1157. ClassResetMediaChangeTimer(
  1158. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  1159. )
  1160. {
  1161. PMEDIA_CHANGE_DETECTION_INFO info = FdoExtension->MediaChangeDetectionInfo;
  1162. if(info != NULL) {
  1163. InterlockedExchange(&(info->MediaChangeCountDown),
  1164. MEDIA_CHANGE_DEFAULT_TIME);
  1165. }
  1166. return;
  1167. } // end ClassResetMediaChangeTimer()
  1168. /*++////////////////////////////////////////////////////////////////////////////
  1169. ClasspInitializePolling() - ISSUE-2000/02/20-henrygab - not documented
  1170. Routine Description:
  1171. This routine
  1172. Arguments:
  1173. DeviceObject -
  1174. Irp -
  1175. Return Value:
  1176. --*/
  1177. NTSTATUS
  1178. ClasspInitializePolling(
  1179. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  1180. IN BOOLEAN AllowDriveToSleep
  1181. )
  1182. {
  1183. PDEVICE_OBJECT fdo = FdoExtension->DeviceObject;
  1184. PCLASS_PRIVATE_FDO_DATA fdoData = FdoExtension->PrivateFdoData;
  1185. ULONG size;
  1186. PMEDIA_CHANGE_DETECTION_INFO info;
  1187. PIRP irp;
  1188. PAGED_CODE();
  1189. if (FdoExtension->MediaChangeDetectionInfo != NULL) {
  1190. return STATUS_SUCCESS;
  1191. }
  1192. info = ExAllocatePoolWithTag(NonPagedPool,
  1193. sizeof(MEDIA_CHANGE_DETECTION_INFO),
  1194. CLASS_TAG_MEDIA_CHANGE_DETECTION);
  1195. if (info != NULL) {
  1196. RtlZeroMemory(info, sizeof(MEDIA_CHANGE_DETECTION_INFO));
  1197. FdoExtension->KernelModeMcnContext.FileObject = (PVOID)-1;
  1198. FdoExtension->KernelModeMcnContext.DeviceObject = (PVOID)-1;
  1199. FdoExtension->KernelModeMcnContext.LockCount = 0;
  1200. FdoExtension->KernelModeMcnContext.McnDisableCount = 0;
  1201. /*
  1202. * Allocate an IRP to carry the Test-Unit-Ready.
  1203. * Allocate an extra IRP stack location
  1204. * so we can cache our device object in the top location.
  1205. */
  1206. irp = IoAllocateIrp((CCHAR)(fdo->StackSize+1), FALSE);
  1207. if (irp != NULL) {
  1208. PVOID buffer;
  1209. buffer = ExAllocatePoolWithTag(
  1210. NonPagedPoolCacheAligned,
  1211. SENSE_BUFFER_SIZE,
  1212. CLASS_TAG_MEDIA_CHANGE_DETECTION);
  1213. if (buffer != NULL) {
  1214. PIO_STACK_LOCATION irpStack;
  1215. PSCSI_REQUEST_BLOCK srb;
  1216. PCDB cdb;
  1217. srb = &(info->MediaChangeSrb);
  1218. info->MediaChangeIrp = irp;
  1219. info->SenseBuffer = buffer;
  1220. //
  1221. // Set default values for the media change notification
  1222. // configuration.
  1223. //
  1224. info->MediaChangeCountDown = MEDIA_CHANGE_DEFAULT_TIME;
  1225. info->MediaChangeDetectionDisableCount = 0;
  1226. //
  1227. // Assume that there is initially no media in the device
  1228. // only notify upper layers if there is something there
  1229. //
  1230. info->MediaChangeDetectionState = MediaUnknown;
  1231. info->MediaChangeIrpTimeInUse = 0;
  1232. info->MediaChangeIrpLost = FALSE;
  1233. //
  1234. // setup all extra flags we'll be setting for this irp
  1235. //
  1236. info->SrbFlags = 0;
  1237. if (AllowDriveToSleep) {
  1238. SET_FLAG(info->SrbFlags, SRB_FLAGS_NO_KEEP_AWAKE);
  1239. }
  1240. SET_FLAG(info->SrbFlags, SRB_CLASS_FLAGS_LOW_PRIORITY);
  1241. SET_FLAG(info->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE);
  1242. SET_FLAG(info->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
  1243. KeInitializeMutex(&info->MediaChangeMutex, 0x100);
  1244. //
  1245. // It is ok to support media change events on this
  1246. // device.
  1247. //
  1248. FdoExtension->MediaChangeDetectionInfo = info;
  1249. //
  1250. // NOTE: the DeviceType is FILE_DEVICE_CD_ROM even
  1251. // when the device supports DVD (no need to
  1252. // check for FILE_DEVICE_DVD, as it's not a
  1253. // valid check).
  1254. //
  1255. if (FdoExtension->DeviceObject->DeviceType == FILE_DEVICE_CD_ROM){
  1256. NTSTATUS status;
  1257. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1258. "ClasspInitializePolling: Testing for GESN\n"));
  1259. status = ClasspInitializeGesn(FdoExtension, info);
  1260. if (NT_SUCCESS(status)) {
  1261. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1262. "ClasspInitializePolling: GESN available "
  1263. "for %p\n", FdoExtension->DeviceObject));
  1264. ASSERT(info->Gesn.Supported );
  1265. ASSERT(info->Gesn.Buffer != NULL);
  1266. ASSERT(info->Gesn.BufferSize != 0);
  1267. ASSERT(info->Gesn.EventMask != 0);
  1268. // must return here, for ASSERTs to be valid.
  1269. return STATUS_SUCCESS;
  1270. }
  1271. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1272. "ClasspInitializePolling: GESN *NOT* available "
  1273. "for %p\n", FdoExtension->DeviceObject));
  1274. }
  1275. ASSERT(info->Gesn.Supported == 0);
  1276. ASSERT(info->Gesn.Buffer == NULL);
  1277. ASSERT(info->Gesn.BufferSize == 0);
  1278. ASSERT(info->Gesn.EventMask == 0);
  1279. info->Gesn.Supported = 0; // just in case....
  1280. return STATUS_SUCCESS;
  1281. }
  1282. IoFreeIrp(irp);
  1283. }
  1284. ExFreePool(info);
  1285. }
  1286. //
  1287. // nothing to free here
  1288. //
  1289. return STATUS_INSUFFICIENT_RESOURCES;
  1290. } // end ClasspInitializePolling()
  1291. NTSTATUS
  1292. ClasspInitializeGesn(
  1293. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  1294. IN PMEDIA_CHANGE_DETECTION_INFO Info
  1295. )
  1296. {
  1297. PNOTIFICATION_EVENT_STATUS_HEADER header;
  1298. CLASS_DETECTION_STATE detectionState = ClassDetectionUnknown;
  1299. PSTORAGE_ADAPTER_DESCRIPTOR adapterDescriptor;
  1300. NTSTATUS status = STATUS_NOT_SUPPORTED;
  1301. PIRP irp;
  1302. KEVENT event;
  1303. BOOLEAN retryImmediately;
  1304. ULONG i;
  1305. ULONG atapiResets;
  1306. PAGED_CODE();
  1307. ASSERT(Info == FdoExtension->MediaChangeDetectionInfo);
  1308. //
  1309. // read if we already know the abilities of the device
  1310. //
  1311. ClassGetDeviceParameter(FdoExtension,
  1312. CLASSP_REG_SUBKEY_NAME,
  1313. CLASSP_REG_MMC_DETECTION_VALUE_NAME,
  1314. (PULONG)&detectionState);
  1315. if (detectionState == ClassDetectionUnsupported) {
  1316. goto ExitWithError;
  1317. }
  1318. //
  1319. // check if the device has a hack flag saying never to try this.
  1320. //
  1321. if (TEST_FLAG(FdoExtension->PrivateFdoData->HackFlags,
  1322. FDO_HACK_GESN_IS_BAD)) {
  1323. ClassSetDeviceParameter(FdoExtension,
  1324. CLASSP_REG_SUBKEY_NAME,
  1325. CLASSP_REG_MMC_DETECTION_VALUE_NAME,
  1326. ClassDetectionUnsupported);
  1327. goto ExitWithError;
  1328. }
  1329. //
  1330. // else go through the process since we allocate buffers and
  1331. // get all sorts of device settings.
  1332. //
  1333. if (Info->Gesn.Buffer == NULL) {
  1334. Info->Gesn.Buffer = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
  1335. GESN_BUFFER_SIZE,
  1336. '??cS');
  1337. }
  1338. if (Info->Gesn.Buffer == NULL) {
  1339. status = STATUS_INSUFFICIENT_RESOURCES;
  1340. goto ExitWithError;
  1341. }
  1342. if (Info->Gesn.Mdl != NULL) {
  1343. IoFreeMdl(Info->Gesn.Mdl);
  1344. }
  1345. Info->Gesn.Mdl = IoAllocateMdl(Info->Gesn.Buffer,
  1346. GESN_BUFFER_SIZE,
  1347. FALSE, FALSE, NULL);
  1348. if (Info->Gesn.Mdl == NULL) {
  1349. status = STATUS_INSUFFICIENT_RESOURCES;
  1350. goto ExitWithError;
  1351. }
  1352. MmBuildMdlForNonPagedPool(Info->Gesn.Mdl);
  1353. Info->Gesn.BufferSize = GESN_BUFFER_SIZE;
  1354. Info->Gesn.EventMask = 0;
  1355. //
  1356. // all items are prepared to use GESN (except the event mask, so don't
  1357. // optimize this part out!).
  1358. //
  1359. // now see if it really works. we have to loop through this because
  1360. // many SAMSUNG (and one COMPAQ) drives timeout when requesting
  1361. // NOT_READY events, even when the IMMEDIATE bit is set. :(
  1362. //
  1363. // using a drive list is cumbersome, so this might fix the problem.
  1364. //
  1365. adapterDescriptor = FdoExtension->AdapterDescriptor;
  1366. atapiResets = 0;
  1367. retryImmediately = TRUE;
  1368. for (i = 0; i < 16 && retryImmediately == TRUE; i++) {
  1369. irp = ClasspPrepareMcnIrp(FdoExtension, Info, TRUE);
  1370. if (irp == NULL) {
  1371. status = STATUS_INSUFFICIENT_RESOURCES;
  1372. goto ExitWithError;
  1373. }
  1374. ASSERT(TEST_FLAG(Info->MediaChangeSrb.SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE));
  1375. //
  1376. // replace the completion routine with a different one this time...
  1377. //
  1378. IoSetCompletionRoutine(irp,
  1379. ClassSignalCompletion,
  1380. &event,
  1381. TRUE, TRUE, TRUE);
  1382. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  1383. status = IoCallDriver(FdoExtension->CommonExtension.LowerDeviceObject, irp);
  1384. if (status == STATUS_PENDING) {
  1385. status = KeWaitForSingleObject(&event,
  1386. Executive,
  1387. KernelMode,
  1388. FALSE,
  1389. NULL);
  1390. ASSERT(NT_SUCCESS(status));
  1391. }
  1392. ClassReleaseRemoveLock(FdoExtension->DeviceObject, irp);
  1393. if (SRB_STATUS(Info->MediaChangeSrb.SrbStatus) != SRB_STATUS_SUCCESS) {
  1394. ClassInterpretSenseInfo(FdoExtension->DeviceObject,
  1395. &(Info->MediaChangeSrb),
  1396. IRP_MJ_SCSI,
  1397. 0,
  1398. 0,
  1399. &status,
  1400. NULL);
  1401. }
  1402. if ((adapterDescriptor->BusType == BusTypeAtapi) &&
  1403. (Info->MediaChangeSrb.SrbStatus == SRB_STATUS_BUS_RESET)
  1404. ) {
  1405. //
  1406. // ATAPI unfortunately returns SRB_STATUS_BUS_RESET instead
  1407. // of SRB_STATUS_TIMEOUT, so we cannot differentiate between
  1408. // the two. if we get this status four time consecutively,
  1409. // stop trying this command. it is too late to change ATAPI
  1410. // at this point, so special-case this here. (07/10/2001)
  1411. // NOTE: any value more than 4 may cause the device to be
  1412. // marked missing.
  1413. //
  1414. atapiResets++;
  1415. if (atapiResets >= 4) {
  1416. status = STATUS_IO_DEVICE_ERROR;
  1417. goto ExitWithError;
  1418. }
  1419. }
  1420. if (status == STATUS_DATA_OVERRUN) {
  1421. status = STATUS_SUCCESS;
  1422. }
  1423. if ((status == STATUS_INVALID_DEVICE_REQUEST) ||
  1424. (status == STATUS_TIMEOUT) ||
  1425. (status == STATUS_IO_DEVICE_ERROR) ||
  1426. (status == STATUS_IO_TIMEOUT)
  1427. ) {
  1428. //
  1429. // with these error codes, we don't ever want to try this command
  1430. // again on this device, since it reacts poorly.
  1431. //
  1432. ClassSetDeviceParameter(FdoExtension,
  1433. CLASSP_REG_SUBKEY_NAME,
  1434. CLASSP_REG_MMC_DETECTION_VALUE_NAME,
  1435. ClassDetectionUnsupported);
  1436. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugWarning,
  1437. "Classpnp => GESN test failed %x for fdo %p\n",
  1438. status, FdoExtension->DeviceObject));
  1439. goto ExitWithError;
  1440. }
  1441. if (!NT_SUCCESS(status)) {
  1442. //
  1443. // this may be other errors that should not disable GESN
  1444. // for all future start_device calls.
  1445. //
  1446. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugWarning,
  1447. "Classpnp => GESN test failed %x for fdo %p\n",
  1448. status, FdoExtension->DeviceObject));
  1449. goto ExitWithError;
  1450. }
  1451. if (i == 0) {
  1452. //
  1453. // the first time, the request was just retrieving a mask of
  1454. // available bits. use this to mask future requests.
  1455. //
  1456. header = (PNOTIFICATION_EVENT_STATUS_HEADER)(Info->Gesn.Buffer);
  1457. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1458. "Classpnp => Fdo %p supports event mask %x\n",
  1459. FdoExtension->DeviceObject, header->SupportedEventClasses));
  1460. if (TEST_FLAG(header->SupportedEventClasses,
  1461. NOTIFICATION_MEDIA_STATUS_CLASS_MASK)) {
  1462. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1463. "Classpnp => GESN supports MCN\n"));
  1464. }
  1465. if (TEST_FLAG(header->SupportedEventClasses,
  1466. NOTIFICATION_DEVICE_BUSY_CLASS_MASK)) {
  1467. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1468. "Classpnp => GESN supports DeviceBusy\n"));
  1469. }
  1470. if (TEST_FLAG(header->SupportedEventClasses,
  1471. NOTIFICATION_OPERATIONAL_CHANGE_CLASS_MASK)) {
  1472. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1473. "Classpnp => GESN supports OpChange\n"));
  1474. }
  1475. Info->Gesn.EventMask = header->SupportedEventClasses;
  1476. //
  1477. // realistically, we are only considering the following events:
  1478. // EXTERNAL REQUEST - this is being tested for play/stop/etc.
  1479. // MEDIA STATUS - autorun and ejection requests.
  1480. // DEVICE BUSY - to allow us to predict when media will be ready.
  1481. // therefore, we should not bother querying for the other,
  1482. // unknown events. clear all but the above flags.
  1483. //
  1484. Info->Gesn.EventMask &=
  1485. NOTIFICATION_OPERATIONAL_CHANGE_CLASS_MASK |
  1486. NOTIFICATION_EXTERNAL_REQUEST_CLASS_MASK |
  1487. NOTIFICATION_MEDIA_STATUS_CLASS_MASK |
  1488. NOTIFICATION_DEVICE_BUSY_CLASS_MASK ;
  1489. //
  1490. // HACKHACK - REF #0001
  1491. // Some devices will *never* report an event if we've also requested
  1492. // that it report lower-priority events. this is due to a
  1493. // misunderstanding in the specification wherein a "No Change" is
  1494. // interpreted to be a real event. what should occur is that the
  1495. // device should ignore "No Change" events when multiple event types
  1496. // are requested unless there are no other events waiting. this
  1497. // greatly reduces the number of requests that the host must send
  1498. // to determine if an event has occurred. Since we must work on all
  1499. // drives, default to enabling the hack until we find evidence of
  1500. // proper firmware.
  1501. //
  1502. if (Info->Gesn.EventMask == 0) {
  1503. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1504. "Classpnp => GESN supported, but not mask we care "
  1505. "about (%x) for FDO %p\n",
  1506. header->SupportedEventClasses,
  1507. FdoExtension->DeviceObject));
  1508. goto ExitWithError;
  1509. } else if (CountOfSetBitsUChar(Info->Gesn.EventMask) == 1) {
  1510. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1511. "Classpnp => GESN hack not required for FDO %p\n",
  1512. FdoExtension->DeviceObject));
  1513. } else {
  1514. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1515. "Classpnp => GESN hack enabled for FDO %p\n",
  1516. FdoExtension->DeviceObject));
  1517. Info->Gesn.HackEventMask = 1;
  1518. }
  1519. } else {
  1520. //
  1521. // not the first time looping through, so interpret the results.
  1522. //
  1523. status = ClasspInterpretGesnData(FdoExtension,
  1524. (PVOID)Info->Gesn.Buffer,
  1525. &retryImmediately);
  1526. if (!NT_SUCCESS(status)) {
  1527. //
  1528. // This drive does not support GESN correctly
  1529. //
  1530. ClassSetDeviceParameter(FdoExtension,
  1531. CLASSP_REG_SUBKEY_NAME,
  1532. CLASSP_REG_MMC_DETECTION_VALUE_NAME,
  1533. ClassDetectionUnsupported);
  1534. goto ExitWithError;
  1535. }
  1536. }
  1537. } // end loop of GESN requests....
  1538. //
  1539. // we can only use this if it can be relied upon for media changes,
  1540. // since we are (by definition) no longer going to be polling via
  1541. // a TEST_UNIT_READY irp, and drives will not report UNIT ATTENTION
  1542. // for this command (although a filter driver, such as one for burning
  1543. // cd's, might still fake those errors).
  1544. //
  1545. // since we also rely upon NOT_READY events to change the cursor
  1546. // into a "wait" cursor, we can't use GESN without NOT_READY support.
  1547. //
  1548. if (TEST_FLAG(Info->Gesn.EventMask,
  1549. NOTIFICATION_MEDIA_STATUS_CLASS_MASK) &&
  1550. TEST_FLAG(Info->Gesn.EventMask,
  1551. NOTIFICATION_DEVICE_BUSY_CLASS_MASK)
  1552. ) {
  1553. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1554. "Classpnp => Enabling GESN support for fdo %p\n",
  1555. FdoExtension->DeviceObject));
  1556. Info->Gesn.Supported = TRUE;
  1557. ClassSetDeviceParameter(FdoExtension,
  1558. CLASSP_REG_SUBKEY_NAME,
  1559. CLASSP_REG_MMC_DETECTION_VALUE_NAME,
  1560. ClassDetectionSupported);
  1561. return STATUS_SUCCESS;
  1562. }
  1563. KdPrintEx((DPFLTR_CLASSPNP_ID, ClassDebugMCN,
  1564. "Classpnp => GESN available but not enabled for fdo %p\n",
  1565. FdoExtension->DeviceObject));
  1566. goto ExitWithError;
  1567. // fall through...
  1568. ExitWithError:
  1569. if (Info->Gesn.Mdl) {
  1570. IoFreeMdl(Info->Gesn.Mdl);
  1571. Info->Gesn.Mdl = NULL;
  1572. }
  1573. if (Info->Gesn.Buffer) {
  1574. ExFreePool(Info->Gesn.Buffer);
  1575. Info->Gesn.Buffer = NULL;
  1576. }
  1577. Info->Gesn.Supported = 0;
  1578. Info->Gesn.EventMask = 0;
  1579. Info->Gesn.BufferSize = 0;
  1580. return STATUS_NOT_SUPPORTED;
  1581. }
  1582. /*++////////////////////////////////////////////////////////////////////////////
  1583. ClassInitializeTestUnitPolling()
  1584. Routine Description:
  1585. This routine will initialize MCN regardless of the settings stored
  1586. in the registry. This should be used with caution, as some devices
  1587. react badly to constant io. (i.e. never spin down, continuously cycling
  1588. media in changers, ejection of media, etc.) It is highly suggested to
  1589. use ClassInitializeMediaChangeDetection() instead.
  1590. Arguments:
  1591. FdoExtension is the device to poll
  1592. AllowDriveToSleep says whether to attempt to allow the drive to sleep
  1593. or not. This only affects system-known spin down states, so if a
  1594. drive spins itself down, this has no effect until the system spins
  1595. it down.
  1596. Return Value:
  1597. --*/
  1598. NTSTATUS
  1599. ClassInitializeTestUnitPolling(
  1600. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  1601. IN BOOLEAN AllowDriveToSleep
  1602. )
  1603. {
  1604. return ClasspInitializePolling(FdoExtension, AllowDriveToSleep);
  1605. } // end ClassInitializeTestUnitPolling()
  1606. /*++////////////////////////////////////////////////////////////////////////////
  1607. ClassInitializeMediaChangeDetection()
  1608. Routine Description:
  1609. This routine checks to see if it is safe to initialize MCN (the back end
  1610. to autorun) for a given device. It will then check the device-type wide
  1611. key "Autorun" in the service key (for legacy reasons), and then look in
  1612. the device-specific key to potentially override that setting.
  1613. If MCN is to be enabled, all neccessary structures and memory are
  1614. allocated and initialized.
  1615. This routine MUST be called only from the ClassInit() callback.
  1616. Arguments:
  1617. FdoExtension - the device to initialize MCN for, if appropriate
  1618. EventPrefix - unused, legacy argument. Set to zero.
  1619. Return Value:
  1620. --*/
  1621. VOID
  1622. ClassInitializeMediaChangeDetection(
  1623. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  1624. IN PUCHAR EventPrefix
  1625. )
  1626. {
  1627. PDEVICE_OBJECT fdo = FdoExtension->DeviceObject;
  1628. NTSTATUS status;
  1629. PCLASS_DRIVER_EXTENSION driverExtension = ClassGetDriverExtension(
  1630. fdo->DriverObject);
  1631. BOOLEAN disabledForBadHardware;
  1632. BOOLEAN disabled;
  1633. BOOLEAN instanceOverride;
  1634. PAGED_CODE();
  1635. //
  1636. // NOTE: This assumes that ClassInitializeMediaChangeDetection is always
  1637. // called in the context of the ClassInitDevice callback. If called
  1638. // after then this check will have already been made and the
  1639. // once a second timer will not have been enabled.
  1640. //
  1641. disabledForBadHardware = ClasspIsMediaChangeDisabledDueToHardwareLimitation(
  1642. FdoExtension,
  1643. &(driverExtension->RegistryPath)
  1644. );
  1645. if (disabledForBadHardware) {
  1646. DebugPrint((ClassDebugMCN,
  1647. "ClassInitializeMCN: Disabled due to hardware"
  1648. "limitations for this device"));
  1649. return;
  1650. }
  1651. //
  1652. // autorun should now be enabled by default for all media types.
  1653. //
  1654. disabled = ClasspIsMediaChangeDisabledForClass(
  1655. FdoExtension,
  1656. &(driverExtension->RegistryPath)
  1657. );
  1658. DebugPrint((ClassDebugMCN,
  1659. "ClassInitializeMCN: Class MCN is %s\n",
  1660. (disabled ? "disabled" : "enabled")));
  1661. status = ClasspMediaChangeDeviceInstanceOverride(
  1662. FdoExtension,
  1663. &instanceOverride); // default value
  1664. if (!NT_SUCCESS(status)) {
  1665. DebugPrint((ClassDebugMCN,
  1666. "ClassInitializeMCN: Instance using default\n"));
  1667. } else {
  1668. DebugPrint((ClassDebugMCN,
  1669. "ClassInitializeMCN: Instance override: %s MCN\n",
  1670. (instanceOverride ? "Enabling" : "Disabling")));
  1671. disabled = !instanceOverride;
  1672. }
  1673. DebugPrint((ClassDebugMCN,
  1674. "ClassInitializeMCN: Instance MCN is %s\n",
  1675. (disabled ? "disabled" : "enabled")));
  1676. if (disabled) {
  1677. return;
  1678. }
  1679. //
  1680. // if the drive is not a CDROM, allow the drive to sleep
  1681. //
  1682. if (FdoExtension->DeviceObject->DeviceType == FILE_DEVICE_CD_ROM) {
  1683. ClasspInitializePolling(FdoExtension, FALSE);
  1684. } else {
  1685. ClasspInitializePolling(FdoExtension, TRUE);
  1686. }
  1687. return;
  1688. } // end ClassInitializeMediaChangeDetection()
  1689. /*++////////////////////////////////////////////////////////////////////////////
  1690. ClasspMediaChangeDeviceInstanceOverride()
  1691. Routine Description:
  1692. The user can override the global setting to enable or disable Autorun on a
  1693. specific cdrom device via the control panel. This routine checks and/or
  1694. sets this value.
  1695. Arguments:
  1696. FdoExtension - the device to set/get the value for
  1697. Value - the value to use in a set
  1698. SetValue - whether to set the value
  1699. Return Value:
  1700. TRUE - Autorun is disabled
  1701. FALSE - Autorun is not disabled (Default)
  1702. --*/
  1703. NTSTATUS
  1704. ClasspMediaChangeDeviceInstanceOverride(
  1705. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  1706. OUT PBOOLEAN Enabled
  1707. )
  1708. {
  1709. HANDLE deviceParameterHandle; // cdrom instance key
  1710. HANDLE driverParameterHandle; // cdrom specific key
  1711. RTL_QUERY_REGISTRY_TABLE queryTable[3];
  1712. OBJECT_ATTRIBUTES objectAttributes;
  1713. UNICODE_STRING subkeyName;
  1714. NTSTATUS status;
  1715. ULONG alwaysEnable;
  1716. ULONG alwaysDisable;
  1717. ULONG i;
  1718. PAGED_CODE();
  1719. deviceParameterHandle = NULL;
  1720. driverParameterHandle = NULL;
  1721. status = STATUS_UNSUCCESSFUL;
  1722. alwaysEnable = FALSE;
  1723. alwaysDisable = FALSE;
  1724. TRY {
  1725. status = IoOpenDeviceRegistryKey( FdoExtension->LowerPdo,
  1726. PLUGPLAY_REGKEY_DEVICE,
  1727. KEY_ALL_ACCESS,
  1728. &deviceParameterHandle
  1729. );
  1730. if (!NT_SUCCESS(status)) {
  1731. //
  1732. // this can occur when a new device is added to the system
  1733. // this is due to cdrom.sys being an 'essential' driver
  1734. //
  1735. DebugPrint((ClassDebugMCN,
  1736. "ClassMediaChangeDeviceInstanceDisabled: "
  1737. "Could not open device registry key [%lx]\n", status));
  1738. LEAVE;
  1739. }
  1740. RtlInitUnicodeString(&subkeyName, MCN_REG_SUBKEY_NAME);
  1741. InitializeObjectAttributes(&objectAttributes,
  1742. &subkeyName,
  1743. OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
  1744. deviceParameterHandle,
  1745. (PSECURITY_DESCRIPTOR) NULL);
  1746. status = ZwCreateKey(&driverParameterHandle,
  1747. KEY_READ,
  1748. &objectAttributes,
  1749. 0,
  1750. (PUNICODE_STRING) NULL,
  1751. REG_OPTION_NON_VOLATILE,
  1752. NULL);
  1753. if (!NT_SUCCESS(status)) {
  1754. DebugPrint((ClassDebugMCN,
  1755. "ClassMediaChangeDeviceInstanceDisabled: "
  1756. "subkey could not be created. %lx\n", status));
  1757. LEAVE;
  1758. }
  1759. //
  1760. // Default to not changing autorun behavior, based upon setting
  1761. // registryValue to zero.
  1762. //
  1763. for (i=0;i<2;i++) {
  1764. RtlZeroMemory(&queryTable[0], sizeof(queryTable));
  1765. queryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
  1766. queryTable[0].DefaultType = REG_DWORD;
  1767. queryTable[0].DefaultLength = 0;
  1768. if (i==0) {
  1769. queryTable[0].Name = MCN_REG_AUTORUN_DISABLE_INSTANCE_NAME;
  1770. queryTable[0].EntryContext = &alwaysDisable;
  1771. queryTable[0].DefaultData = &alwaysDisable;
  1772. } else {
  1773. queryTable[0].Name = MCN_REG_AUTORUN_ENABLE_INSTANCE_NAME;
  1774. queryTable[0].EntryContext = &alwaysEnable;
  1775. queryTable[0].DefaultData = &alwaysEnable;
  1776. }
  1777. //
  1778. // don't care if it succeeds, since we set defaults above
  1779. //
  1780. RtlQueryRegistryValues(RTL_REGISTRY_HANDLE,
  1781. (PWSTR)driverParameterHandle,
  1782. queryTable,
  1783. NULL,
  1784. NULL);
  1785. }
  1786. } FINALLY {
  1787. if (driverParameterHandle) ZwClose(driverParameterHandle);
  1788. if (deviceParameterHandle) ZwClose(deviceParameterHandle);
  1789. }
  1790. if (alwaysEnable && alwaysDisable) {
  1791. DebugPrint((ClassDebugMCN,
  1792. "ClassMediaChangeDeviceInstanceDisabled: %s selected\n",
  1793. "Both Enable and Disable set -- DISABLE"));
  1794. ASSERT(NT_SUCCESS(status));
  1795. status = STATUS_SUCCESS;
  1796. *Enabled = FALSE;
  1797. } else if (alwaysDisable) {
  1798. DebugPrint((ClassDebugMCN,
  1799. "ClassMediaChangeDeviceInstanceDisabled: %s selected\n",
  1800. "DISABLE"));
  1801. ASSERT(NT_SUCCESS(status));
  1802. status = STATUS_SUCCESS;
  1803. *Enabled = FALSE;
  1804. } else if (alwaysEnable) {
  1805. DebugPrint((ClassDebugMCN,
  1806. "ClassMediaChangeDeviceInstanceDisabled: %s selected\n",
  1807. "ENABLE"));
  1808. ASSERT(NT_SUCCESS(status));
  1809. status = STATUS_SUCCESS;
  1810. *Enabled = TRUE;
  1811. } else {
  1812. DebugPrint((ClassDebugMCN,
  1813. "ClassMediaChangeDeviceInstanceDisabled: %s selected\n",
  1814. "DEFAULT"));
  1815. status = STATUS_UNSUCCESSFUL;
  1816. }
  1817. return status;
  1818. } // end ClasspMediaChangeDeviceInstanceOverride()
  1819. /*++////////////////////////////////////////////////////////////////////////////
  1820. ClasspIsMediaChangeDisabledDueToHardwareLimitation()
  1821. Routine Description:
  1822. The key AutoRunAlwaysDisable contains a MULTI_SZ of hardware IDs for
  1823. which to never enable MediaChangeNotification.
  1824. The user can override the global setting to enable or disable Autorun on a
  1825. specific cdrom device via the control panel.
  1826. Arguments:
  1827. FdoExtension -
  1828. RegistryPath - pointer to the unicode string inside
  1829. ...\CurrentControlSet\Services\Cdrom
  1830. Return Value:
  1831. TRUE - no autorun.
  1832. FALSE - Autorun may be enabled
  1833. --*/
  1834. BOOLEAN
  1835. ClasspIsMediaChangeDisabledDueToHardwareLimitation(
  1836. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  1837. IN PUNICODE_STRING RegistryPath
  1838. )
  1839. {
  1840. PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor = FdoExtension->DeviceDescriptor;
  1841. OBJECT_ATTRIBUTES objectAttributes = {0};
  1842. HANDLE serviceKey = NULL;
  1843. RTL_QUERY_REGISTRY_TABLE parameters[2] = {0};
  1844. UNICODE_STRING deviceUnicodeString;
  1845. ANSI_STRING deviceString;
  1846. ULONG mediaChangeNotificationDisabled = FALSE;
  1847. NTSTATUS status;
  1848. PAGED_CODE();
  1849. //
  1850. // open the service key.
  1851. //
  1852. InitializeObjectAttributes(&objectAttributes,
  1853. RegistryPath,
  1854. OBJ_CASE_INSENSITIVE,
  1855. NULL,
  1856. NULL);
  1857. status = ZwOpenKey(&serviceKey,
  1858. KEY_READ,
  1859. &objectAttributes);
  1860. ASSERT(NT_SUCCESS(status));
  1861. if(!NT_SUCCESS(status)) {
  1862. //
  1863. // always take the safe path. if we can't open the service key,
  1864. // disable autorun
  1865. //
  1866. return TRUE;
  1867. }
  1868. TRY {
  1869. //
  1870. // Determine if drive is in a list of those requiring
  1871. // autorun to be disabled. this is stored in a REG_MULTI_SZ
  1872. // named AutoRunAlwaysDisable. this is required as some autochangers
  1873. // must load the disc to reply to ChkVerify request, causing them
  1874. // to cycle discs continuously.
  1875. //
  1876. PWSTR nullMultiSz;
  1877. PUCHAR vendorId;
  1878. PUCHAR productId;
  1879. PUCHAR revisionId;
  1880. ULONG length;
  1881. ULONG offset;
  1882. deviceString.Buffer = NULL;
  1883. deviceUnicodeString.Buffer = NULL;
  1884. //
  1885. // there may be nothing to check against
  1886. //
  1887. if ((deviceDescriptor->VendorIdOffset == 0) &&
  1888. (deviceDescriptor->ProductIdOffset == 0)) {
  1889. LEAVE;
  1890. }
  1891. length = 0;
  1892. if (deviceDescriptor->VendorIdOffset == 0) {
  1893. vendorId = NULL;
  1894. } else {
  1895. vendorId = (PUCHAR) deviceDescriptor + deviceDescriptor->VendorIdOffset;
  1896. length = strlen(vendorId);
  1897. }
  1898. if ( deviceDescriptor->ProductIdOffset == 0 ) {
  1899. productId = NULL;
  1900. } else {
  1901. productId = (PUCHAR) deviceDescriptor + deviceDescriptor->ProductIdOffset;
  1902. length += strlen(productId);
  1903. }
  1904. if ( deviceDescriptor->ProductRevisionOffset == 0 ) {
  1905. revisionId = NULL;
  1906. } else {
  1907. revisionId = (PUCHAR) deviceDescriptor + deviceDescriptor->ProductRevisionOffset;
  1908. length += strlen(revisionId);
  1909. }
  1910. //
  1911. // allocate a buffer for the string
  1912. //
  1913. deviceString.Length = (USHORT)( length );
  1914. deviceString.MaximumLength = deviceString.Length + 1;
  1915. deviceString.Buffer = (PUCHAR)ExAllocatePoolWithTag( NonPagedPool,
  1916. deviceString.MaximumLength,
  1917. CLASS_TAG_AUTORUN_DISABLE
  1918. );
  1919. if (deviceString.Buffer == NULL) {
  1920. DebugPrint((ClassDebugMCN,
  1921. "ClassMediaChangeDisabledForHardware: Unable to alloc "
  1922. "string buffer\n" ));
  1923. LEAVE;
  1924. }
  1925. //
  1926. // copy strings to the buffer
  1927. //
  1928. offset = 0;
  1929. if (vendorId != NULL) {
  1930. RtlCopyMemory(deviceString.Buffer + offset,
  1931. vendorId,
  1932. strlen(vendorId));
  1933. offset += strlen(vendorId);
  1934. }
  1935. if ( productId != NULL ) {
  1936. RtlCopyMemory(deviceString.Buffer + offset,
  1937. productId,
  1938. strlen(productId));
  1939. offset += strlen(productId);
  1940. }
  1941. if ( revisionId != NULL ) {
  1942. RtlCopyMemory(deviceString.Buffer + offset,
  1943. revisionId,
  1944. strlen(revisionId));
  1945. offset += strlen(revisionId);
  1946. }
  1947. ASSERT(offset == deviceString.Length);
  1948. deviceString.Buffer[deviceString.Length] = '\0'; // Null-terminated
  1949. //
  1950. // convert to unicode as registry deals with unicode strings
  1951. //
  1952. status = RtlAnsiStringToUnicodeString( &deviceUnicodeString,
  1953. &deviceString,
  1954. TRUE
  1955. );
  1956. if (!NT_SUCCESS(status)) {
  1957. DebugPrint((ClassDebugMCN,
  1958. "ClassMediaChangeDisabledForHardware: cannot convert "
  1959. "to unicode %lx\n", status));
  1960. LEAVE;
  1961. }
  1962. //
  1963. // query the value, setting valueFound to true if found
  1964. //
  1965. nullMultiSz = L"\0";
  1966. parameters[0].QueryRoutine = ClasspMediaChangeRegistryCallBack;
  1967. parameters[0].Flags = RTL_QUERY_REGISTRY_REQUIRED;
  1968. parameters[0].Name = L"AutoRunAlwaysDisable";
  1969. parameters[0].EntryContext = &mediaChangeNotificationDisabled;
  1970. parameters[0].DefaultType = REG_MULTI_SZ;
  1971. parameters[0].DefaultData = nullMultiSz;
  1972. parameters[0].DefaultLength = 0;
  1973. status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE,
  1974. serviceKey,
  1975. parameters,
  1976. &deviceUnicodeString,
  1977. NULL);
  1978. if ( !NT_SUCCESS(status) ) {
  1979. LEAVE;
  1980. }
  1981. } FINALLY {
  1982. if (deviceString.Buffer != NULL) {
  1983. ExFreePool( deviceString.Buffer );
  1984. }
  1985. if (deviceUnicodeString.Buffer != NULL) {
  1986. RtlFreeUnicodeString( &deviceUnicodeString );
  1987. }
  1988. ZwClose(serviceKey);
  1989. }
  1990. if (mediaChangeNotificationDisabled) {
  1991. DebugPrint((ClassDebugMCN, "ClassMediaChangeDisabledForHardware: "
  1992. "Device is on disable list\n"));
  1993. return TRUE;
  1994. }
  1995. return FALSE;
  1996. } // end ClasspIsMediaChangeDisabledDueToHardwareLimitation()
  1997. /*++////////////////////////////////////////////////////////////////////////////
  1998. ClasspIsMediaChangeDisabledForClass()
  1999. Routine Description:
  2000. The user must specify that AutoPlay is to run on the platform
  2001. by setting the registry value HKEY_LOCAL_MACHINE\System\CurrentControlSet\
  2002. Services\<SERVICE>\Autorun:REG_DWORD:1.
  2003. The user can override the global setting to enable or disable Autorun on a
  2004. specific cdrom device via the control panel.
  2005. Arguments:
  2006. FdoExtension -
  2007. RegistryPath - pointer to the unicode string inside
  2008. ...\CurrentControlSet\Services\Cdrom
  2009. Return Value:
  2010. TRUE - Autorun is disabled for this class
  2011. FALSE - Autorun is enabled for this class
  2012. --*/
  2013. BOOLEAN
  2014. ClasspIsMediaChangeDisabledForClass(
  2015. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  2016. IN PUNICODE_STRING RegistryPath
  2017. )
  2018. {
  2019. PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor = FdoExtension->DeviceDescriptor;
  2020. OBJECT_ATTRIBUTES objectAttributes = {0};
  2021. HANDLE serviceKey = NULL;
  2022. HANDLE parametersKey = NULL;
  2023. RTL_QUERY_REGISTRY_TABLE parameters[3] = {0};
  2024. UNICODE_STRING paramStr;
  2025. UNICODE_STRING deviceUnicodeString;
  2026. ANSI_STRING deviceString;
  2027. //
  2028. // Default to ENABLING MediaChangeNotification (!)
  2029. //
  2030. ULONG mcnRegistryValue = 1;
  2031. NTSTATUS status;
  2032. PAGED_CODE();
  2033. //
  2034. // open the service key.
  2035. //
  2036. InitializeObjectAttributes(&objectAttributes,
  2037. RegistryPath,
  2038. OBJ_CASE_INSENSITIVE,
  2039. NULL,
  2040. NULL);
  2041. status = ZwOpenKey(&serviceKey,
  2042. KEY_READ,
  2043. &objectAttributes);
  2044. ASSERT(NT_SUCCESS(status));
  2045. if(!NT_SUCCESS(status)) {
  2046. //
  2047. // return the default value, which is the
  2048. // inverse of the registry setting default
  2049. // since this routine asks if it's disabled
  2050. //
  2051. DebugPrint((ClassDebugMCN, "ClassCheckServiceMCN: Defaulting to %s\n",
  2052. (mcnRegistryValue ? "Enabled" : "Disabled")));
  2053. return (BOOLEAN)(!mcnRegistryValue);
  2054. }
  2055. //
  2056. // Open the parameters key (if any) beneath the services key.
  2057. //
  2058. RtlInitUnicodeString(&paramStr, L"Parameters");
  2059. InitializeObjectAttributes(&objectAttributes,
  2060. &paramStr,
  2061. OBJ_CASE_INSENSITIVE,
  2062. serviceKey,
  2063. NULL);
  2064. status = ZwOpenKey(&parametersKey,
  2065. KEY_READ,
  2066. &objectAttributes);
  2067. if (!NT_SUCCESS(status)) {
  2068. parametersKey = NULL;
  2069. }
  2070. //
  2071. // Check for the Autorun value.
  2072. //
  2073. parameters[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
  2074. parameters[0].Name = L"Autorun";
  2075. parameters[0].EntryContext = &mcnRegistryValue;
  2076. parameters[0].DefaultType = REG_DWORD;
  2077. parameters[0].DefaultData = &mcnRegistryValue;
  2078. parameters[0].DefaultLength = sizeof(ULONG);
  2079. status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE | RTL_REGISTRY_OPTIONAL,
  2080. serviceKey,
  2081. parameters,
  2082. NULL,
  2083. NULL);
  2084. DebugPrint((ClassDebugMCN, "ClassCheckServiceMCN: "
  2085. "<Service>/Autorun flag = %d\n", mcnRegistryValue));
  2086. if(parametersKey != NULL) {
  2087. status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE | RTL_REGISTRY_OPTIONAL,
  2088. parametersKey,
  2089. parameters,
  2090. NULL,
  2091. NULL);
  2092. DebugPrint((ClassDebugMCN, "ClassCheckServiceMCN: "
  2093. "<Service>/Parameters/Autorun flag = %d\n",
  2094. mcnRegistryValue));
  2095. ZwClose(parametersKey);
  2096. }
  2097. ZwClose(serviceKey);
  2098. DebugPrint((ClassDebugMCN, "ClassCheckServiceMCN: "
  2099. "Autoplay for device %p is %s\n",
  2100. FdoExtension->DeviceObject,
  2101. (mcnRegistryValue ? "on" : "off")
  2102. ));
  2103. //
  2104. // return if it is _disabled_, which is the
  2105. // inverse of the registry setting
  2106. //
  2107. return (BOOLEAN)(!mcnRegistryValue);
  2108. } // end ClasspIsMediaChangeDisabledForClass()
  2109. /*++////////////////////////////////////////////////////////////////////////////
  2110. ClassEnableMediaChangeDetection() ISSUE-2000/02/20-henrygab - why public?
  2111. ClassEnableMediaChangeDetection() ISSUE-2000/02/20-henrygab - not documented
  2112. Routine Description:
  2113. This routine
  2114. Arguments:
  2115. DeviceObject -
  2116. Irp -
  2117. Return Value:
  2118. --*/
  2119. VOID
  2120. ClassEnableMediaChangeDetection(
  2121. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  2122. )
  2123. {
  2124. PMEDIA_CHANGE_DETECTION_INFO info = FdoExtension->MediaChangeDetectionInfo;
  2125. LONG oldCount;
  2126. PAGED_CODE();
  2127. if(info == NULL) {
  2128. DebugPrint((ClassDebugMCN,
  2129. "ClassEnableMediaChangeDetection: not initialized\n"));
  2130. return;
  2131. }
  2132. KeWaitForMutexObject(&info->MediaChangeMutex,
  2133. UserRequest,
  2134. KernelMode,
  2135. FALSE,
  2136. NULL);
  2137. oldCount = --info->MediaChangeDetectionDisableCount;
  2138. ASSERT(oldCount >= 0);
  2139. DebugPrint((ClassDebugMCN, "ClassEnableMediaChangeDetection: Disable count "
  2140. "reduced to %d - ",
  2141. info->MediaChangeDetectionDisableCount));
  2142. if(oldCount == 0) {
  2143. //
  2144. // We don't know what state the media is in anymore.
  2145. //
  2146. ClasspInternalSetMediaChangeState(FdoExtension,
  2147. MediaUnknown,
  2148. FALSE
  2149. );
  2150. //
  2151. // Reset the MCN timer.
  2152. //
  2153. ClassResetMediaChangeTimer(FdoExtension);
  2154. DebugPrint((ClassDebugMCN, "MCD is enabled\n"));
  2155. } else {
  2156. DebugPrint((ClassDebugMCN, "MCD still disabled\n"));
  2157. }
  2158. //
  2159. // Let something else run.
  2160. //
  2161. KeReleaseMutex(&info->MediaChangeMutex, FALSE);
  2162. return;
  2163. } // end ClassEnableMediaChangeDetection()
  2164. /*++////////////////////////////////////////////////////////////////////////////
  2165. ClassDisableMediaChangeDetection() ISSUE-2000/02/20-henrygab - why public?
  2166. ClassDisableMediaChangeDetection() ISSUE-2000/02/20-henrygab - not documented
  2167. Routine Description:
  2168. This routine
  2169. Arguments:
  2170. DeviceObject -
  2171. Irp -
  2172. Return Value:
  2173. --*/
  2174. ULONG BreakOnMcnDisable = FALSE;
  2175. VOID
  2176. ClassDisableMediaChangeDetection(
  2177. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  2178. )
  2179. {
  2180. PMEDIA_CHANGE_DETECTION_INFO info = FdoExtension->MediaChangeDetectionInfo;
  2181. PAGED_CODE();
  2182. if(info == NULL) {
  2183. return;
  2184. }
  2185. KeWaitForMutexObject(&info->MediaChangeMutex,
  2186. UserRequest,
  2187. KernelMode,
  2188. FALSE,
  2189. NULL);
  2190. info->MediaChangeDetectionDisableCount++;
  2191. DebugPrint((ClassDebugMCN, "ClassDisableMediaChangeDetection: "
  2192. "disable count is %d\n",
  2193. info->MediaChangeDetectionDisableCount));
  2194. KeReleaseMutex(&info->MediaChangeMutex, FALSE);
  2195. return;
  2196. } // end ClassDisableMediaChangeDetection()
  2197. /*++////////////////////////////////////////////////////////////////////////////
  2198. ClassCleanupMediaChangeDetection() ISSUE-2000/02/20-henrygab - why public?!
  2199. Routine Description:
  2200. This routine will cleanup any resources allocated for MCN. It is called
  2201. by classpnp during remove device, and therefore is not typically required
  2202. by external drivers.
  2203. Arguments:
  2204. Return Value:
  2205. --*/
  2206. VOID
  2207. ClassCleanupMediaChangeDetection(
  2208. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
  2209. )
  2210. {
  2211. PMEDIA_CHANGE_DETECTION_INFO info = FdoExtension->MediaChangeDetectionInfo;
  2212. PAGED_CODE()
  2213. if(info == NULL) {
  2214. return;
  2215. }
  2216. FdoExtension->MediaChangeDetectionInfo = NULL;
  2217. if (info->Gesn.Buffer) {
  2218. ExFreePool(info->Gesn.Buffer);
  2219. }
  2220. IoFreeIrp(info->MediaChangeIrp);
  2221. ExFreePool(info->SenseBuffer);
  2222. ExFreePool(info);
  2223. return;
  2224. } // end ClassCleanupMediaChangeDetection()
  2225. /*++////////////////////////////////////////////////////////////////////////////
  2226. ClasspMcnControl() - ISSUE-2000/02/20-henrygab - not documented
  2227. Routine Description:
  2228. This routine
  2229. Arguments:
  2230. DeviceObject -
  2231. Irp -
  2232. Return Value:
  2233. --*/
  2234. NTSTATUS
  2235. ClasspMcnControl(
  2236. IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  2237. IN PIRP Irp,
  2238. IN PSCSI_REQUEST_BLOCK Srb
  2239. )
  2240. {
  2241. PCOMMON_DEVICE_EXTENSION commonExtension =
  2242. (PCOMMON_DEVICE_EXTENSION) FdoExtension;
  2243. PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
  2244. PPREVENT_MEDIA_REMOVAL request = Irp->AssociatedIrp.SystemBuffer;
  2245. PFILE_OBJECT fileObject = irpStack->FileObject;
  2246. PFILE_OBJECT_EXTENSION fsContext = NULL;
  2247. NTSTATUS status = STATUS_SUCCESS;
  2248. PAGED_CODE();
  2249. //
  2250. // Check to make sure we have a file object extension to keep track of this
  2251. // request. If not we'll fail it before synchronizing.
  2252. //
  2253. TRY {
  2254. if(fileObject != NULL) {
  2255. fsContext = ClasspGetFsContext(commonExtension, fileObject);
  2256. }else if(Irp->RequestorMode == KernelMode) { // && fileObject == NULL
  2257. fsContext = &FdoExtension->KernelModeMcnContext;
  2258. }
  2259. if (fsContext == NULL) {
  2260. //
  2261. // This handle isn't setup correctly. We can't let the
  2262. // operation go.
  2263. //
  2264. status = STATUS_INVALID_PARAMETER;
  2265. LEAVE;
  2266. }
  2267. if(request->PreventMediaRemoval) {
  2268. //
  2269. // This is a lock command. Reissue the command in case bus or
  2270. // device was reset and the lock was cleared.
  2271. //
  2272. ClassDisableMediaChangeDetection(FdoExtension);
  2273. InterlockedIncrement(&(fsContext->McnDisableCount));
  2274. } else {
  2275. if(fsContext->McnDisableCount == 0) {
  2276. status = STATUS_INVALID_DEVICE_STATE;
  2277. LEAVE;
  2278. }
  2279. InterlockedDecrement(&(fsContext->McnDisableCount));
  2280. ClassEnableMediaChangeDetection(FdoExtension);
  2281. }
  2282. } FINALLY {
  2283. Irp->IoStatus.Status = status;
  2284. if(Srb) {
  2285. ExFreePool(Srb);
  2286. }
  2287. ClassReleaseRemoveLock(FdoExtension->DeviceObject, Irp);
  2288. ClassCompleteRequest(FdoExtension->DeviceObject,
  2289. Irp,
  2290. IO_NO_INCREMENT);
  2291. }
  2292. return status;
  2293. } // end ClasspMcnControl(
  2294. /*++////////////////////////////////////////////////////////////////////////////
  2295. ClasspMediaChangeRegistryCallBack()
  2296. Routine Description:
  2297. This callback for a registry SZ or MULTI_SZ is called once for each
  2298. SZ in the value. It will attempt to match the data with the
  2299. UNICODE_STRING passed in as Context, and modify EntryContext if a
  2300. match is found. Written for ClasspCheckRegistryForMediaChangeCompletion
  2301. Arguments:
  2302. ValueName - name of the key that was opened
  2303. ValueType - type of data stored in the value (REG_SZ for this routine)
  2304. ValueData - data in the registry, in this case a wide string
  2305. ValueLength - length of the data including the terminating null
  2306. Context - unicode string to compare against ValueData
  2307. EntryContext - should be initialized to 0, will be set to 1 if match found
  2308. Return Value:
  2309. STATUS_SUCCESS
  2310. EntryContext will be 1 if found
  2311. --*/
  2312. NTSTATUS
  2313. ClasspMediaChangeRegistryCallBack(
  2314. IN PWSTR ValueName,
  2315. IN ULONG ValueType,
  2316. IN PVOID ValueData,
  2317. IN ULONG ValueLength,
  2318. IN PVOID Context,
  2319. IN PVOID EntryContext
  2320. )
  2321. {
  2322. PULONG valueFound;
  2323. PUNICODE_STRING deviceString;
  2324. PWSTR keyValue;
  2325. PAGED_CODE();
  2326. UNREFERENCED_PARAMETER(ValueName);
  2327. //
  2328. // if we have already set the value to true, exit
  2329. //
  2330. valueFound = EntryContext;
  2331. if ((*valueFound) != 0) {
  2332. DebugPrint((ClassDebugMCN, "ClasspMcnRegCB: already set to true\n"));
  2333. return STATUS_SUCCESS;
  2334. }
  2335. if (ValueLength == sizeof(WCHAR)) {
  2336. DebugPrint((ClassDebugError, "ClasspMcnRegCB: NULL string should "
  2337. "never be passed to registry call-back!\n"));
  2338. return STATUS_SUCCESS;
  2339. }
  2340. //
  2341. // if the data is not a terminated string, exit
  2342. //
  2343. if (ValueType != REG_SZ) {
  2344. return STATUS_SUCCESS;
  2345. }
  2346. deviceString = Context;
  2347. keyValue = ValueData;
  2348. ValueLength -= sizeof(WCHAR); // ignore the null character
  2349. //
  2350. // do not compare more memory than is in deviceString
  2351. //
  2352. if (ValueLength > deviceString->Length) {
  2353. ValueLength = deviceString->Length;
  2354. }
  2355. //
  2356. // if the strings match, disable autorun
  2357. //
  2358. if (RtlCompareMemory(deviceString->Buffer, keyValue, ValueLength) == ValueLength) {
  2359. DebugPrint((ClassDebugMCN, "ClasspRegMcnCB: Match found\n"));
  2360. DebugPrint((ClassDebugMCN, "ClasspRegMcnCB: DeviceString at %p\n",
  2361. deviceString->Buffer));
  2362. DebugPrint((ClassDebugMCN, "ClasspRegMcnCB: KeyValue at %p\n",
  2363. keyValue));
  2364. (*valueFound) = TRUE;
  2365. }
  2366. return STATUS_SUCCESS;
  2367. } // end ClasspMediaChangeRegistryCallBack()
  2368. /*++////////////////////////////////////////////////////////////////////////////
  2369. ClasspTimerTick() - ISSUE-2000/02/20-henrygab - not documented
  2370. Routine Description:
  2371. This routine
  2372. Arguments:
  2373. DeviceObject -
  2374. Irp -
  2375. Return Value:
  2376. --*/
  2377. VOID
  2378. ClasspTimerTick(
  2379. PDEVICE_OBJECT DeviceObject,
  2380. PVOID Context
  2381. )
  2382. {
  2383. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
  2384. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  2385. ULONG isRemoved;
  2386. ASSERT(commonExtension->IsFdo);
  2387. //
  2388. // Do any media change work
  2389. //
  2390. isRemoved = ClassAcquireRemoveLock(DeviceObject, (PIRP)ClasspTimerTick);
  2391. //
  2392. // We stop the timer before deleting the device. It's safe to keep going
  2393. // if the flag value is REMOVE_PENDING because the removal thread will be
  2394. // blocked trying to stop the timer.
  2395. //
  2396. ASSERT(isRemoved != REMOVE_COMPLETE);
  2397. //
  2398. // This routine is reasonably safe even if the device object has a pending
  2399. // remove
  2400. if(!isRemoved) {
  2401. PFAILURE_PREDICTION_INFO info = fdoExtension->FailurePredictionInfo;
  2402. //
  2403. // Do any media change detection work
  2404. //
  2405. if (fdoExtension->MediaChangeDetectionInfo != NULL) {
  2406. ClassCheckMediaState(fdoExtension);
  2407. }
  2408. //
  2409. // Do any failure prediction work
  2410. //
  2411. if ((info != NULL) && (info->Method != FailurePredictionNone)) {
  2412. ULONG countDown;
  2413. ULONG active;
  2414. if (ClasspCanSendPollingIrp(fdoExtension)) {
  2415. //
  2416. // Synchronization is not required here since the Interlocked
  2417. // locked instruction guarantees atomicity. Other code that
  2418. // resets CountDown uses InterlockedExchange which is also
  2419. // atomic.
  2420. //
  2421. countDown = InterlockedDecrement(&info->CountDown);
  2422. if (countDown == 0) {
  2423. DebugPrint((4, "ClasspTimerTick: Send FP irp for %p\n",
  2424. DeviceObject));
  2425. if(info->WorkQueueItem == NULL) {
  2426. info->WorkQueueItem =
  2427. IoAllocateWorkItem(fdoExtension->DeviceObject);
  2428. if(info->WorkQueueItem == NULL) {
  2429. //
  2430. // Set the countdown to one minute in the future.
  2431. // we'll try again then in the hopes there's more
  2432. // free memory.
  2433. //
  2434. DebugPrint((1, "ClassTimerTick: Couldn't allocate "
  2435. "item - try again in one minute\n"));
  2436. InterlockedExchange(&info->CountDown, 60);
  2437. } else {
  2438. //
  2439. // Grab the remove lock so that removal will block
  2440. // until the work item is done.
  2441. //
  2442. ClassAcquireRemoveLock(fdoExtension->DeviceObject,
  2443. info->WorkQueueItem);
  2444. IoQueueWorkItem(info->WorkQueueItem,
  2445. ClasspFailurePredict,
  2446. DelayedWorkQueue,
  2447. info);
  2448. }
  2449. } else {
  2450. DebugPrint((3, "ClasspTimerTick: Failure "
  2451. "Prediction work item is "
  2452. "already active for device %p\n",
  2453. DeviceObject));
  2454. }
  2455. } // end (countdown == 0)
  2456. } else {
  2457. //
  2458. // If device is sleeping then just rearm polling timer
  2459. DebugPrint((4, "ClassTimerTick, SHHHH!!! device is %p is sleeping\n",
  2460. DeviceObject));
  2461. }
  2462. } // end failure prediction polling
  2463. //
  2464. // Give driver a chance to do its own specific work
  2465. //
  2466. if (commonExtension->DriverExtension->InitData.ClassTick != NULL) {
  2467. commonExtension->DriverExtension->InitData.ClassTick(DeviceObject);
  2468. } // end device specific tick handler
  2469. } // end check for removed
  2470. ClassReleaseRemoveLock(DeviceObject, (PIRP)ClasspTimerTick);
  2471. } // end ClasspTimerTick()
  2472. /*++////////////////////////////////////////////////////////////////////////////
  2473. ClasspEnableTimer() - ISSUE-2000/02/20-henrygab - not documented
  2474. Routine Description:
  2475. This routine
  2476. Arguments:
  2477. DeviceObject -
  2478. Irp -
  2479. Return Value:
  2480. --*/
  2481. NTSTATUS
  2482. ClasspEnableTimer(
  2483. PDEVICE_OBJECT DeviceObject
  2484. )
  2485. {
  2486. NTSTATUS status;
  2487. PAGED_CODE();
  2488. if (DeviceObject->Timer == NULL) {
  2489. status = IoInitializeTimer(DeviceObject, ClasspTimerTick, NULL);
  2490. } else {
  2491. status = STATUS_SUCCESS;
  2492. }
  2493. if (NT_SUCCESS(status)) {
  2494. IoStartTimer(DeviceObject);
  2495. DebugPrint((1, "ClasspEnableTimer: Once a second timer enabled "
  2496. "for device %p\n", DeviceObject));
  2497. }
  2498. DebugPrint((1, "ClasspEnableTimer: Device %p, Status %lx "
  2499. "initializing timer\n", DeviceObject, status));
  2500. return status;
  2501. } // end ClasspEnableTimer()
  2502. /*++////////////////////////////////////////////////////////////////////////////
  2503. ClasspDisableTimer() - ISSUE-2000/02/20-henrygab - not documented
  2504. Routine Description:
  2505. This routine
  2506. Arguments:
  2507. DeviceObject -
  2508. Irp -
  2509. Return Value:
  2510. --*/
  2511. NTSTATUS
  2512. ClasspDisableTimer(
  2513. PDEVICE_OBJECT DeviceObject
  2514. )
  2515. {
  2516. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
  2517. PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
  2518. PMEDIA_CHANGE_DETECTION_INFO mCDInfo = fdoExtension->MediaChangeDetectionInfo;
  2519. PFAILURE_PREDICTION_INFO fPInfo = fdoExtension->FailurePredictionInfo;
  2520. NTSTATUS status;
  2521. PAGED_CODE();
  2522. if (DeviceObject->Timer != NULL) {
  2523. //
  2524. // we are only going to stop the actual timer in remove device routine.
  2525. // it is the responsibility of the code within the timer routine to
  2526. // check if the device is removed and not processing io for the final
  2527. // call.
  2528. // this keeps the code clean and prevents lots of bugs.
  2529. //
  2530. IoStopTimer(DeviceObject);
  2531. DebugPrint((3, "ClasspDisableTimer: Once a second timer disabled "
  2532. "for device %p\n", DeviceObject));
  2533. } else {
  2534. DebugPrint((1, "ClasspDisableTimer: Timer never enabled\n"));
  2535. }
  2536. return STATUS_SUCCESS;
  2537. } // end ClasspDisableTimer()
  2538. /*++////////////////////////////////////////////////////////////////////////////
  2539. ClasspFailurePredict() - ISSUE-2000/02/20-henrygab - not documented
  2540. Routine Description:
  2541. This routine
  2542. Arguments:
  2543. DeviceObject -
  2544. Irp -
  2545. Return Value:
  2546. Note: this function can be called (via the workitem callback) after the paging device is shut down,
  2547. so it must be PAGE LOCKED.
  2548. --*/
  2549. VOID
  2550. ClasspFailurePredict(
  2551. IN PDEVICE_OBJECT DeviceObject,
  2552. IN PFAILURE_PREDICTION_INFO Info
  2553. )
  2554. {
  2555. PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
  2556. PIO_WORKITEM workItem;
  2557. STORAGE_PREDICT_FAILURE checkFailure = {0};
  2558. SCSI_ADDRESS scsiAddress = {0};
  2559. NTSTATUS status;
  2560. ASSERT(Info != NULL);
  2561. DebugPrint((1, "ClasspFailurePredict: Polling for failure\n"));
  2562. //
  2563. // Mark the work item as inactive and reset the countdown timer. we
  2564. // can't risk freeing the work item until we've released the remove-lock
  2565. // though - if we do it might get resused as a tag before we can release
  2566. // the lock.
  2567. //
  2568. InterlockedExchange(&Info->CountDown, Info->Period);
  2569. workItem = InterlockedExchangePointer(&(Info->WorkQueueItem), NULL);
  2570. if (ClasspCanSendPollingIrp(fdoExtension)) {
  2571. KEVENT event;
  2572. PDEVICE_OBJECT topOfStack;
  2573. PIRP irp = NULL;
  2574. IO_STATUS_BLOCK ioStatus;
  2575. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  2576. topOfStack = IoGetAttachedDeviceReference(DeviceObject);
  2577. //
  2578. // Send down irp to see if drive is predicting failure
  2579. //
  2580. irp = IoBuildDeviceIoControlRequest(
  2581. IOCTL_STORAGE_PREDICT_FAILURE,
  2582. topOfStack,
  2583. NULL,
  2584. 0,
  2585. &checkFailure,
  2586. sizeof(STORAGE_PREDICT_FAILURE),
  2587. FALSE,
  2588. &event,
  2589. &ioStatus);
  2590. if (irp != NULL) {
  2591. status = IoCallDriver(topOfStack, irp);
  2592. if (status == STATUS_PENDING) {
  2593. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  2594. status = ioStatus.Status;
  2595. }
  2596. } else {
  2597. status = STATUS_INSUFFICIENT_RESOURCES;
  2598. }
  2599. if (NT_SUCCESS(status) && (checkFailure.PredictFailure)) {
  2600. checkFailure.PredictFailure = 512;
  2601. //
  2602. // Send down irp to get scsi address
  2603. //
  2604. KeInitializeEvent(&event, SynchronizationEvent, FALSE);
  2605. RtlZeroMemory(&scsiAddress, sizeof(SCSI_ADDRESS));
  2606. irp = IoBuildDeviceIoControlRequest(
  2607. IOCTL_SCSI_GET_ADDRESS,
  2608. topOfStack,
  2609. NULL,
  2610. 0,
  2611. &scsiAddress,
  2612. sizeof(SCSI_ADDRESS),
  2613. FALSE,
  2614. &event,
  2615. &ioStatus);
  2616. if (irp != NULL) {
  2617. status = IoCallDriver(topOfStack, irp);
  2618. if (status == STATUS_PENDING) {
  2619. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  2620. status = ioStatus.Status;
  2621. }
  2622. }
  2623. ClassNotifyFailurePredicted(fdoExtension,
  2624. (PUCHAR)&checkFailure,
  2625. sizeof(checkFailure),
  2626. (BOOLEAN)(fdoExtension->FailurePredicted == FALSE),
  2627. 2,
  2628. scsiAddress.PathId,
  2629. scsiAddress.TargetId,
  2630. scsiAddress.Lun);
  2631. fdoExtension->FailurePredicted = TRUE;
  2632. }
  2633. ObDereferenceObject(topOfStack);
  2634. }
  2635. ClassReleaseRemoveLock(DeviceObject, (PIRP) workItem);
  2636. IoFreeWorkItem(workItem);
  2637. return;
  2638. } // end ClasspFailurePredict()
  2639. /*++////////////////////////////////////////////////////////////////////////////
  2640. ClassNotifyFailurePredicted() ISSUE-alanwar-2000/02/20 - not documented
  2641. Routine Description:
  2642. Arguments:
  2643. Return Value:
  2644. --*/
  2645. VOID
  2646. ClassNotifyFailurePredicted(
  2647. PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  2648. PUCHAR Buffer,
  2649. ULONG BufferSize,
  2650. BOOLEAN LogError,
  2651. ULONG UniqueErrorValue,
  2652. UCHAR PathId,
  2653. UCHAR TargetId,
  2654. UCHAR Lun
  2655. )
  2656. {
  2657. PIO_ERROR_LOG_PACKET logEntry;
  2658. DebugPrint((1, "ClasspFailurePredictPollCompletion: Failure predicted for device %p\n", FdoExtension->DeviceObject));
  2659. //
  2660. // Fire off a WMI event
  2661. //
  2662. ClassWmiFireEvent(FdoExtension->DeviceObject,
  2663. &StoragePredictFailureEventGuid,
  2664. 0,
  2665. BufferSize,
  2666. Buffer);
  2667. //
  2668. // Log an error into the eventlog
  2669. //
  2670. if (LogError)
  2671. {
  2672. logEntry = IoAllocateErrorLogEntry(
  2673. FdoExtension->DeviceObject,
  2674. sizeof(IO_ERROR_LOG_PACKET) + (3 * sizeof(ULONG)));
  2675. if (logEntry != NULL)
  2676. {
  2677. logEntry->FinalStatus = STATUS_SUCCESS;
  2678. logEntry->ErrorCode = IO_WRN_FAILURE_PREDICTED;
  2679. logEntry->SequenceNumber = 0;
  2680. logEntry->MajorFunctionCode = IRP_MJ_DEVICE_CONTROL;
  2681. logEntry->IoControlCode = IOCTL_STORAGE_PREDICT_FAILURE;
  2682. logEntry->RetryCount = 0;
  2683. logEntry->UniqueErrorValue = UniqueErrorValue;
  2684. logEntry->DumpDataSize = 3;
  2685. logEntry->DumpData[0] = PathId;
  2686. logEntry->DumpData[1] = TargetId;
  2687. logEntry->DumpData[2] = Lun;
  2688. //
  2689. // Write the error log packet.
  2690. //
  2691. IoWriteErrorLogEntry(logEntry);
  2692. }
  2693. }
  2694. } // end ClassNotifyFailurePredicted()
  2695. /*++////////////////////////////////////////////////////////////////////////////
  2696. ClassSetFailurePredictionPoll()
  2697. Routine Description:
  2698. This routine enables polling for failure prediction, setting the timer
  2699. to fire every N seconds as specified by the PollingPeriod.
  2700. Arguments:
  2701. FdoExtension - the device to setup failure prediction for.
  2702. FailurePredictionMethod - specific failure prediction method to use
  2703. if set to FailurePredictionNone, will disable failure detection
  2704. PollingPeriod - if 0 then no change to current polling timer
  2705. Return Value:
  2706. NT Status
  2707. --*/
  2708. NTSTATUS
  2709. ClassSetFailurePredictionPoll(
  2710. PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
  2711. FAILURE_PREDICTION_METHOD FailurePredictionMethod,
  2712. ULONG PollingPeriod
  2713. )
  2714. {
  2715. PFAILURE_PREDICTION_INFO info;
  2716. NTSTATUS status;
  2717. DEVICE_POWER_STATE powerState;
  2718. PAGED_CODE();
  2719. if (FdoExtension->FailurePredictionInfo == NULL) {
  2720. if (FailurePredictionMethod != FailurePredictionNone) {
  2721. info = ExAllocatePoolWithTag(NonPagedPool,
  2722. sizeof(FAILURE_PREDICTION_INFO),
  2723. CLASS_TAG_FAILURE_PREDICT);
  2724. if (info == NULL) {
  2725. return STATUS_INSUFFICIENT_RESOURCES;
  2726. }
  2727. KeInitializeEvent(&info->Event, SynchronizationEvent, TRUE);
  2728. info->WorkQueueItem = NULL;
  2729. info->Period = DEFAULT_FAILURE_PREDICTION_PERIOD;
  2730. } else {
  2731. //
  2732. // FaultPrediction has not been previously initialized, nor
  2733. // is it being initialized now. No need to do anything.
  2734. //
  2735. return STATUS_SUCCESS;
  2736. }
  2737. FdoExtension->FailurePredictionInfo = info;
  2738. } else {
  2739. info = FdoExtension->FailurePredictionInfo;
  2740. }
  2741. /*
  2742. * Make sure the user-mode thread is not suspended while we hold the synchronization event.
  2743. */
  2744. KeEnterCriticalRegion();
  2745. KeWaitForSingleObject(&info->Event,
  2746. UserRequest,
  2747. KernelMode,
  2748. FALSE,
  2749. NULL);
  2750. //
  2751. // Reset polling period and counter. Setup failure detection type
  2752. //
  2753. if (PollingPeriod != 0) {
  2754. InterlockedExchange(&info->Period, PollingPeriod);
  2755. }
  2756. InterlockedExchange(&info->CountDown, info->Period);
  2757. info->Method = FailurePredictionMethod;
  2758. if (FailurePredictionMethod != FailurePredictionNone) {
  2759. status = ClasspEnableTimer(FdoExtension->DeviceObject);
  2760. if (NT_SUCCESS(status)) {
  2761. DebugPrint((3, "ClassEnableFailurePredictPoll: Enabled for "
  2762. "device %p\n", FdoExtension->DeviceObject));
  2763. }
  2764. } else {
  2765. status = ClasspDisableTimer(FdoExtension->DeviceObject);
  2766. DebugPrint((3, "ClassEnableFailurePredictPoll: Disabled for "
  2767. "device %p\n", FdoExtension->DeviceObject));
  2768. status = STATUS_SUCCESS;
  2769. }
  2770. KeSetEvent(&info->Event, IO_NO_INCREMENT, FALSE);
  2771. KeLeaveCriticalRegion();
  2772. return status;
  2773. } // end ClassSetFailurePredictionPoll()