PageRenderTime 76ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/drivers/storage/classpnp/autorun.c

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