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

1055 lines
31 KiB

  1. /*++
  2. Copyright (c) 1990 Microsoft Corporation
  3. Module Name:
  4. lazyrite.c
  5. Abstract:
  6. This module implements the lazy writer for the Cache subsystem.
  7. Author:
  8. Tom Miller [TomM] 22-July-1990
  9. Revision History:
  10. --*/
  11. #include "cc.h"
  12. //
  13. // The Bug check file id for this module
  14. //
  15. #define BugCheckFileId (CACHE_BUG_CHECK_LAZYRITE)
  16. //
  17. // Define our debug constant
  18. //
  19. #define me 0x00000020
  20. //
  21. // Local support routines
  22. //
  23. PWORK_QUEUE_ENTRY
  24. CcReadWorkQueue (
  25. );
  26. VOID
  27. CcLazyWriteScan (
  28. );
  29. VOID
  30. CcScheduleLazyWriteScan (
  31. IN BOOLEAN FastScan
  32. )
  33. /*++
  34. Routine Description:
  35. This routine may be called to schedule the next lazy writer scan,
  36. during which lazy write and lazy close activity is posted to other
  37. worker threads. Callers should acquire the lazy writer spin lock
  38. to see if the scan is currently active, and then call this routine
  39. still holding the spin lock if not. One special call is used at
  40. the end of the lazy write scan to propagate lazy write active once
  41. we go active. This call is "the" scan thread, and it can therefore
  42. safely schedule the next scan without taking out the spin lock.
  43. Arguments:
  44. FastScan - if set, make the scan happen immediately
  45. Return Value:
  46. None.
  47. --*/
  48. {
  49. //
  50. // It is important to set the active flag TRUE first for the propagate
  51. // case, because it is conceivable that once the timer is set, another
  52. // thread could actually run and make the scan go idle before we then
  53. // jam the flag TRUE.
  54. //
  55. // When going from idle to active, we delay a little longer to let the
  56. // app finish saving its file.
  57. //
  58. if (FastScan) {
  59. LazyWriter.ScanActive = TRUE;
  60. KeSetTimer( &LazyWriter.ScanTimer, CcNoDelay, &LazyWriter.ScanDpc );
  61. } else if (LazyWriter.ScanActive) {
  62. KeSetTimer( &LazyWriter.ScanTimer, CcIdleDelay, &LazyWriter.ScanDpc );
  63. } else {
  64. LazyWriter.ScanActive = TRUE;
  65. KeSetTimer( &LazyWriter.ScanTimer, CcFirstDelay, &LazyWriter.ScanDpc );
  66. }
  67. }
  68. VOID
  69. CcScanDpc (
  70. IN PKDPC Dpc,
  71. IN PVOID DeferredContext,
  72. IN PVOID SystemArgument1,
  73. IN PVOID SystemArgument2
  74. )
  75. /*++
  76. Routine Description:
  77. This is the Dpc routine which runs when the scan timer goes off. It
  78. simply posts an element for an Ex Worker thread to do the scan.
  79. Arguments:
  80. (All are ignored)
  81. Return Value:
  82. None.
  83. --*/
  84. {
  85. PWORK_QUEUE_ENTRY WorkQueueEntry;
  86. UNREFERENCED_PARAMETER(Dpc);
  87. UNREFERENCED_PARAMETER(DeferredContext);
  88. UNREFERENCED_PARAMETER(SystemArgument1);
  89. UNREFERENCED_PARAMETER(SystemArgument2);
  90. WorkQueueEntry = CcAllocateWorkQueueEntry();
  91. //
  92. // If we failed to allocate a WorkQueueEntry, things must
  93. // be in pretty bad shape. However, all we have to do is
  94. // say we are not active, and wait for another event to
  95. // wake things up again.
  96. //
  97. if (WorkQueueEntry == NULL) {
  98. LazyWriter.ScanActive = FALSE;
  99. } else {
  100. //
  101. // Otherwise post a work queue entry to do the scan.
  102. //
  103. WorkQueueEntry->Function = (UCHAR)LazyWriteScan;
  104. CcPostWorkQueue( WorkQueueEntry, &CcRegularWorkQueue );
  105. }
  106. }
  107. NTSTATUS
  108. CcWaitForCurrentLazyWriterActivity (
  109. )
  110. /*++
  111. Routine Description:
  112. This routine allows a thread to receive notification when the current tick
  113. of lazy writer work has completed. It must not be called within a lazy
  114. writer workitem! The caller must not be holding synchronization that could
  115. block a Cc workitem!
  116. In particular, this lets a caller insure that all available lazy closes at
  117. the time of the call have completed.
  118. Arguments:
  119. None.
  120. Return Value:
  121. Final result of the wait.
  122. --*/
  123. {
  124. KIRQL OldIrql;
  125. KEVENT Event;
  126. PWORK_QUEUE_ENTRY WorkQueueEntry;
  127. WorkQueueEntry = CcAllocateWorkQueueEntry();
  128. if (WorkQueueEntry == NULL) {
  129. return STATUS_INSUFFICIENT_RESOURCES;
  130. }
  131. WorkQueueEntry->Function = (UCHAR)EventSet;
  132. KeInitializeEvent( &Event, NotificationEvent, FALSE );
  133. WorkQueueEntry->Parameters.Event.Event = &Event;
  134. //
  135. // Add this to the post-tick work queue and wake the lazy writer for it.
  136. // The lazy writer will add this to the end of the next batch of work
  137. // he issues.
  138. //
  139. CcAcquireMasterLock( &OldIrql );
  140. InsertTailList( &CcPostTickWorkQueue, &WorkQueueEntry->WorkQueueLinks );
  141. LazyWriter.OtherWork = TRUE;
  142. if (!LazyWriter.ScanActive) {
  143. CcScheduleLazyWriteScan( TRUE );
  144. }
  145. CcReleaseMasterLock( OldIrql );
  146. return KeWaitForSingleObject( &Event, Executive, KernelMode, FALSE, NULL );
  147. }
  148. VOID
  149. CcLazyWriteScan (
  150. )
  151. /*++
  152. Routine Description:
  153. This routine implements the Lazy Writer scan for dirty data to flush
  154. or any other work to do (lazy close). This routine is scheduled by
  155. calling CcScheduleLazyWriteScan.
  156. Arguments:
  157. None.
  158. Return Value:
  159. None.
  160. --*/
  161. {
  162. ULONG PagesToWrite, ForegroundRate, EstimatedDirtyNextInterval;
  163. PSHARED_CACHE_MAP SharedCacheMap, FirstVisited, NextSharedCacheMap;
  164. KIRQL OldIrql;
  165. ULONG LoopsWithLockHeld = 0;
  166. BOOLEAN AlreadyMoved = FALSE;
  167. BOOLEAN MoveBehindCursor = FALSE;
  168. LIST_ENTRY PostTickWorkQueue;
  169. //
  170. // Top of Lazy Writer scan.
  171. //
  172. try {
  173. //
  174. // If there is no work to do, then we will go inactive, and return.
  175. //
  176. CcAcquireMasterLock( &OldIrql );
  177. if ((CcTotalDirtyPages == 0) && !LazyWriter.OtherWork) {
  178. //
  179. // Sleep if there are no deferred writes. It is important to check
  180. // proactively because writes may be blocked for reasons external
  181. // to the cache manager. The lazy writer must keep poking since it
  182. // may have no bytes to write itself.
  183. //
  184. #if DBG
  185. //
  186. // In DBG builds, make sure that the CcDirtySharedCacheMapList
  187. // is really empty (except for the cursor) if we are going to sleep
  188. // because we think there is no more work to do.
  189. //
  190. {
  191. PLIST_ENTRY CurrentEntry = CcDirtySharedCacheMapList.SharedCacheMapLinks.Flink;
  192. PSHARED_CACHE_MAP CurrentScm;
  193. ULONG Count = 0;
  194. while( CurrentEntry != &CcDirtySharedCacheMapList.SharedCacheMapLinks ) {
  195. CurrentScm = CONTAINING_RECORD( CurrentEntry,
  196. SHARED_CACHE_MAP,
  197. SharedCacheMapLinks );
  198. if (FlagOn(CurrentScm->Flags, WAITING_FOR_TEARDOWN)) {
  199. Count++;
  200. }
  201. CurrentEntry = CurrentEntry->Flink;
  202. }
  203. ASSERTMSG( "CcLazyWriteScan stopped scan while SCM with the flag WAITING_FOR_TEARDOWN are still in the dirty list!\n",
  204. Count == 0 );
  205. }
  206. #endif
  207. if (IsListEmpty(&CcDeferredWrites)) {
  208. LazyWriter.ScanActive = FALSE;
  209. CcReleaseMasterLock( OldIrql );
  210. } else {
  211. CcReleaseMasterLock( OldIrql );
  212. //
  213. // Check for writes and schedule the next scan.
  214. //
  215. CcPostDeferredWrites();
  216. CcScheduleLazyWriteScan( FALSE );
  217. }
  218. return;
  219. }
  220. //
  221. // Pull out the post tick workitems for this pass. It is important that
  222. // we are doing this at the top since more could be queued as we rummage
  223. // for work to do. Post tick workitems are guaranteed to occur after all
  224. // work generated in a complete scan.
  225. //
  226. InitializeListHead( &PostTickWorkQueue );
  227. while (!IsListEmpty( &CcPostTickWorkQueue )) {
  228. PLIST_ENTRY Entry = RemoveHeadList( &CcPostTickWorkQueue );
  229. InsertTailList( &PostTickWorkQueue, Entry );
  230. }
  231. //
  232. // Calculate the next sweep time stamp, then update all relevant fields for
  233. // the next time around. Also we can clear the OtherWork flag.
  234. //
  235. LazyWriter.OtherWork = FALSE;
  236. //
  237. // Assume we will write our usual fraction of dirty pages. Do not do the
  238. // divide if there is not enough dirty pages, or else we will never write
  239. // the last few pages.
  240. //
  241. PagesToWrite = CcTotalDirtyPages;
  242. if (PagesToWrite > LAZY_WRITER_MAX_AGE_TARGET) {
  243. PagesToWrite /= LAZY_WRITER_MAX_AGE_TARGET;
  244. }
  245. //
  246. // Estimate the rate of dirty pages being produced in the foreground.
  247. // This is the total number of dirty pages now plus the number of dirty
  248. // pages we scheduled to write last time, minus the number of dirty
  249. // pages we have now. Throw out any cases which would not produce a
  250. // positive rate.
  251. //
  252. ForegroundRate = 0;
  253. if ((CcTotalDirtyPages + CcPagesWrittenLastTime) > CcDirtyPagesLastScan) {
  254. ForegroundRate = (CcTotalDirtyPages + CcPagesWrittenLastTime) -
  255. CcDirtyPagesLastScan;
  256. }
  257. //
  258. // If we estimate that we will exceed our dirty page target by the end
  259. // of this interval, then we must write more. Try to arrive on target.
  260. //
  261. EstimatedDirtyNextInterval = CcTotalDirtyPages - PagesToWrite + ForegroundRate;
  262. if (EstimatedDirtyNextInterval > CcDirtyPageTarget) {
  263. PagesToWrite += EstimatedDirtyNextInterval - CcDirtyPageTarget;
  264. }
  265. //
  266. // Now save away the number of dirty pages and the number of pages we
  267. // just calculated to write.
  268. //
  269. CcDirtyPagesLastScan = CcTotalDirtyPages;
  270. CcPagesYetToWrite = CcPagesWrittenLastTime = PagesToWrite;
  271. //
  272. // Loop to flush enough Shared Cache Maps to write the number of pages
  273. // we just calculated.
  274. //
  275. SharedCacheMap = CONTAINING_RECORD( CcLazyWriterCursor.SharedCacheMapLinks.Flink,
  276. SHARED_CACHE_MAP,
  277. SharedCacheMapLinks );
  278. DebugTrace( 0, me, "Start of Lazy Writer Scan\n", 0 );
  279. //
  280. // Normally we would just like to visit every Cache Map once on each scan,
  281. // so the scan will terminate normally when we return to FirstVisited. But
  282. // in the off chance that FirstVisited gets deleted, we are guaranteed to stop
  283. // when we get back to our own listhead.
  284. //
  285. FirstVisited = NULL;
  286. while ((SharedCacheMap != FirstVisited) &&
  287. (&SharedCacheMap->SharedCacheMapLinks != &CcLazyWriterCursor.SharedCacheMapLinks)) {
  288. if (FirstVisited == NULL) {
  289. FirstVisited = SharedCacheMap;
  290. }
  291. //
  292. // Skip the SharedCacheMap if a write behind request is
  293. // already queued, write behind has been disabled, or
  294. // if there is no work to do (either dirty data to be written
  295. // or a delete is required).
  296. //
  297. // Note that for streams where modified writing is disabled, we
  298. // need to take out Bcbs exclusive, which serializes with foreground
  299. // activity. Therefore we use a special counter in the SharedCacheMap
  300. // to only service these once every n intervals.
  301. //
  302. // Skip temporary files unless we currently could not write as many
  303. // bytes as we might charge some hapless thread for throttling, unless
  304. // it has been closed. We assume that the "tick" of the lazy writer,
  305. // delayed temporarily by the passcount check, will permit the common
  306. // open/write/close/delete action on temporary files to sneak in and
  307. // truncate the file before we really write the data, if the file was
  308. // not opened delete-on-close to begin with.
  309. //
  310. // Since we will write closed files with dirty pages as part of the
  311. // regular pass (even temporary ones), only do lazy close on files
  312. // with no dirty pages.
  313. //
  314. if (!FlagOn(SharedCacheMap->Flags, WRITE_QUEUED | IS_CURSOR)
  315. &&
  316. (((SharedCacheMap->DirtyPages != 0)
  317. &&
  318. (FlagOn(SharedCacheMap->Flags, WAITING_FOR_TEARDOWN)
  319. ||
  320. ((PagesToWrite != 0)
  321. &&
  322. (((++SharedCacheMap->LazyWritePassCount & 0xF) == 0) ||
  323. !FlagOn(SharedCacheMap->Flags, MODIFIED_WRITE_DISABLED) ||
  324. (CcCapturedSystemSize == MmSmallSystem) ||
  325. (SharedCacheMap->DirtyPages >= (4 * (MAX_WRITE_BEHIND / PAGE_SIZE))))
  326. &&
  327. (!FlagOn(SharedCacheMap->FileObject->Flags, FO_TEMPORARY_FILE) ||
  328. (SharedCacheMap->OpenCount == 0) ||
  329. !CcCanIWrite(SharedCacheMap->FileObject, WRITE_CHARGE_THRESHOLD, FALSE, MAXUCHAR)))))
  330. ||
  331. ((SharedCacheMap->OpenCount == 0) &&
  332. (SharedCacheMap->DirtyPages == 0) ||
  333. (SharedCacheMap->FileSize.QuadPart == 0)))) {
  334. PWORK_QUEUE_ENTRY WorkQueueEntry;
  335. //
  336. // If this is a metadata stream with at least 4 times
  337. // the maximum write behind I/O size, then let's tell
  338. // this guy to write 1/8 of his dirty data on this pass
  339. // so it doesn't build up.
  340. //
  341. // Else assume we can write everything (PagesToWrite only affects
  342. // metadata streams - otherwise writing is controlled by the Mbcb -
  343. // this throttle is engaged in CcWriteBehind).
  344. //
  345. SharedCacheMap->PagesToWrite = SharedCacheMap->DirtyPages;
  346. if (FlagOn(SharedCacheMap->Flags, MODIFIED_WRITE_DISABLED) &&
  347. (SharedCacheMap->PagesToWrite >= (4 * (MAX_WRITE_BEHIND / PAGE_SIZE))) &&
  348. (CcCapturedSystemSize != MmSmallSystem)) {
  349. SharedCacheMap->PagesToWrite /= 8;
  350. }
  351. //
  352. // If still searching for pages to write, adjust our targets.
  353. //
  354. if (!AlreadyMoved) {
  355. //
  356. // See if he exhausts the number of pages to write. (We
  357. // keep going in case there are any closes to do.)
  358. //
  359. if (SharedCacheMap->PagesToWrite >= PagesToWrite) {
  360. //
  361. // Here is where we should move the cursor to. Figure
  362. // out if we should resume on this stream or the next one.
  363. //
  364. //
  365. // For Metadata streams, set up to resume on the next stream on the
  366. // next scan. Also force a push forward every n intervals if all of
  367. // the pages came from this stream, so we don't get preoccupied with
  368. // one stream at the expense of others (which may be waiting for a
  369. // lazy close). Normally we would like to avoid seek overhead and
  370. // take the common case of a large sequential series of writes.
  371. //
  372. // This is similar to hotspot detection.
  373. //
  374. // Note, to ensure that we iterate through the entire
  375. // CcDirtySharedCacheMap list, we cannot move this shared
  376. // cache map behind the cursor now. We will just
  377. // remember that we want to move this to the end of the
  378. // list and do the actual move when we are ready to read
  379. // the next entry.
  380. //
  381. if (FlagOn(SharedCacheMap->Flags, MODIFIED_WRITE_DISABLED) ||
  382. ((FirstVisited == SharedCacheMap) &&
  383. ((SharedCacheMap->LazyWritePassCount & 0xF) == 0))) {
  384. MoveBehindCursor = TRUE;
  385. //
  386. // For other streams, set up to resume on the same stream on the
  387. // next scan.
  388. //
  389. } else {
  390. RemoveEntryList( &CcLazyWriterCursor.SharedCacheMapLinks );
  391. InsertTailList( &SharedCacheMap->SharedCacheMapLinks, &CcLazyWriterCursor.SharedCacheMapLinks );
  392. }
  393. PagesToWrite = 0;
  394. AlreadyMoved = TRUE;
  395. } else {
  396. PagesToWrite -= SharedCacheMap->PagesToWrite;
  397. }
  398. }
  399. //
  400. // Otherwise show we are actively writing, and keep it in the dirty
  401. // list.
  402. //
  403. SetFlag(SharedCacheMap->Flags, WRITE_QUEUED);
  404. SharedCacheMap->DirtyPages += 1;
  405. CcReleaseMasterLock( OldIrql );
  406. //
  407. // Queue the request to do the work to a worker thread.
  408. //
  409. WorkQueueEntry = CcAllocateWorkQueueEntry();
  410. //
  411. // If we failed to allocate a WorkQueueEntry, things must
  412. // be in pretty bad shape. However, all we have to do is
  413. // break out of our current loop, and try to go back and
  414. // delay a while. Even if the current guy should have gone
  415. // away when we clear WRITE_QUEUED, we will find him again
  416. // in the LW scan.
  417. //
  418. if (WorkQueueEntry == NULL) {
  419. CcAcquireMasterLock( &OldIrql );
  420. ClearFlag(SharedCacheMap->Flags, WRITE_QUEUED);
  421. SharedCacheMap->DirtyPages -= 1;
  422. break;
  423. }
  424. WorkQueueEntry->Function = (UCHAR)WriteBehind;
  425. WorkQueueEntry->Parameters.Write.SharedCacheMap = SharedCacheMap;
  426. //
  427. // Post it to the regular work queue.
  428. //
  429. CcAcquireMasterLock( &OldIrql );
  430. SharedCacheMap->DirtyPages -= 1;
  431. if (FlagOn( SharedCacheMap->Flags, WAITING_FOR_TEARDOWN )) {
  432. //
  433. // If we are waiting for this shared cache map to be torn
  434. // down, put it at the head of the express work queue so
  435. // that it gets processed right away.
  436. //
  437. CcPostWorkQueue( WorkQueueEntry, &CcExpressWorkQueue );
  438. } else {
  439. //
  440. // We aren't anxiously awaiting for this shared cached map
  441. // to go away, so just process this work item via the
  442. // regular work queue.
  443. //
  444. CcPostWorkQueue( WorkQueueEntry, &CcRegularWorkQueue );
  445. }
  446. LoopsWithLockHeld = 0;
  447. //
  448. // Make sure we occasionally drop the lock. Set WRITE_QUEUED
  449. // to keep the guy from going away.
  450. //
  451. } else if ((++LoopsWithLockHeld >= 20) &&
  452. !FlagOn(SharedCacheMap->Flags, WRITE_QUEUED | IS_CURSOR)) {
  453. SetFlag(SharedCacheMap->Flags, WRITE_QUEUED);
  454. SharedCacheMap->DirtyPages += 1;
  455. CcReleaseMasterLock( OldIrql );
  456. LoopsWithLockHeld = 0;
  457. CcAcquireMasterLock( &OldIrql );
  458. ClearFlag(SharedCacheMap->Flags, WRITE_QUEUED);
  459. SharedCacheMap->DirtyPages -= 1;
  460. }
  461. //
  462. // Now loop back.
  463. //
  464. // If we want to put this shared cache map at the end of the
  465. // dirty list, we will do it AFTER we determine the next shared
  466. // cache map to go to. This ensures that we loop through the entire
  467. // list during this scan tick.
  468. //
  469. NextSharedCacheMap =
  470. CONTAINING_RECORD( SharedCacheMap->SharedCacheMapLinks.Flink,
  471. SHARED_CACHE_MAP,
  472. SharedCacheMapLinks );
  473. if (MoveBehindCursor) {
  474. RemoveEntryList( &CcLazyWriterCursor.SharedCacheMapLinks );
  475. InsertHeadList( &SharedCacheMap->SharedCacheMapLinks, &CcLazyWriterCursor.SharedCacheMapLinks );
  476. MoveBehindCursor = FALSE;
  477. }
  478. SharedCacheMap = NextSharedCacheMap;
  479. }
  480. DebugTrace( 0, me, "End of Lazy Writer Scan\n", 0 );
  481. //
  482. // Queue up our post tick workitems for this pass.
  483. //
  484. while (!IsListEmpty( &PostTickWorkQueue )) {
  485. PLIST_ENTRY Entry = RemoveHeadList( &PostTickWorkQueue );
  486. CcPostWorkQueue( CONTAINING_RECORD( Entry, WORK_QUEUE_ENTRY, WorkQueueLinks ),
  487. &CcRegularWorkQueue );
  488. }
  489. //
  490. // Now we can release the global list and loop back, per chance to sleep.
  491. //
  492. CcReleaseMasterLock( OldIrql );
  493. //
  494. // Once again we need to give the deferred writes a poke. We can have all dirty
  495. // pages on disable_write_behind files but also have an external condition that
  496. // caused the cached IO to be deferred. If so, this serves as our only chance to
  497. // issue it when the condition clears.
  498. //
  499. // Case hit on ForrestF's 5gb Alpha, 1/12/99.
  500. //
  501. if (!IsListEmpty(&CcDeferredWrites)) {
  502. CcPostDeferredWrites();
  503. }
  504. //
  505. // Now go ahead and schedule the next scan.
  506. //
  507. CcScheduleLazyWriteScan( FALSE );
  508. //
  509. // Basically, the Lazy Writer thread should never get an exception,
  510. // so we put a try-except around it that bug checks one way or the other.
  511. // Better we bug check here than worry about what happens if we let one
  512. // get by.
  513. //
  514. } except( CcExceptionFilter( GetExceptionCode() )) {
  515. CcBugCheck( GetExceptionCode(), 0, 0 );
  516. }
  517. }
  518. //
  519. // Internal support routine
  520. //
  521. LONG
  522. CcExceptionFilter (
  523. IN NTSTATUS ExceptionCode
  524. )
  525. /*++
  526. Routine Description:
  527. This is the standard exception filter for worker threads which simply
  528. calls an FsRtl routine to see if an expected status is being raised.
  529. If so, the exception is handled, else we bug check.
  530. Arguments:
  531. ExceptionCode - the exception code which was raised.
  532. Return Value:
  533. EXCEPTION_EXECUTE_HANDLER if expected, else a Bug Check occurs.
  534. --*/
  535. {
  536. DebugTrace(0, 0, "CcExceptionFilter %08lx\n", ExceptionCode);
  537. if (FsRtlIsNtstatusExpected( ExceptionCode )) {
  538. return EXCEPTION_EXECUTE_HANDLER;
  539. } else {
  540. return EXCEPTION_CONTINUE_SEARCH;
  541. }
  542. }
  543. //
  544. // Internal support routine
  545. //
  546. VOID
  547. FASTCALL
  548. CcPostWorkQueue (
  549. IN PWORK_QUEUE_ENTRY WorkQueueEntry,
  550. IN PLIST_ENTRY WorkQueue
  551. )
  552. /*++
  553. Routine Description:
  554. This routine queues a WorkQueueEntry, which has been allocated and
  555. initialized by the caller, to the WorkQueue for FIFO processing by
  556. the work threads.
  557. Arguments:
  558. WorkQueueEntry - supplies a pointer to the entry to queue
  559. Return Value:
  560. None
  561. --*/
  562. {
  563. KIRQL OldIrql;
  564. PLIST_ENTRY WorkerThreadEntry = NULL;
  565. ASSERT(FIELD_OFFSET(WORK_QUEUE_ITEM, List) == 0);
  566. DebugTrace(+1, me, "CcPostWorkQueue:\n", 0 );
  567. DebugTrace( 0, me, " WorkQueueEntry = %08lx\n", WorkQueueEntry );
  568. //
  569. // Queue the entry to the respective work queue.
  570. //
  571. CcAcquireWorkQueueLock( &OldIrql );
  572. InsertTailList( WorkQueue, &WorkQueueEntry->WorkQueueLinks );
  573. //
  574. // Now, if we aren't throttled and have any more idle threads we can
  575. // use, activate one.
  576. //
  577. if (!CcQueueThrottle && !IsListEmpty(&CcIdleWorkerThreadList)) {
  578. WorkerThreadEntry = RemoveHeadList( &CcIdleWorkerThreadList );
  579. CcNumberActiveWorkerThreads += 1;
  580. }
  581. CcReleaseWorkQueueLock( OldIrql );
  582. if (WorkerThreadEntry != NULL) {
  583. //
  584. // I had to peak in the sources to verify that this routine
  585. // is a noop if the Flink is not NULL. Sheeeeit!
  586. //
  587. ((PWORK_QUEUE_ITEM)WorkerThreadEntry)->List.Flink = NULL;
  588. ExQueueWorkItem( (PWORK_QUEUE_ITEM)WorkerThreadEntry, CriticalWorkQueue );
  589. }
  590. //
  591. // And return to our caller
  592. //
  593. DebugTrace(-1, me, "CcPostWorkQueue -> VOID\n", 0 );
  594. return;
  595. }
  596. //
  597. // Internal support routine
  598. //
  599. VOID
  600. CcWorkerThread (
  601. PVOID ExWorkQueueItem
  602. )
  603. /*++
  604. Routine Description:
  605. This is worker thread routine for processing cache manager work queue
  606. entries.
  607. Arguments:
  608. ExWorkQueueItem - The work item used for this thread
  609. Return Value:
  610. None
  611. --*/
  612. {
  613. KIRQL OldIrql;
  614. PLIST_ENTRY WorkQueue;
  615. PWORK_QUEUE_ENTRY WorkQueueEntry;
  616. BOOLEAN RescanOk = FALSE;
  617. BOOLEAN DropThrottle = FALSE;
  618. IO_STATUS_BLOCK IoStatus;
  619. IoStatus.Status = STATUS_SUCCESS;
  620. IoStatus.Information = 0;
  621. ASSERT(FIELD_OFFSET(WORK_QUEUE_ENTRY, WorkQueueLinks) == 0);
  622. while (TRUE) {
  623. CcAcquireWorkQueueLock( &OldIrql );
  624. //
  625. // If we just processed a throttled operation, drop the flag.
  626. //
  627. if (DropThrottle) {
  628. DropThrottle = CcQueueThrottle = FALSE;
  629. }
  630. //
  631. // On requeue, push at end of the source queue and clear hint.
  632. //
  633. if (IoStatus.Information == CC_REQUEUE) {
  634. InsertTailList( WorkQueue, &WorkQueueEntry->WorkQueueLinks );
  635. IoStatus.Information = 0;
  636. }
  637. //
  638. // First see if there is something in the express queue.
  639. //
  640. if (!IsListEmpty(&CcExpressWorkQueue)) {
  641. WorkQueue = &CcExpressWorkQueue;
  642. //
  643. // If there was nothing there, then try the regular queue.
  644. //
  645. } else if (!IsListEmpty(&CcRegularWorkQueue)) {
  646. WorkQueue = &CcRegularWorkQueue;
  647. //
  648. // Else we can break and go idle.
  649. //
  650. } else {
  651. break;
  652. }
  653. WorkQueueEntry = CONTAINING_RECORD( WorkQueue->Flink, WORK_QUEUE_ENTRY, WorkQueueLinks );
  654. //
  655. // If this is an EventSet, throttle down to a single thread to be sure
  656. // that this event fires after all preceeding workitems have completed.
  657. //
  658. if (WorkQueueEntry->Function == EventSet && CcNumberActiveWorkerThreads > 1) {
  659. CcQueueThrottle = TRUE;
  660. break;
  661. }
  662. //
  663. // Pop the workitem off: we will execute it now.
  664. //
  665. RemoveHeadList( WorkQueue );
  666. CcReleaseWorkQueueLock( OldIrql );
  667. //
  668. // Process the entry within a try-except clause, so that any errors
  669. // will cause us to continue after the called routine has unwound.
  670. //
  671. try {
  672. switch (WorkQueueEntry->Function) {
  673. //
  674. // Perform read ahead
  675. //
  676. case ReadAhead:
  677. DebugTrace( 0, me, "CcWorkerThread Read Ahead FileObject = %08lx\n",
  678. WorkQueueEntry->Parameters.Read.FileObject );
  679. CcPerformReadAhead( WorkQueueEntry->Parameters.Read.FileObject );
  680. break;
  681. //
  682. // Perform write behind
  683. //
  684. case WriteBehind:
  685. DebugTrace( 0, me, "CcWorkerThread WriteBehind SharedCacheMap = %08lx\n",
  686. WorkQueueEntry->Parameters.Write.SharedCacheMap );
  687. //
  688. // While CcWriteBehind is running, we mark this thread as a
  689. // MemoryMaker so that Mm will allow pool allocations to
  690. // succeed when we are getting into low-resource situations.
  691. // This helps avoid loss delayed write error in low-resource
  692. // scenarios.
  693. //
  694. PsGetCurrentThread()->MemoryMaker = 1;
  695. CcWriteBehind( WorkQueueEntry->Parameters.Write.SharedCacheMap, &IoStatus );
  696. RescanOk = (BOOLEAN)NT_SUCCESS(IoStatus.Status);
  697. PsGetCurrentThread()->MemoryMaker = 0;
  698. break;
  699. //
  700. // Perform set event
  701. //
  702. case EventSet:
  703. DebugTrace( 0, me, "CcWorkerThread SetEvent Event = %08lx\n",
  704. WorkQueueEntry->Parameters.Event.Event );
  705. KeSetEvent( WorkQueueEntry->Parameters.Event.Event, 0, FALSE );
  706. DropThrottle = TRUE;
  707. break;
  708. //
  709. // Perform Lazy Write Scan
  710. //
  711. case LazyWriteScan:
  712. DebugTrace( 0, me, "CcWorkerThread Lazy Write Scan\n", 0 );
  713. CcLazyWriteScan();
  714. break;
  715. }
  716. }
  717. except( CcExceptionFilter( GetExceptionCode() )) {
  718. //
  719. // If we hit an exception in this thread, we need to make sure
  720. // that if we had made this thread a memory maker that flag is
  721. // cleared in the thread structure because this thread will be
  722. // reused by arbitrary system worker threads that should not have
  723. // this designation.
  724. //
  725. if (WorkQueueEntry->Function == WriteBehind) {
  726. PsGetCurrentThread()->MemoryMaker = 0;
  727. }
  728. }
  729. //
  730. // If not a requeue request, free the workitem.
  731. //
  732. if (IoStatus.Information != CC_REQUEUE) {
  733. CcFreeWorkQueueEntry( WorkQueueEntry );
  734. }
  735. }
  736. //
  737. // No more work. Requeue our worker thread entry and get out.
  738. //
  739. InsertTailList( &CcIdleWorkerThreadList,
  740. &((PWORK_QUEUE_ITEM)ExWorkQueueItem)->List );
  741. CcNumberActiveWorkerThreads -= 1;
  742. CcReleaseWorkQueueLock( OldIrql );
  743. if (!IsListEmpty(&CcDeferredWrites) && (CcTotalDirtyPages >= 20) && RescanOk) {
  744. CcLazyWriteScan();
  745. }
  746. return;
  747. }