PageRenderTime 69ms CodeModel.GetById 28ms 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

Large files files are truncated, but you can click here to view the full file

  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_TRANSF

Large files files are truncated, but you can click here to view the full file