Source code of Windows XP (NT5)
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.

4194 lines
123 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. sectsup.c
  5. Abstract:
  6. This module contains the routines which implement the
  7. section object.
  8. Author:
  9. Lou Perazzoli (loup) 22-May-1989
  10. Landy Wang (landyw) 02-June-1997
  11. Revision History:
  12. --*/
  13. #include "mi.h"
  14. VOID
  15. FASTCALL
  16. MiRemoveBasedSection (
  17. IN PSECTION Section
  18. );
  19. #ifdef ALLOC_PRAGMA
  20. #pragma alloc_text(INIT,MiSectionInitialization)
  21. #pragma alloc_text(PAGE,MiRemoveBasedSection)
  22. #pragma alloc_text(PAGE,MmGetFileNameForSection)
  23. #pragma alloc_text(PAGE,MmGetFileNameForAddress)
  24. #pragma alloc_text(PAGE,MiSectionDelete)
  25. #pragma alloc_text(PAGE,MiInsertBasedSection)
  26. #pragma alloc_text(PAGE,MiGetEventCounter)
  27. #pragma alloc_text(PAGE,MiFreeEventCounter)
  28. #pragma alloc_text(PAGE,MmGetFileObjectForSection)
  29. #endif
  30. ULONG MmUnusedSegmentForceFree;
  31. ULONG MiSubsectionsProcessed;
  32. ULONG MiSubsectionActions;
  33. SIZE_T MmSharedCommit = 0;
  34. extern const ULONG MMCONTROL;
  35. //
  36. // Define segment dereference thread wait object types.
  37. //
  38. typedef enum _SEGMENT_DEREFERENCE_OBJECT {
  39. SegmentDereference,
  40. UsedSegmentCleanup,
  41. SegMaximumObject
  42. } BALANCE_OBJECT;
  43. extern POBJECT_TYPE IoFileObjectType;
  44. #ifdef ALLOC_DATA_PRAGMA
  45. #pragma const_seg("INITCONST")
  46. #endif
  47. const GENERIC_MAPPING MiSectionMapping = {
  48. STANDARD_RIGHTS_READ |
  49. SECTION_QUERY | SECTION_MAP_READ,
  50. STANDARD_RIGHTS_WRITE |
  51. SECTION_MAP_WRITE,
  52. STANDARD_RIGHTS_EXECUTE |
  53. SECTION_MAP_EXECUTE,
  54. SECTION_ALL_ACCESS
  55. };
  56. #ifdef ALLOC_DATA_PRAGMA
  57. #pragma const_seg()
  58. #endif
  59. VOID
  60. MiRemoveUnusedSegments(
  61. VOID
  62. );
  63. VOID
  64. FASTCALL
  65. MiInsertBasedSection (
  66. IN PSECTION Section
  67. )
  68. /*++
  69. Routine Description:
  70. This function inserts a virtual address descriptor into the tree and
  71. reorders the splay tree as appropriate.
  72. Arguments:
  73. Section - Supplies a pointer to a based section.
  74. Return Value:
  75. None.
  76. Environment:
  77. Must be holding the section based mutex.
  78. --*/
  79. {
  80. PMMADDRESS_NODE *Root;
  81. ASSERT (Section->Address.EndingVpn >= Section->Address.StartingVpn);
  82. Root = &MmSectionBasedRoot;
  83. MiInsertNode (&Section->Address, Root);
  84. return;
  85. }
  86. VOID
  87. FASTCALL
  88. MiRemoveBasedSection (
  89. IN PSECTION Section
  90. )
  91. /*++
  92. Routine Description:
  93. This function removes a based section from the tree.
  94. Arguments:
  95. Section - pointer to the based section object to remove.
  96. Return Value:
  97. None.
  98. Environment:
  99. Must be holding the section based mutex.
  100. --*/
  101. {
  102. PMMADDRESS_NODE *Root;
  103. Root = &MmSectionBasedRoot;
  104. MiRemoveNode (&Section->Address, Root);
  105. return;
  106. }
  107. VOID
  108. MiSegmentDelete (
  109. PSEGMENT Segment
  110. )
  111. /*++
  112. Routine Description:
  113. This routine is called whenever the last reference to a segment object
  114. has been removed. This routine releases the pool allocated for the
  115. prototype PTEs and performs consistency checks on those PTEs.
  116. For segments which map files, the file object is dereferenced.
  117. Note, that for a segment which maps a file, no PTEs may be valid
  118. or transition, while a segment which is backed by a paging file
  119. may have transition pages, but no valid pages (there can be no
  120. PTEs which refer to the segment).
  121. Arguments:
  122. Segment - a pointer to the segment structure.
  123. Return Value:
  124. None.
  125. --*/
  126. {
  127. PMMPTE PointerPte;
  128. PMMPTE LastPte;
  129. PMMPFN Pfn1;
  130. PMMPFN Pfn2;
  131. KIRQL OldIrql;
  132. volatile PCONTROL_AREA ControlArea;
  133. PEVENT_COUNTER Event;
  134. MMPTE PteContents;
  135. PSUBSECTION Subsection;
  136. PSUBSECTION NextSubsection;
  137. PMSUBSECTION MappedSubsection;
  138. PFN_NUMBER PageTableFrameIndex;
  139. SIZE_T NumberOfCommittedPages;
  140. ControlArea = Segment->ControlArea;
  141. ASSERT (ControlArea->u.Flags.BeingDeleted == 1);
  142. ASSERT (ControlArea->Segment->WritableUserReferences == 0);
  143. LOCK_PFN (OldIrql);
  144. if (ControlArea->DereferenceList.Flink != NULL) {
  145. //
  146. // Remove this from the list of unused segments. The dereference
  147. // segment thread cannot be processing any subsections from this
  148. // control area right now because it bumps the NumberOfMappedViews
  149. // for the control area prior to releasing the PFN lock and it checks
  150. // for BeingDeleted.
  151. //
  152. ExAcquireSpinLockAtDpcLevel (&MmDereferenceSegmentHeader.Lock);
  153. RemoveEntryList (&ControlArea->DereferenceList);
  154. MI_UNUSED_SEGMENTS_REMOVE_CHARGE (ControlArea);
  155. ExReleaseSpinLockFromDpcLevel (&MmDereferenceSegmentHeader.Lock);
  156. }
  157. UNLOCK_PFN (OldIrql);
  158. if ((ControlArea->u.Flags.Image) || (ControlArea->u.Flags.File)) {
  159. //
  160. // Unload kernel debugger symbols if any were loaded.
  161. //
  162. if (ControlArea->u.Flags.DebugSymbolsLoaded != 0) {
  163. //
  164. // TEMP TEMP TEMP rip out when debugger converted
  165. //
  166. ANSI_STRING AnsiName;
  167. NTSTATUS Status;
  168. Status = RtlUnicodeStringToAnsiString( &AnsiName,
  169. (PUNICODE_STRING)&Segment->ControlArea->FilePointer->FileName,
  170. TRUE );
  171. if (NT_SUCCESS( Status)) {
  172. DbgUnLoadImageSymbols( &AnsiName,
  173. Segment->BasedAddress,
  174. (ULONG_PTR)PsGetCurrentProcess());
  175. RtlFreeAnsiString( &AnsiName );
  176. }
  177. LOCK_PFN (OldIrql);
  178. ControlArea->u.Flags.DebugSymbolsLoaded = 0;
  179. }
  180. else {
  181. LOCK_PFN (OldIrql);
  182. }
  183. //
  184. // Signal any threads waiting on the deletion event.
  185. //
  186. Event = ControlArea->WaitingForDeletion;
  187. ControlArea->WaitingForDeletion = NULL;
  188. UNLOCK_PFN (OldIrql);
  189. if (Event != NULL) {
  190. KeSetEvent (&Event->Event, 0, FALSE);
  191. }
  192. //
  193. // Clear the segment context and dereference the file object
  194. // for this Segment.
  195. //
  196. // If the segment was deleted due to a name collision at insertion
  197. // we don't want to dereference the file pointer.
  198. //
  199. if (ControlArea->u.Flags.BeingCreated == FALSE) {
  200. #if DBG
  201. if (ControlArea->u.Flags.Image == 1) {
  202. ASSERT (ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject != (PVOID)ControlArea);
  203. }
  204. else {
  205. ASSERT (ControlArea->FilePointer->SectionObjectPointer->DataSectionObject != (PVOID)ControlArea);
  206. }
  207. #endif
  208. PERFINFO_SEGMENT_DELETE(ControlArea->FilePointer);
  209. ObDereferenceObject (ControlArea->FilePointer);
  210. }
  211. //
  212. // If there have been committed pages in this segment, adjust
  213. // the total commit count.
  214. //
  215. if (ControlArea->u.Flags.Image == 0) {
  216. //
  217. // This is a mapped data file. None of the prototype
  218. // PTEs may be referencing a physical page (valid or transition).
  219. //
  220. if (ControlArea->u.Flags.Rom == 0) {
  221. Subsection = (PSUBSECTION)(ControlArea + 1);
  222. }
  223. else {
  224. Subsection = (PSUBSECTION)((PLARGE_CONTROL_AREA)ControlArea + 1);
  225. }
  226. #if DBG
  227. if (Subsection->SubsectionBase != NULL) {
  228. PointerPte = Subsection->SubsectionBase;
  229. LastPte = PointerPte + Segment->NonExtendedPtes;
  230. while (PointerPte < LastPte) {
  231. //
  232. // Prototype PTEs for segments backed by paging file are
  233. // either in demand zero, page file format, or transition.
  234. //
  235. ASSERT (PointerPte->u.Hard.Valid == 0);
  236. ASSERT ((PointerPte->u.Soft.Prototype == 1) ||
  237. (PointerPte->u.Long == 0));
  238. PointerPte += 1;
  239. }
  240. }
  241. #endif
  242. //
  243. // Deallocate the control area and subsections.
  244. //
  245. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 0);
  246. if (ControlArea->FilePointer != NULL) {
  247. MappedSubsection = (PMSUBSECTION) Subsection;
  248. LOCK_PFN (OldIrql);
  249. while (MappedSubsection != NULL) {
  250. if (MappedSubsection->DereferenceList.Flink != NULL) {
  251. //
  252. // Remove this from the list of unused subsections.
  253. //
  254. RemoveEntryList (&MappedSubsection->DereferenceList);
  255. MI_UNUSED_SUBSECTIONS_COUNT_REMOVE (MappedSubsection);
  256. }
  257. MappedSubsection = (PMSUBSECTION) MappedSubsection->NextSubsection;
  258. }
  259. UNLOCK_PFN (OldIrql);
  260. if (Subsection->SubsectionBase != NULL) {
  261. ExFreePool (Subsection->SubsectionBase);
  262. }
  263. }
  264. Subsection = Subsection->NextSubsection;
  265. while (Subsection != NULL) {
  266. if (Subsection->SubsectionBase != NULL) {
  267. ExFreePool (Subsection->SubsectionBase);
  268. }
  269. NextSubsection = Subsection->NextSubsection;
  270. ExFreePool (Subsection);
  271. Subsection = NextSubsection;
  272. }
  273. NumberOfCommittedPages = Segment->NumberOfCommittedPages;
  274. if (NumberOfCommittedPages != 0) {
  275. MiReturnCommitment (NumberOfCommittedPages);
  276. MM_TRACK_COMMIT (MM_DBG_COMMIT_RETURN_SEGMENT_DELETE1,
  277. NumberOfCommittedPages);
  278. InterlockedExchangeAddSizeT (&MmSharedCommit, 0-NumberOfCommittedPages);
  279. }
  280. ExFreePool (ControlArea);
  281. ExFreePool (Segment);
  282. //
  283. // The file mapped Segment object is now deleted.
  284. //
  285. return;
  286. }
  287. }
  288. //
  289. // This is a page file backed or image Segment. The Segment is being
  290. // deleted, remove all references to the paging file and physical memory.
  291. //
  292. // The PFN lock is required for deallocating pages from a paging
  293. // file and for deleting transition PTEs.
  294. //
  295. if ((ControlArea->u.Flags.GlobalOnlyPerSession == 0) &&
  296. (ControlArea->u.Flags.Rom == 0)) {
  297. Subsection = (PSUBSECTION)(ControlArea + 1);
  298. }
  299. else {
  300. Subsection = (PSUBSECTION)((PLARGE_CONTROL_AREA)ControlArea + 1);
  301. }
  302. PointerPte = Subsection->SubsectionBase;
  303. LastPte = PointerPte + Segment->NonExtendedPtes;
  304. LOCK_PFN (OldIrql);
  305. MiMakeSystemAddressValidPfn (PointerPte);
  306. while (PointerPte < LastPte) {
  307. if (MiIsPteOnPdeBoundary(PointerPte)) {
  308. //
  309. // We are on a page boundary, make sure this PTE is resident.
  310. //
  311. if (MmIsAddressValid (PointerPte) == FALSE) {
  312. MiMakeSystemAddressValidPfn (PointerPte);
  313. }
  314. }
  315. PteContents = *PointerPte;
  316. //
  317. // Prototype PTEs for Segments backed by paging file
  318. // are either in demand zero, page file format, or transition.
  319. //
  320. ASSERT (PteContents.u.Hard.Valid == 0);
  321. if (PteContents.u.Soft.Prototype == 0) {
  322. if (PteContents.u.Soft.Transition == 1) {
  323. //
  324. // Prototype PTE in transition, put the page on the free list.
  325. //
  326. Pfn1 = MI_PFN_ELEMENT (PteContents.u.Trans.PageFrameNumber);
  327. MI_SET_PFN_DELETED (Pfn1);
  328. PageTableFrameIndex = Pfn1->u4.PteFrame;
  329. Pfn2 = MI_PFN_ELEMENT (PageTableFrameIndex);
  330. MiDecrementShareCountInline (Pfn2, PageTableFrameIndex);
  331. //
  332. // Check the reference count for the page, if the reference
  333. // count is zero and the page is not on the freelist,
  334. // move the page to the free list, if the reference
  335. // count is not zero, ignore this page.
  336. // When the reference count goes to zero, it will be placed
  337. // on the free list.
  338. //
  339. if (Pfn1->u3.e2.ReferenceCount == 0) {
  340. MiUnlinkPageFromList (Pfn1);
  341. MiReleasePageFileSpace (Pfn1->OriginalPte);
  342. MiInsertPageInFreeList (MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&PteContents));
  343. }
  344. }
  345. else {
  346. //
  347. // This is not a prototype PTE, if any paging file
  348. // space has been allocated, release it.
  349. //
  350. if (IS_PTE_NOT_DEMAND_ZERO (PteContents)) {
  351. MiReleasePageFileSpace (PteContents);
  352. }
  353. }
  354. }
  355. #if DBG
  356. MI_WRITE_INVALID_PTE (PointerPte, ZeroPte);
  357. #endif
  358. PointerPte += 1;
  359. }
  360. UNLOCK_PFN (OldIrql);
  361. //
  362. // If there have been committed pages in this segment, adjust
  363. // the total commit count.
  364. //
  365. NumberOfCommittedPages = Segment->NumberOfCommittedPages;
  366. if (NumberOfCommittedPages != 0) {
  367. MiReturnCommitment (NumberOfCommittedPages);
  368. if (ControlArea->u.Flags.Image) {
  369. MM_TRACK_COMMIT (MM_DBG_COMMIT_RETURN_SEGMENT_DELETE2,
  370. NumberOfCommittedPages);
  371. }
  372. else {
  373. MM_TRACK_COMMIT (MM_DBG_COMMIT_RETURN_SEGMENT_DELETE3,
  374. NumberOfCommittedPages);
  375. }
  376. InterlockedExchangeAddSizeT (&MmSharedCommit, 0-NumberOfCommittedPages);
  377. }
  378. ExFreePool (ControlArea);
  379. ExFreePool (Segment);
  380. return;
  381. }
  382. ULONG
  383. MmDoesFileHaveUserWritableReferences (
  384. IN PSECTION_OBJECT_POINTERS SectionPointer
  385. )
  386. /*++
  387. Routine Description:
  388. This routine is called by the transaction filesystem to determine if
  389. the given transaction is referencing a file which has user writable sections
  390. or user writable views into it. If so, the transaction must be aborted
  391. as it cannot be guaranteed atomicity.
  392. The transaction filesystem is responsible for checking and intercepting
  393. file object creates that specify write access prior to using this
  394. interface. Specifically, prior to starting a transaction, the transaction
  395. filesystem must ensure that there are no writable file objects that
  396. currently exist for the given file in the transaction. While the
  397. transaction is ongoing, requests to create file objects with write access
  398. for the transaction files must be refused.
  399. This Mm routine exists to catch the case where the user has closed the
  400. file handles and the section handles, but still has open writable views.
  401. For this reason, no locks are needed to read the value below.
  402. Arguments:
  403. SectionPointer - Supplies a pointer to the section object pointers
  404. from the file object.
  405. Return Value:
  406. Number of user writable references.
  407. Environment:
  408. Kernel mode, APC_LEVEL or below, no mutexes held.
  409. --*/
  410. {
  411. KIRQL OldIrql;
  412. ULONG WritableUserReferences;
  413. PCONTROL_AREA ControlArea;
  414. LOCK_PFN (OldIrql);
  415. ControlArea = (PCONTROL_AREA)(SectionPointer->DataSectionObject);
  416. if (ControlArea == NULL) {
  417. UNLOCK_PFN (OldIrql);
  418. return 0;
  419. }
  420. //
  421. // Up the map view count so the control area cannot be deleted
  422. // out from under the call.
  423. //
  424. ControlArea->NumberOfMappedViews += 1;
  425. MiMakeSystemAddressValidPfn (&ControlArea->Segment->WritableUserReferences);
  426. WritableUserReferences = ControlArea->Segment->WritableUserReferences;
  427. ASSERT ((LONG)ControlArea->NumberOfMappedViews >= 1);
  428. ControlArea->NumberOfMappedViews -= 1;
  429. //
  430. // This routine will release the PFN lock.
  431. //
  432. MiCheckControlArea (ControlArea, NULL, OldIrql);
  433. return WritableUserReferences;
  434. }
  435. VOID
  436. MiDereferenceControlAreaBySection (
  437. IN PCONTROL_AREA ControlArea,
  438. IN ULONG UserRef
  439. )
  440. /*++
  441. Routine Description:
  442. This is a nonpaged helper routine to dereference the specified control area.
  443. Arguments:
  444. ControlArea - Supplies a pointer to the control area.
  445. UserRef - Supplies the number of user dereferences to apply.
  446. Return Value:
  447. None.
  448. --*/
  449. {
  450. KIRQL OldIrql;
  451. LOCK_PFN (OldIrql);
  452. ControlArea->NumberOfSectionReferences -= 1;
  453. ControlArea->NumberOfUserReferences -= UserRef;
  454. //
  455. // Check to see if the control area (segment) should be deleted.
  456. // This routine releases the PFN lock.
  457. //
  458. MiCheckControlArea (ControlArea, NULL, OldIrql);
  459. }
  460. VOID
  461. MiSectionDelete (
  462. IN PVOID Object
  463. )
  464. /*++
  465. Routine Description:
  466. This routine is called by the object management procedures whenever
  467. the last reference to a section object has been removed. This routine
  468. dereferences the associated segment object and checks to see if
  469. the segment object should be deleted by queueing the segment to the
  470. segment deletion thread.
  471. Arguments:
  472. Object - a pointer to the body of the section object.
  473. Return Value:
  474. None.
  475. --*/
  476. {
  477. PSECTION Section;
  478. volatile PCONTROL_AREA ControlArea;
  479. ULONG UserRef;
  480. Section = (PSECTION)Object;
  481. if (Section->Segment == (PSEGMENT)NULL) {
  482. //
  483. // The section was never initialized, no need to remove
  484. // any structures.
  485. //
  486. return;
  487. }
  488. UserRef = Section->u.Flags.UserReference;
  489. ControlArea = Section->Segment->ControlArea;
  490. if (Section->Address.StartingVpn != 0) {
  491. //
  492. // This section is based, remove the base address from the
  493. // tree.
  494. //
  495. //
  496. // Get the allocation base mutex.
  497. //
  498. ExAcquireFastMutex (&MmSectionBasedMutex);
  499. MiRemoveBasedSection (Section);
  500. ExReleaseFastMutex (&MmSectionBasedMutex);
  501. }
  502. //
  503. // Adjust the count of writable user sections for transaction support.
  504. //
  505. if ((Section->u.Flags.UserWritable == 1) &&
  506. (ControlArea->u.Flags.Image == 0) &&
  507. (ControlArea->FilePointer != NULL)) {
  508. ASSERT (Section->InitialPageProtection & (PAGE_READWRITE|PAGE_EXECUTE_READWRITE));
  509. InterlockedDecrement ((PLONG)&ControlArea->Segment->WritableUserReferences);
  510. }
  511. //
  512. // Decrement the number of section references to the segment for this
  513. // section. This requires APCs to be blocked and the PFN lock to
  514. // synchronize upon.
  515. //
  516. MiDereferenceControlAreaBySection (ControlArea, UserRef);
  517. return;
  518. }
  519. VOID
  520. MiDereferenceSegmentThread (
  521. IN PVOID StartContext
  522. )
  523. /*++
  524. Routine Description:
  525. This routine is the thread for dereferencing segments which have
  526. no references from any sections or mapped views AND there are
  527. no prototype PTEs within the segment which are in the transition
  528. state (i.e., no PFN database references to the segment).
  529. It also does double duty and is used for expansion of paging files.
  530. Arguments:
  531. StartContext - Not used.
  532. Return Value:
  533. None.
  534. --*/
  535. {
  536. PCONTROL_AREA ControlArea;
  537. PETHREAD CurrentThread;
  538. PMMPAGE_FILE_EXPANSION PageExpand;
  539. PLIST_ENTRY NextEntry;
  540. KIRQL OldIrql;
  541. static KWAIT_BLOCK WaitBlockArray[SegMaximumObject];
  542. PVOID WaitObjects[SegMaximumObject];
  543. NTSTATUS Status;
  544. UNREFERENCED_PARAMETER (StartContext);
  545. //
  546. // Make this a real time thread.
  547. //
  548. CurrentThread = PsGetCurrentThread();
  549. KeSetPriorityThread (&CurrentThread->Tcb, LOW_REALTIME_PRIORITY + 2);
  550. CurrentThread->MemoryMaker = 1;
  551. WaitObjects[SegmentDereference] = (PVOID)&MmDereferenceSegmentHeader.Semaphore;
  552. WaitObjects[UsedSegmentCleanup] = (PVOID)&MmUnusedSegmentCleanup;
  553. for (;;) {
  554. Status = KeWaitForMultipleObjects(SegMaximumObject,
  555. &WaitObjects[0],
  556. WaitAny,
  557. WrVirtualMemory,
  558. UserMode,
  559. FALSE,
  560. NULL,
  561. &WaitBlockArray[0]);
  562. //
  563. // Switch on the wait status.
  564. //
  565. switch (Status) {
  566. case SegmentDereference:
  567. //
  568. // An entry is available to dereference, acquire the spinlock
  569. // and remove the entry.
  570. //
  571. ExAcquireSpinLock (&MmDereferenceSegmentHeader.Lock, &OldIrql);
  572. if (IsListEmpty (&MmDereferenceSegmentHeader.ListHead)) {
  573. //
  574. // There is nothing in the list, rewait.
  575. //
  576. ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);
  577. break;
  578. }
  579. NextEntry = RemoveHeadList (&MmDereferenceSegmentHeader.ListHead);
  580. ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);
  581. ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);
  582. ControlArea = CONTAINING_RECORD (NextEntry,
  583. CONTROL_AREA,
  584. DereferenceList);
  585. if (ControlArea->Segment != NULL) {
  586. //
  587. // This is a control area, delete it after indicating
  588. // this entry is not on any list.
  589. //
  590. ControlArea->DereferenceList.Flink = NULL;
  591. ASSERT (ControlArea->u.Flags.FilePointerNull == 1);
  592. MiSegmentDelete (ControlArea->Segment);
  593. }
  594. else {
  595. //
  596. // This is a request to expand or reduce the paging files.
  597. //
  598. PageExpand = (PMMPAGE_FILE_EXPANSION)ControlArea;
  599. if (PageExpand->RequestedExpansionSize == MI_CONTRACT_PAGEFILES) {
  600. //
  601. // Attempt to reduce the size of the paging files.
  602. //
  603. ExFreePool (PageExpand);
  604. MiAttemptPageFileReduction ();
  605. }
  606. else {
  607. //
  608. // Attempt to expand the size of the paging files.
  609. //
  610. MiExtendPagingFiles (PageExpand);
  611. KeSetEvent (&PageExpand->Event, 0, FALSE);
  612. MiRemoveUnusedSegments();
  613. }
  614. }
  615. break;
  616. case UsedSegmentCleanup:
  617. MiRemoveUnusedSegments();
  618. KeClearEvent (&MmUnusedSegmentCleanup);
  619. break;
  620. default:
  621. KdPrint(("MMSegmentderef: Illegal wait status, %lx =\n", Status));
  622. break;
  623. } // end switch
  624. } //end for
  625. return;
  626. }
  627. ULONG
  628. MiSectionInitialization (
  629. )
  630. /*++
  631. Routine Description:
  632. This function creates the section object type descriptor at system
  633. initialization and stores the address of the object type descriptor
  634. in global storage.
  635. Arguments:
  636. None.
  637. Return Value:
  638. TRUE - Initialization was successful.
  639. FALSE - Initialization Failed.
  640. --*/
  641. {
  642. OBJECT_TYPE_INITIALIZER ObjectTypeInitializer;
  643. UNICODE_STRING TypeName;
  644. HANDLE ThreadHandle;
  645. OBJECT_ATTRIBUTES ObjectAttributes;
  646. UNICODE_STRING SectionName;
  647. PSECTION Section;
  648. HANDLE Handle;
  649. PSEGMENT Segment;
  650. PCONTROL_AREA ControlArea;
  651. NTSTATUS Status;
  652. MmSectionBasedRoot = (PMMADDRESS_NODE)NULL;
  653. //
  654. // Initialize the common fields of the Object Type Initializer record
  655. //
  656. RtlZeroMemory( &ObjectTypeInitializer, sizeof( ObjectTypeInitializer ) );
  657. ObjectTypeInitializer.Length = sizeof( ObjectTypeInitializer );
  658. ObjectTypeInitializer.InvalidAttributes = OBJ_OPENLINK;
  659. ObjectTypeInitializer.GenericMapping = MiSectionMapping;
  660. ObjectTypeInitializer.PoolType = PagedPool;
  661. ObjectTypeInitializer.DefaultPagedPoolCharge = sizeof(SECTION);
  662. //
  663. // Initialize string descriptor.
  664. //
  665. RtlInitUnicodeString (&TypeName, (const PUSHORT)L"Section");
  666. //
  667. // Create the section object type descriptor
  668. //
  669. ObjectTypeInitializer.ValidAccessMask = SECTION_ALL_ACCESS;
  670. ObjectTypeInitializer.DeleteProcedure = MiSectionDelete;
  671. ObjectTypeInitializer.GenericMapping = MiSectionMapping;
  672. ObjectTypeInitializer.UseDefaultObject = TRUE;
  673. if ( !NT_SUCCESS(ObCreateObjectType(&TypeName,
  674. &ObjectTypeInitializer,
  675. (PSECURITY_DESCRIPTOR) NULL,
  676. &MmSectionObjectType
  677. )) ) {
  678. return FALSE;
  679. }
  680. //
  681. // Create the Segment dereferencing thread.
  682. //
  683. InitializeObjectAttributes( &ObjectAttributes,
  684. NULL,
  685. 0,
  686. NULL,
  687. NULL );
  688. if ( !NT_SUCCESS(PsCreateSystemThread(
  689. &ThreadHandle,
  690. THREAD_ALL_ACCESS,
  691. &ObjectAttributes,
  692. 0,
  693. NULL,
  694. MiDereferenceSegmentThread,
  695. NULL
  696. )) ) {
  697. return FALSE;
  698. }
  699. ZwClose (ThreadHandle);
  700. //
  701. // Create the permanent section which maps physical memory.
  702. //
  703. Segment = (PSEGMENT)ExAllocatePoolWithTag (PagedPool,
  704. sizeof(SEGMENT),
  705. 'gSmM');
  706. if (Segment == NULL) {
  707. return FALSE;
  708. }
  709. ControlArea = ExAllocatePoolWithTag (NonPagedPool,
  710. (ULONG)sizeof(CONTROL_AREA),
  711. MMCONTROL);
  712. if (ControlArea == NULL) {
  713. ExFreePool (Segment);
  714. return FALSE;
  715. }
  716. RtlZeroMemory (Segment, sizeof(SEGMENT));
  717. RtlZeroMemory (ControlArea, sizeof(CONTROL_AREA));
  718. ControlArea->Segment = Segment;
  719. ControlArea->NumberOfSectionReferences = 1;
  720. ControlArea->u.Flags.PhysicalMemory = 1;
  721. Segment->ControlArea = ControlArea;
  722. Segment->SegmentPteTemplate = ZeroPte;
  723. //
  724. // Now that the segment object is created, create a section object
  725. // which refers to the segment object.
  726. //
  727. RtlInitUnicodeString (&SectionName, (const PUSHORT)L"\\Device\\PhysicalMemory");
  728. InitializeObjectAttributes( &ObjectAttributes,
  729. &SectionName,
  730. OBJ_PERMANENT,
  731. NULL,
  732. NULL
  733. );
  734. Status = ObCreateObject (KernelMode,
  735. MmSectionObjectType,
  736. &ObjectAttributes,
  737. KernelMode,
  738. NULL,
  739. sizeof(SECTION),
  740. sizeof(SECTION),
  741. 0,
  742. (PVOID *)&Section);
  743. if (!NT_SUCCESS(Status)) {
  744. ExFreePool (ControlArea);
  745. ExFreePool (Segment);
  746. return FALSE;
  747. }
  748. Section->Segment = Segment;
  749. Section->SizeOfSection.QuadPart = ((LONGLONG)1 << PHYSICAL_ADDRESS_BITS) - 1;
  750. Section->u.LongFlags = 0;
  751. Section->InitialPageProtection = PAGE_READWRITE;
  752. Status = ObInsertObject ((PVOID)Section,
  753. NULL,
  754. SECTION_MAP_READ,
  755. 0,
  756. (PVOID *)NULL,
  757. &Handle);
  758. if (!NT_SUCCESS( Status )) {
  759. return FALSE;
  760. }
  761. if ( !NT_SUCCESS (NtClose ( Handle))) {
  762. return FALSE;
  763. }
  764. return TRUE;
  765. }
  766. BOOLEAN
  767. MmForceSectionClosed (
  768. IN PSECTION_OBJECT_POINTERS SectionObjectPointer,
  769. IN BOOLEAN DelayClose
  770. )
  771. /*++
  772. Routine Description:
  773. This function examines the Section object pointers. If they are NULL,
  774. no further action is taken and the value TRUE is returned.
  775. If the Section object pointer is not NULL, the section reference count
  776. and the map view count are checked. If both counts are zero, the
  777. segment associated with the file is deleted and the file closed.
  778. If one of the counts is non-zero, no action is taken and the
  779. value FALSE is returned.
  780. Arguments:
  781. SectionObjectPointer - Supplies a pointer to a section object.
  782. DelayClose - Supplies the value TRUE if the close operation should
  783. occur as soon as possible in the event this section
  784. cannot be closed now due to outstanding references.
  785. Return Value:
  786. TRUE - The segment was deleted and the file closed or no segment was
  787. located.
  788. FALSE - The segment was not deleted and no action was performed OR
  789. an I/O error occurred trying to write the pages.
  790. --*/
  791. {
  792. PCONTROL_AREA ControlArea;
  793. KIRQL OldIrql;
  794. LOGICAL state;
  795. //
  796. // Check the status of the control area, if the control area is in use
  797. // or the control area is being deleted, this operation cannot continue.
  798. //
  799. state = MiCheckControlAreaStatus (CheckBothSection,
  800. SectionObjectPointer,
  801. DelayClose,
  802. &ControlArea,
  803. &OldIrql);
  804. if (ControlArea == NULL) {
  805. return (BOOLEAN) state;
  806. }
  807. //
  808. // PFN LOCK IS NOW HELD!
  809. //
  810. //
  811. // Repeat until there are no more control areas - multiple control areas
  812. // for the same image section occur to support user global DLLs - these DLLs
  813. // require data that is shared within a session but not across sessions.
  814. // Note this can only happen for Hydra.
  815. //
  816. do {
  817. //
  818. // Set the being deleted flag and up the number of mapped views
  819. // for the segment. Upping the number of mapped views prevents
  820. // the segment from being deleted and passed to the deletion thread
  821. // while we are forcing a delete.
  822. //
  823. ControlArea->u.Flags.BeingDeleted = 1;
  824. ASSERT (ControlArea->NumberOfMappedViews == 0);
  825. ControlArea->NumberOfMappedViews = 1;
  826. //
  827. // This is a page file backed or image Segment. The Segment is being
  828. // deleted, remove all references to the paging file and physical memory.
  829. //
  830. UNLOCK_PFN (OldIrql);
  831. //
  832. // Delete the section by flushing all modified pages back to the section
  833. // if it is a file and freeing up the pages such that the
  834. // PfnReferenceCount goes to zero.
  835. //
  836. MiCleanSection (ControlArea, TRUE);
  837. //
  838. // Get the next Hydra control area.
  839. //
  840. state = MiCheckControlAreaStatus (CheckBothSection,
  841. SectionObjectPointer,
  842. DelayClose,
  843. &ControlArea,
  844. &OldIrql);
  845. } while (ControlArea);
  846. return (BOOLEAN) state;
  847. }
  848. VOID
  849. MiCleanSection (
  850. IN PCONTROL_AREA ControlArea,
  851. IN LOGICAL DirtyDataPagesOk
  852. )
  853. /*++
  854. Routine Description:
  855. This function examines each prototype PTE in the section and
  856. takes the appropriate action to "delete" the prototype PTE.
  857. If the PTE is dirty and is backed by a file (not a paging file),
  858. the corresponding page is written to the file.
  859. At the completion of this service, the section which was
  860. operated upon is no longer usable.
  861. NOTE - ALL I/O ERRORS ARE IGNORED. IF ANY WRITES FAIL, THE
  862. DIRTY PAGES ARE MARKED CLEAN AND THE SECTION IS DELETED.
  863. Arguments:
  864. ControlArea - Supplies a pointer to the control area for the section.
  865. DirtyDataPagesOk - Supplies TRUE if dirty data pages are ok. If FALSE
  866. is specified then no dirty data pages are expected (as
  867. this is a dereference operation) so any encountered
  868. must be due to pool corruption so bugcheck.
  869. Note that dirty image pages are always discarded.
  870. This should only happen for images that were either
  871. read in from floppies or images with shared global
  872. subsections.
  873. Return Value:
  874. None.
  875. --*/
  876. {
  877. LOGICAL DroppedPfnLock;
  878. PMMPTE PointerPte;
  879. PMMPTE LastPte;
  880. PMMPTE LastWritten;
  881. PMMPTE FirstWritten;
  882. MMPTE PteContents;
  883. PMMPFN Pfn1;
  884. PMMPFN Pfn2;
  885. PMMPFN Pfn3;
  886. PMMPTE WrittenPte;
  887. MMPTE WrittenContents;
  888. KIRQL OldIrql;
  889. PMDL Mdl;
  890. PSUBSECTION Subsection;
  891. PPFN_NUMBER Page;
  892. PPFN_NUMBER LastPage;
  893. LARGE_INTEGER StartingOffset;
  894. LARGE_INTEGER TempOffset;
  895. NTSTATUS Status;
  896. IO_STATUS_BLOCK IoStatus;
  897. ULONG WriteNow;
  898. ULONG ImageSection;
  899. ULONG DelayCount;
  900. ULONG First;
  901. KEVENT IoEvent;
  902. PFN_NUMBER PageTableFrameIndex;
  903. PFN_NUMBER MdlHack[(sizeof(MDL)/sizeof(PFN_NUMBER)) + MM_MAXIMUM_WRITE_CLUSTER];
  904. ULONG ReflushCount;
  905. ULONG MaxClusterSize;
  906. WriteNow = FALSE;
  907. ImageSection = FALSE;
  908. DelayCount = 0;
  909. MaxClusterSize = MmModifiedWriteClusterSize;
  910. FirstWritten = NULL;
  911. ASSERT (ControlArea->FilePointer);
  912. if ((ControlArea->u.Flags.GlobalOnlyPerSession == 0) &&
  913. (ControlArea->u.Flags.Rom == 0)) {
  914. Subsection = (PSUBSECTION)(ControlArea + 1);
  915. }
  916. else {
  917. Subsection = (PSUBSECTION)((PLARGE_CONTROL_AREA)ControlArea + 1);
  918. }
  919. if (ControlArea->u.Flags.Image) {
  920. ImageSection = TRUE;
  921. PointerPte = Subsection->SubsectionBase;
  922. LastPte = PointerPte + ControlArea->Segment->NonExtendedPtes;
  923. }
  924. else {
  925. //
  926. // Initializing these are not needed for correctness as they are
  927. // overwritten below, but without it the compiler cannot compile
  928. // this code W4 to check for use of uninitialized variables.
  929. //
  930. PointerPte = NULL;
  931. LastPte = NULL;
  932. }
  933. Mdl = (PMDL)&MdlHack;
  934. KeInitializeEvent (&IoEvent, NotificationEvent, FALSE);
  935. LastWritten = NULL;
  936. ASSERT (MmModifiedWriteClusterSize == MM_MAXIMUM_WRITE_CLUSTER);
  937. LastPage = NULL;
  938. //
  939. // Initializing StartingOffset is not needed for correctness
  940. // but without it the compiler cannot compile this code
  941. // W4 to check for use of uninitialized variables.
  942. //
  943. StartingOffset.QuadPart = 0;
  944. //
  945. // The PFN lock is required for deallocating pages from a paging
  946. // file and for deleting transition PTEs.
  947. //
  948. LOCK_PFN (OldIrql);
  949. //
  950. // Stop the modified page writer from writing pages to this
  951. // file, and if any paging I/O is in progress, wait for it
  952. // to complete.
  953. //
  954. ControlArea->u.Flags.NoModifiedWriting = 1;
  955. while (ControlArea->ModifiedWriteCount != 0) {
  956. //
  957. // There is modified page writing in progess. Set the
  958. // flag in the control area indicating the modified page
  959. // writer should signal when a write to this control area
  960. // is complete. Release the PFN LOCK and wait in an
  961. // atomic operation. Once the wait is satisfied, recheck
  962. // to make sure it was this file's I/O that was written.
  963. //
  964. ControlArea->u.Flags.SetMappedFileIoComplete = 1;
  965. //
  966. // Keep APCs blocked so no special APCs can be delivered in KeWait
  967. // which would cause the dispatcher lock to be released opening a
  968. // window where this thread could miss a pulse.
  969. //
  970. UNLOCK_PFN_AND_THEN_WAIT (APC_LEVEL);
  971. KeWaitForSingleObject (&MmMappedFileIoComplete,
  972. WrPageOut,
  973. KernelMode,
  974. FALSE,
  975. NULL);
  976. KeLowerIrql (OldIrql);
  977. LOCK_PFN (OldIrql);
  978. }
  979. if (ImageSection == FALSE) {
  980. while (Subsection->SubsectionBase == NULL) {
  981. Subsection = Subsection->NextSubsection;
  982. if (Subsection == NULL) {
  983. goto alldone;
  984. }
  985. }
  986. PointerPte = Subsection->SubsectionBase;
  987. LastPte = PointerPte + Subsection->PtesInSubsection;
  988. }
  989. for (;;) {
  990. restartchunk:
  991. First = TRUE;
  992. while (PointerPte < LastPte) {
  993. if ((MiIsPteOnPdeBoundary(PointerPte)) || (First)) {
  994. First = FALSE;
  995. if ((ImageSection) ||
  996. (MiCheckProtoPtePageState(PointerPte, FALSE, &DroppedPfnLock))) {
  997. MiMakeSystemAddressValidPfn (PointerPte);
  998. }
  999. else {
  1000. //
  1001. // Paged pool page is not resident, hence no transition or
  1002. // valid prototype PTEs can be present in it. Skip it.
  1003. //
  1004. PointerPte = (PMMPTE)((((ULONG_PTR)PointerPte | PAGE_SIZE - 1)) + 1);
  1005. if (LastWritten != NULL) {
  1006. WriteNow = TRUE;
  1007. }
  1008. goto WriteItOut;
  1009. }
  1010. }
  1011. PteContents = *PointerPte;
  1012. //
  1013. // Prototype PTEs for Segments backed by paging file
  1014. // are either in demand zero, page file format, or transition.
  1015. //
  1016. if (PteContents.u.Hard.Valid == 1) {
  1017. KeBugCheckEx (POOL_CORRUPTION_IN_FILE_AREA,
  1018. 0x0,
  1019. (ULONG_PTR)ControlArea,
  1020. (ULONG_PTR)PointerPte,
  1021. (ULONG_PTR)PteContents.u.Long);
  1022. }
  1023. if (PteContents.u.Soft.Prototype == 1) {
  1024. //
  1025. // This is a normal prototype PTE in mapped file format.
  1026. //
  1027. if (LastWritten != NULL) {
  1028. WriteNow = TRUE;
  1029. }
  1030. }
  1031. else if (PteContents.u.Soft.Transition == 1) {
  1032. //
  1033. // Prototype PTE in transition, there are 3 possible cases:
  1034. // 1. The page is part of an image which is sharable and
  1035. // refers to the paging file - dereference page file
  1036. // space and free the physical page.
  1037. // 2. The page refers to the segment but is not modified -
  1038. // free the physical page.
  1039. // 3. The page refers to the segment and is modified -
  1040. // write the page to the file and free the physical page.
  1041. //
  1042. Pfn1 = MI_PFN_ELEMENT (PteContents.u.Trans.PageFrameNumber);
  1043. if (Pfn1->u3.e2.ReferenceCount != 0) {
  1044. if (DelayCount < 20) {
  1045. //
  1046. // There must be an I/O in progress on this
  1047. // page. Wait for the I/O operation to complete.
  1048. //
  1049. UNLOCK_PFN (OldIrql);
  1050. //
  1051. // Drain the deferred lists as these pages may be
  1052. // sitting in there right now.
  1053. //
  1054. MiDeferredUnlockPages (0);
  1055. KeDelayExecutionThread (KernelMode, FALSE, (PLARGE_INTEGER)&MmShortTime);
  1056. DelayCount += 1;
  1057. //
  1058. // Redo the loop, if the delay count is greater than
  1059. // 20, assume that this thread is deadlocked and
  1060. // don't purge this page. The file system can deal
  1061. // with the write operation in progress.
  1062. //
  1063. LOCK_PFN (OldIrql);
  1064. MiMakeSystemAddressValidPfn (PointerPte);
  1065. continue;
  1066. }
  1067. #if DBG
  1068. //
  1069. // The I/O still has not completed, just ignore
  1070. // the fact that the I/O is in progress and
  1071. // delete the page.
  1072. //
  1073. KdPrint(("MM:CLEAN - page number %lx has i/o outstanding\n",
  1074. PteContents.u.Trans.PageFrameNumber));
  1075. #endif
  1076. }
  1077. if (Pfn1->OriginalPte.u.Soft.Prototype == 0) {
  1078. //
  1079. // Paging file reference (case 1).
  1080. //
  1081. MI_SET_PFN_DELETED (Pfn1);
  1082. if (!ImageSection) {
  1083. //
  1084. // This is not an image section, it must be a
  1085. // page file backed section, therefore decrement
  1086. // the PFN reference count for the control area.
  1087. //
  1088. ControlArea->NumberOfPfnReferences -= 1;
  1089. ASSERT ((LONG)ControlArea->NumberOfPfnReferences >= 0);
  1090. }
  1091. #if DBG
  1092. else {
  1093. //
  1094. // This should only happen for images with shared
  1095. // global subsections.
  1096. //
  1097. }
  1098. #endif
  1099. PageTableFrameIndex = Pfn1->u4.PteFrame;
  1100. Pfn2 = MI_PFN_ELEMENT (PageTableFrameIndex);
  1101. MiDecrementShareCountInline (Pfn2, PageTableFrameIndex);
  1102. //
  1103. // Check the reference count for the page, if the // reference count is zero and the page is not on the
  1104. // freelist, move the page to the free list, if the
  1105. // reference count is not zero, ignore this page. When
  1106. // the reference count goes to zero, it will be placed
  1107. // on the free list.
  1108. //
  1109. if ((Pfn1->u3.e2.ReferenceCount == 0) &&
  1110. (Pfn1->u3.e1.PageLocation != FreePageList)) {
  1111. MiUnlinkPageFromList (Pfn1);
  1112. MiReleasePageFileSpace (Pfn1->OriginalPte);
  1113. MiInsertPageInFreeList (MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&PteContents));
  1114. }
  1115. PointerPte->u.Long = 0;
  1116. //
  1117. // If a cluster of pages to write has been completed,
  1118. // set the WriteNow flag.
  1119. //
  1120. if (LastWritten != NULL) {
  1121. WriteNow = TRUE;
  1122. }
  1123. }
  1124. else {
  1125. if ((Pfn1->u3.e1.Modified == 0) || (ImageSection)) {
  1126. //
  1127. // Non modified or image file page (case 2).
  1128. //
  1129. MI_SET_PFN_DELETED (Pfn1);
  1130. ControlArea->NumberOfPfnReferences -= 1;
  1131. ASSERT ((LONG)ControlArea->NumberOfPfnReferences >= 0);
  1132. PageTableFrameIndex = Pfn1->u4.PteFrame;
  1133. Pfn2 = MI_PFN_ELEMENT (PageTableFrameIndex);
  1134. MiDecrementShareCountInline (Pfn2, PageTableFrameIndex);
  1135. //
  1136. // Check the reference count for the page, if the
  1137. // reference count is zero and the page is not on
  1138. // the freelist, move the page to the free list,
  1139. // if the reference count is not zero, ignore this
  1140. // page. When the reference count goes to zero, it
  1141. // will be placed on the free list.
  1142. //
  1143. if ((Pfn1->u3.e2.ReferenceCount == 0) &&
  1144. (Pfn1->u3.e1.PageLocation != FreePageList)) {
  1145. MiUnlinkPageFromList (Pfn1);
  1146. MiReleasePageFileSpace (Pfn1->OriginalPte);
  1147. MiInsertPageInFreeList (MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&PteContents));
  1148. }
  1149. PointerPte->u.Long = 0;
  1150. //
  1151. // If a cluster of pages to write has been
  1152. // completed, set the WriteNow flag.
  1153. //
  1154. if (LastWritten != NULL) {
  1155. WriteNow = TRUE;
  1156. }
  1157. }
  1158. else {
  1159. //
  1160. // Modified page backed by the file (case 3).
  1161. // Check to see if this is the first page of a
  1162. // cluster.
  1163. //
  1164. if (LastWritten == NULL) {
  1165. LastPage = (PPFN_NUMBER)(Mdl + 1);
  1166. ASSERT (MiGetSubsectionAddress(&Pfn1->OriginalPte) ==
  1167. Subsection);
  1168. //
  1169. // Calculate the offset to read into the file.
  1170. // offset = base + ((thispte - basepte) << PAGE_SHIFT)
  1171. //
  1172. ASSERT (Subsection->ControlArea->u.Flags.Image == 0);
  1173. StartingOffset.QuadPart = MiStartingOffset(
  1174. Subsection,
  1175. Pfn1->PteAddress);
  1176. MI_INITIALIZE_ZERO_MDL (Mdl);
  1177. Mdl->MdlFlags |= MDL_PAGES_LOCKED;
  1178. Mdl->StartVa = NULL;
  1179. Mdl->Size = (CSHORT)(sizeof(MDL) +
  1180. (sizeof(PFN_NUMBER) * MaxClusterSize));
  1181. FirstWritten = PointerPte;
  1182. }
  1183. LastWritten = PointerPte;
  1184. Mdl->ByteCount += PAGE_SIZE;
  1185. //
  1186. // If the cluster is now full,
  1187. // set the write now flag.
  1188. //
  1189. if (Mdl->ByteCount == (PAGE_SIZE * MaxClusterSize)) {
  1190. WriteNow = TRUE;
  1191. }
  1192. MiUnlinkPageFromList (Pfn1);
  1193. MI_SET_MODIFIED (Pfn1, 0, 0x27);
  1194. //
  1195. // Up the reference count for the physical page as
  1196. // there is I/O in progress.
  1197. //
  1198. MI_ADD_LOCKED_PAGE_CHARGE_FOR_MODIFIED_PAGE(Pfn1, 22);
  1199. Pfn1->u3.e2.ReferenceCount += 1;
  1200. //
  1201. // Clear the modified bit for the page and set the
  1202. // write in progress bit.
  1203. //
  1204. *LastPage = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&PteContents);
  1205. LastPage += 1;
  1206. }
  1207. }
  1208. }
  1209. else {
  1210. if (IS_PTE_NOT_DEMAND_ZERO (PteContents)) {
  1211. MiReleasePageFileSpace (PteContents);
  1212. }
  1213. PointerPte->u.Long = 0;
  1214. //
  1215. // If a cluster of pages to write has been completed,
  1216. // set the WriteNow flag.
  1217. //
  1218. if (LastWritten != NULL) {
  1219. WriteNow = TRUE;
  1220. }
  1221. }
  1222. //
  1223. // Write the current cluster if it is complete,
  1224. // full, or the loop is now complete.
  1225. //
  1226. PointerPte += 1;
  1227. WriteItOut:
  1228. DelayCount = 0;
  1229. if ((WriteNow) ||
  1230. ((PointerPte == LastPte) && (LastWritten != NULL))) {
  1231. //
  1232. // Issue the write request.
  1233. //
  1234. UNLOCK_PFN (OldIrql);
  1235. if (DirtyDataPagesOk == FALSE) {
  1236. KeBugCheckEx (POOL_CORRUPTION_IN_FILE_AREA,
  1237. 0x1,
  1238. (ULONG_PTR)ControlArea,
  1239. (ULONG_PTR)Mdl,
  1240. ControlArea->u.LongFlags);
  1241. }
  1242. WriteNow = FALSE;
  1243. //
  1244. // Make sure the write does not go past the
  1245. // end of file. (segment size).
  1246. //
  1247. ASSERT (Subsection->ControlArea->u.Flags.Image == 0);
  1248. TempOffset = MiEndingOffset(Subsection);
  1249. if (((UINT64)StartingOffset.QuadPart + Mdl->ByteCount) >
  1250. (UINT64)TempOffset.QuadPart) {
  1251. ASSERT ((ULONG)(TempOffset.QuadPart -
  1252. StartingOffset.QuadPart) >
  1253. (Mdl->ByteCount - PAGE_SIZE));
  1254. Mdl->ByteCount = (ULONG)(TempOffset.QuadPart -
  1255. StartingOffset.QuadPart);
  1256. }
  1257. ReflushCount = 0;
  1258. while (TRUE) {
  1259. KeClearEvent (&IoEvent);
  1260. Status = IoSynchronousPageWrite (ControlArea->FilePointer,
  1261. Mdl,
  1262. &StartingOffset,
  1263. &IoEvent,
  1264. &IoStatus);
  1265. if (NT_SUCCESS(Status)) {
  1266. KeWaitForSingleObject (&IoEvent,
  1267. WrPageOut,
  1268. KernelMode,
  1269. FALSE,
  1270. NULL);
  1271. }
  1272. else {
  1273. IoStatus.Status = Status;
  1274. }
  1275. if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
  1276. MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
  1277. }
  1278. if (MmIsRetryIoStatus(IoStatus.Status)) {
  1279. ReflushCount -= 1;
  1280. if (ReflushCount & MiIoRetryMask) {
  1281. KeDelayExecutionThread (KernelMode, FALSE, (PLARGE_INTEGER)&Mm30Milliseconds);
  1282. continue;
  1283. }
  1284. }
  1285. break;
  1286. }
  1287. Page = (PPFN_NUMBER)(Mdl + 1);
  1288. LOCK_PFN (OldIrql);
  1289. if (MiIsPteOnPdeBoundary(PointerPte) == 0) {
  1290. //
  1291. // The next PTE is not in a different page, make
  1292. // sure this page did not leave memory when the
  1293. // I/O was in progress.
  1294. //
  1295. MiMakeSystemAddressValidPfn (PointerPte);
  1296. }
  1297. if (!NT_SUCCESS(IoStatus.Status)) {
  1298. if ((MmIsRetryIoStatus(IoStatus.Status)) &&
  1299. (MaxClusterSize != 1) &&
  1300. (Mdl->ByteCount > PAGE_SIZE)) {
  1301. //
  1302. // Retried I/O of a cluster have failed, reissue
  1303. // the cluster one page at a time as the
  1304. // storage stack should always be able to
  1305. // make forward progress this way.
  1306. //
  1307. ASSERT (FirstWritten != NULL);
  1308. ASSERT (LastWritten != NULL);
  1309. ASSERT (FirstWritten != LastWritten);
  1310. IoStatus.Information = 0;
  1311. while (Page < LastPage) {
  1312. Pfn2 = MI_PFN_ELEMENT (*Page);
  1313. //
  1314. // Mark the page dirty again so it can be rewritten.
  1315. //
  1316. MI_SET_MODIFIED (Pfn2, 1, 0xE);
  1317. MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF(Pfn2, 21);
  1318. Page += 1;
  1319. }
  1320. PointerPte = FirstWritten;
  1321. LastWritten = NULL;
  1322. MaxClusterSize = 1;
  1323. goto restartchunk;
  1324. }
  1325. }
  1326. //
  1327. // I/O complete unlock pages.
  1328. //
  1329. // NOTE that the error status is ignored.
  1330. //
  1331. while (Page < LastPage) {
  1332. Pfn2 = MI_PFN_ELEMENT (*Page);
  1333. //
  1334. // Make sure the page is still transition.
  1335. //
  1336. WrittenPte = Pfn2->PteAddress;
  1337. MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (Pfn2, 23);
  1338. if (!MI_IS_PFN_DELETED (Pfn2)) {
  1339. //
  1340. // Make sure the prototype PTE is
  1341. // still in the working set.
  1342. //
  1343. MiMakeSystemAddressValidPfn (WrittenPte);
  1344. if (Pfn2->PteAddress != WrittenPte) {
  1345. //
  1346. // The PFN lock was released to make the
  1347. // page table page valid, and while it
  1348. // was released, the physical page
  1349. // was reused. Go onto the next one.
  1350. //
  1351. Page += 1;
  1352. continue;
  1353. }
  1354. WrittenContents = *WrittenPte;
  1355. if ((WrittenContents.u.Soft.Prototype == 0) &&
  1356. (WrittenContents.u.Soft.Transition == 1)) {
  1357. MI_SET_PFN_DELETED (Pfn2);
  1358. ControlArea->NumberOfPfnReferences -= 1;
  1359. ASSERT ((LONG)ControlArea->NumberOfPfnReferences >= 0);
  1360. PageTableFrameIndex = Pfn2->u4.PteFrame;
  1361. Pfn3 = MI_PFN_ELEMENT (PageTableFrameIndex);
  1362. MiDecrementShareCountInline (Pfn3, PageTableFrameIndex);
  1363. //
  1364. // Check the reference count for the page,
  1365. // if the reference count is zero and the
  1366. // page is not on the freelist, move the page
  1367. // to the free list, if the reference
  1368. // count is not zero, ignore this page.
  1369. // When the reference count goes to zero,
  1370. // it will be placed on the free list.
  1371. //
  1372. if ((Pfn2->u3.e2.ReferenceCount == 0) &&
  1373. (Pfn2->u3.e1.PageLocation != FreePageList)) {
  1374. MiUnlinkPageFromList (Pfn2);
  1375. MiReleasePageFileSpace (Pfn2->OriginalPte);
  1376. MiInsertPageInFreeList (*Page);
  1377. }
  1378. }
  1379. WrittenPte->u.Long = 0;
  1380. }
  1381. Page += 1;
  1382. }
  1383. //
  1384. // Indicate that there is no current cluster being built.
  1385. //
  1386. LastWritten = NULL;
  1387. }
  1388. } // end while
  1389. //
  1390. // Get the next subsection if any.
  1391. //
  1392. if (Subsection->NextSubsection == NULL) {
  1393. break;
  1394. }
  1395. Subsection = Subsection->NextSubsection;
  1396. if (ImageSection == FALSE) {
  1397. while (Subsection->SubsectionBase == NULL) {
  1398. Subsection = Subsection->NextSubsection;
  1399. if (Subsection == NULL) {
  1400. goto alldone;
  1401. }
  1402. }
  1403. }
  1404. PointerPte = Subsection->SubsectionBase;
  1405. LastPte = PointerPte + Subsection->PtesInSubsection;
  1406. } // end for
  1407. alldone:
  1408. ControlArea->NumberOfMappedViews = 0;
  1409. ASSERT (ControlArea->NumberOfPfnReferences == 0);
  1410. if (ControlArea->u.Flags.FilePointerNull == 0) {
  1411. ControlArea->u.Flags.FilePointerNull = 1;
  1412. if (ControlArea->u.Flags.Image) {
  1413. MiRemoveImageSectionObject (ControlArea->FilePointer, ControlArea);
  1414. }
  1415. else {
  1416. ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) != NULL);
  1417. ControlArea->FilePointer->SectionObjectPointer->DataSectionObject = NULL;
  1418. }
  1419. }
  1420. UNLOCK_PFN (OldIrql);
  1421. //
  1422. // Delete the segment structure.
  1423. //
  1424. MiSegmentDelete (ControlArea->Segment);
  1425. return;
  1426. }
  1427. NTSTATUS
  1428. MmGetFileNameForSection (
  1429. IN PSECTION SectionObject,
  1430. OUT PSTRING FileName
  1431. )
  1432. /*++
  1433. Routine Description:
  1434. This function returns the file name for the corresponding section.
  1435. Arguments:
  1436. SectionObject - Supplies the section to get the name of.
  1437. FileName - Returns the name of the corresponding section.
  1438. Return Value:
  1439. TBS
  1440. Environment:
  1441. Kernel mode, APC_LEVEL or below, no mutexes held.
  1442. --*/
  1443. {
  1444. POBJECT_NAME_INFORMATION FileNameInfo;
  1445. ULONG whocares;
  1446. NTSTATUS Status;
  1447. #define xMAX_NAME 1024
  1448. if (SectionObject->u.Flags.Image == 0) {
  1449. return STATUS_SECTION_NOT_IMAGE;
  1450. }
  1451. FileNameInfo = ExAllocatePoolWithTag (PagedPool, xMAX_NAME, ' mM');
  1452. if ( !FileNameInfo ) {
  1453. return STATUS_NO_MEMORY;
  1454. }
  1455. Status = ObQueryNameString(
  1456. SectionObject->Segment->ControlArea->FilePointer,
  1457. FileNameInfo,
  1458. xMAX_NAME,
  1459. &whocares
  1460. );
  1461. if ( !NT_SUCCESS(Status) ) {
  1462. ExFreePool(FileNameInfo);
  1463. return Status;
  1464. }
  1465. FileName->Length = 0;
  1466. FileName->MaximumLength = (USHORT)((FileNameInfo->Name.Length/sizeof(WCHAR)) + 1);
  1467. FileName->Buffer = ExAllocatePoolWithTag (PagedPool,
  1468. FileName->MaximumLength,
  1469. ' mM');
  1470. if (!FileName->Buffer) {
  1471. ExFreePool(FileNameInfo);
  1472. return STATUS_NO_MEMORY;
  1473. }
  1474. RtlUnicodeStringToAnsiString ((PANSI_STRING)FileName,
  1475. &FileNameInfo->Name,FALSE);
  1476. FileName->Buffer[FileName->Length] = '\0';
  1477. ExFreePool(FileNameInfo);
  1478. return STATUS_SUCCESS;
  1479. }
  1480. NTSTATUS
  1481. MmGetFileNameForAddress (
  1482. IN PVOID ProcessVa,
  1483. OUT PUNICODE_STRING FileName
  1484. )
  1485. /*++
  1486. Routine Description:
  1487. This function returns the file name for the corresponding process address if it corresponds to an image section.
  1488. Arguments:
  1489. ProcessVa - Process virtual address
  1490. FileName - Returns the name of the corresponding section.
  1491. Return Value:
  1492. NTSTATUS - Status of operation
  1493. Environment:
  1494. Kernel mode, APC_LEVEL or below, no mutexes held.
  1495. --*/
  1496. {
  1497. PMMVAD Vad;
  1498. PFILE_OBJECT FileObject;
  1499. PCONTROL_AREA ControlArea;
  1500. NTSTATUS Status;
  1501. ULONG RetLen;
  1502. ULONG BufLen;
  1503. PEPROCESS Process;
  1504. POBJECT_NAME_INFORMATION FileNameInfo;
  1505. PAGED_CODE ();
  1506. Process = PsGetCurrentProcess();
  1507. LOCK_ADDRESS_SPACE (Process);
  1508. Vad = MiLocateAddress (ProcessVa);
  1509. if (Vad == NULL) {
  1510. //
  1511. // No virtual address is allocated at the specified base address,
  1512. // return an error.
  1513. //
  1514. Status = STATUS_INVALID_ADDRESS;
  1515. goto ErrorReturn;
  1516. }
  1517. //
  1518. // Reject private memory.
  1519. //
  1520. if (Vad->u.VadFlags.PrivateMemory == 1) {
  1521. Status = STATUS_SECTION_NOT_IMAGE;
  1522. goto ErrorReturn;
  1523. }
  1524. ControlArea = Vad->ControlArea;
  1525. if (ControlArea == NULL) {
  1526. Status = STATUS_SECTION_NOT_IMAGE;
  1527. goto ErrorReturn;
  1528. }
  1529. //
  1530. // Reject non-image sections.
  1531. //
  1532. if (ControlArea->u.Flags.Image == 0) {
  1533. Status = STATUS_SECTION_NOT_IMAGE;
  1534. goto ErrorReturn;
  1535. }
  1536. FileObject = ControlArea->FilePointer;
  1537. ASSERT (FileObject != NULL);
  1538. ObReferenceObject (FileObject);
  1539. UNLOCK_ADDRESS_SPACE (Process);
  1540. //
  1541. // Pick an initial size big enough for most reasonable files.
  1542. //
  1543. BufLen = sizeof (*FileNameInfo) + 1024;
  1544. do {
  1545. FileNameInfo = ExAllocatePoolWithTag (PagedPool, BufLen, ' mM');
  1546. if (FileNameInfo == NULL) {
  1547. Status = STATUS_NO_MEMORY;
  1548. break;
  1549. }
  1550. RetLen = 0;
  1551. Status = ObQueryNameString (FileObject, FileNameInfo, BufLen, &RetLen);
  1552. if (NT_SUCCESS (Status)) {
  1553. FileName->Length = FileName->MaximumLength = FileNameInfo->Name.Length;
  1554. FileName->Buffer = (PWCHAR) FileNameInfo;
  1555. RtlMoveMemory (FileName->Buffer, FileNameInfo->Name.Buffer, FileName->Length);
  1556. }
  1557. else {
  1558. ExFreePool (FileNameInfo);
  1559. if (RetLen > BufLen) {
  1560. BufLen = RetLen;
  1561. continue;
  1562. }
  1563. }
  1564. break;
  1565. } while (TRUE);
  1566. ObDereferenceObject (FileObject);
  1567. return Status;
  1568. ErrorReturn:
  1569. UNLOCK_ADDRESS_SPACE (Process);
  1570. return Status;
  1571. }
  1572. PFILE_OBJECT
  1573. MmGetFileObjectForSection (
  1574. IN PVOID Section
  1575. )
  1576. /*++
  1577. Routine Description:
  1578. This routine returns a pointer to the file object backing a section object.
  1579. Arguments:
  1580. Section - Supplies the section to query.
  1581. Return Value:
  1582. A pointer to the file object backing the argument section.
  1583. Environment:
  1584. Kernel mode, PASSIVE_LEVEL.
  1585. The caller must ensure that the section is valid for the
  1586. duration of the call.
  1587. --*/
  1588. {
  1589. PFILE_OBJECT FileObject;
  1590. ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL);
  1591. ASSERT (Section != NULL);
  1592. FileObject = ((PSECTION)Section)->Segment->ControlArea->FilePointer;
  1593. return FileObject;
  1594. }
  1595. VOID
  1596. MiCheckControlArea (
  1597. IN PCONTROL_AREA ControlArea,
  1598. IN PEPROCESS CurrentProcess,
  1599. IN KIRQL PreviousIrql
  1600. )
  1601. /*++
  1602. Routine Description:
  1603. This routine checks the reference counts for the specified
  1604. control area, and if the counts are all zero, it marks the
  1605. control area for deletion and queues it to the deletion thread.
  1606. *********************** NOTE ********************************
  1607. This routine returns with the PFN LOCK RELEASED!!!!!
  1608. Arguments:
  1609. ControlArea - Supplies a pointer to the control area to check.
  1610. CurrentProcess - Supplies a pointer to the current process if and ONLY
  1611. IF the working set lock is held.
  1612. PreviousIrql - Supplies the previous IRQL.
  1613. Return Value:
  1614. NONE.
  1615. Environment:
  1616. Kernel mode, PFN lock held, PFN lock released upon return!!!
  1617. --*/
  1618. {
  1619. PEVENT_COUNTER PurgeEvent;
  1620. ULONG DeleteOnClose;
  1621. ULONG DereferenceSegment;
  1622. ULONG PagedPoolPercentInUse;
  1623. ULONG NonPagedPoolPercentInUse;
  1624. PurgeEvent = NULL;
  1625. DeleteOnClose = FALSE;
  1626. DereferenceSegment = FALSE;
  1627. MM_PFN_LOCK_ASSERT();
  1628. if ((ControlArea->NumberOfMappedViews == 0) &&
  1629. (ControlArea->NumberOfSectionReferences == 0)) {
  1630. ASSERT (ControlArea->NumberOfUserReferences == 0);
  1631. if (ControlArea->FilePointer != (PFILE_OBJECT)NULL) {
  1632. if (ControlArea->NumberOfPfnReferences == 0) {
  1633. //
  1634. // There are no views and no physical pages referenced
  1635. // by the Segment, dereference the Segment object.
  1636. //
  1637. ControlArea->u.Flags.BeingDeleted = 1;
  1638. DereferenceSegment = TRUE;
  1639. ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
  1640. ControlArea->u.Flags.FilePointerNull = 1;
  1641. if (ControlArea->u.Flags.Image) {
  1642. MiRemoveImageSectionObject (ControlArea->FilePointer, ControlArea);
  1643. }
  1644. else {
  1645. ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) != NULL);
  1646. ControlArea->FilePointer->SectionObjectPointer->DataSectionObject = NULL;
  1647. }
  1648. }
  1649. else {
  1650. //
  1651. // Insert this segment into the unused segment list (unless
  1652. // it is already on the list).
  1653. //
  1654. if (ControlArea->DereferenceList.Flink == NULL) {
  1655. MI_INSERT_UNUSED_SEGMENT (ControlArea);
  1656. }
  1657. //
  1658. // Indicate if this section should be deleted now that
  1659. // the reference counts are zero.
  1660. //
  1661. DeleteOnClose = ControlArea->u.Flags.DeleteOnClose;
  1662. //
  1663. // The number of mapped views are zero, the number of
  1664. // section references are zero, but there are some
  1665. // pages of the file still resident. If this is
  1666. // an image with Global Memory, "purge" the subsections
  1667. // which contain the global memory and reset them to
  1668. // point back to the file.
  1669. //
  1670. if (ControlArea->u.Flags.GlobalMemory == 1) {
  1671. ASSERT (ControlArea->u.Flags.Image == 1);
  1672. ControlArea->u.Flags.BeingPurged = 1;
  1673. ControlArea->NumberOfMappedViews = 1;
  1674. MiPurgeImageSection (ControlArea, CurrentProcess);
  1675. ControlArea->u.Flags.BeingPurged = 0;
  1676. ControlArea->NumberOfMappedViews -= 1;
  1677. if ((ControlArea->NumberOfMappedViews == 0) &&
  1678. (ControlArea->NumberOfSectionReferences == 0) &&
  1679. (ControlArea->NumberOfPfnReferences == 0)) {
  1680. ControlArea->u.Flags.BeingDeleted = 1;
  1681. DereferenceSegment = TRUE;
  1682. ControlArea->u.Flags.FilePointerNull = 1;
  1683. MiRemoveImageSectionObject (ControlArea->FilePointer,
  1684. ControlArea);
  1685. }
  1686. else {
  1687. PurgeEvent = ControlArea->WaitingForDeletion;
  1688. ControlArea->WaitingForDeletion = NULL;
  1689. }
  1690. }
  1691. //
  1692. // If delete on close is set and the segment was
  1693. // not deleted, up the count of mapped views so the
  1694. // control area will not be deleted when the PFN lock
  1695. // is released.
  1696. //
  1697. if (DeleteOnClose && !DereferenceSegment) {
  1698. ControlArea->NumberOfMappedViews = 1;
  1699. ControlArea->u.Flags.BeingDeleted = 1;
  1700. }
  1701. }
  1702. }
  1703. else {
  1704. //
  1705. // This Segment is backed by a paging file, dereference the
  1706. // Segment object when the number of views goes from 1 to 0
  1707. // without regard to the number of PFN references.
  1708. //
  1709. ControlArea->u.Flags.BeingDeleted = 1;
  1710. DereferenceSegment = TRUE;
  1711. }
  1712. }
  1713. else if (ControlArea->WaitingForDeletion != NULL) {
  1714. PurgeEvent = ControlArea->WaitingForDeletion;
  1715. ControlArea->WaitingForDeletion = NULL;
  1716. }
  1717. UNLOCK_PFN (PreviousIrql);
  1718. if (DereferenceSegment || DeleteOnClose) {
  1719. //
  1720. // Release the working set mutex, if it is held as the object
  1721. // management routines may page fault, etc..
  1722. //
  1723. if (CurrentProcess) {
  1724. UNLOCK_WS_UNSAFE (CurrentProcess);
  1725. }
  1726. ASSERT (ControlArea->Segment->WritableUserReferences == 0);
  1727. if (DereferenceSegment) {
  1728. //
  1729. // Delete the segment.
  1730. //
  1731. MiSegmentDelete (ControlArea->Segment);
  1732. }
  1733. else {
  1734. //
  1735. // The segment should be forced closed now.
  1736. //
  1737. MiCleanSection (ControlArea, TRUE);
  1738. }
  1739. ASSERT (PurgeEvent == NULL);
  1740. //
  1741. // Reacquire the working set lock, if a process was specified.
  1742. //
  1743. if (CurrentProcess) {
  1744. LOCK_WS_UNSAFE (CurrentProcess);
  1745. }
  1746. }
  1747. else {
  1748. //
  1749. // If any threads are waiting for the segment, indicate the
  1750. // the purge operation has completed.
  1751. //
  1752. if (PurgeEvent != NULL) {
  1753. KeSetEvent (&PurgeEvent->Event, 0, FALSE);
  1754. }
  1755. PagedPoolPercentInUse = (ULONG)((MmPagedPoolInfo.AllocatedPagedPool * 100) / (MmSizeOfPagedPoolInBytes >> PAGE_SHIFT));
  1756. NonPagedPoolPercentInUse = (ULONG)((MmAllocatedNonPagedPool * 100) / (MmMaximumNonPagedPoolInBytes >> PAGE_SHIFT));
  1757. if ((PagedPoolPercentInUse > MmConsumedPoolPercentage) ||
  1758. (NonPagedPoolPercentInUse > MmConsumedPoolPercentage)) {
  1759. KeSetEvent (&MmUnusedSegmentCleanup, 0, FALSE);
  1760. }
  1761. }
  1762. return;
  1763. }
  1764. VOID
  1765. MiCheckForControlAreaDeletion (
  1766. IN PCONTROL_AREA ControlArea
  1767. )
  1768. /*++
  1769. Routine Description:
  1770. This routine checks the reference counts for the specified
  1771. control area, and if the counts are all zero, it marks the
  1772. control area for deletion and queues it to the deletion thread.
  1773. Arguments:
  1774. ControlArea - Supplies a pointer to the control area to check.
  1775. Return Value:
  1776. None.
  1777. Environment:
  1778. Kernel mode, PFN lock held.
  1779. --*/
  1780. {
  1781. KIRQL OldIrql;
  1782. MM_PFN_LOCK_ASSERT();
  1783. if ((ControlArea->NumberOfPfnReferences == 0) &&
  1784. (ControlArea->NumberOfMappedViews == 0) &&
  1785. (ControlArea->NumberOfSectionReferences == 0 )) {
  1786. //
  1787. // This segment is no longer mapped in any address space
  1788. // nor are there any prototype PTEs within the segment
  1789. // which are valid or in a transition state. Queue
  1790. // the segment to the segment-dereferencer thread
  1791. // which will dereference the segment object, potentially
  1792. // causing the segment to be deleted.
  1793. //
  1794. ControlArea->u.Flags.BeingDeleted = 1;
  1795. ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
  1796. ControlArea->u.Flags.FilePointerNull = 1;
  1797. if (ControlArea->u.Flags.Image) {
  1798. MiRemoveImageSectionObject (ControlArea->FilePointer,
  1799. ControlArea);
  1800. }
  1801. else {
  1802. ControlArea->FilePointer->SectionObjectPointer->DataSectionObject =
  1803. NULL;
  1804. }
  1805. ExAcquireSpinLock (&MmDereferenceSegmentHeader.Lock, &OldIrql);
  1806. if (ControlArea->DereferenceList.Flink != NULL) {
  1807. //
  1808. // Remove the entry from the unused segment list and put it
  1809. // on the dereference list.
  1810. //
  1811. RemoveEntryList (&ControlArea->DereferenceList);
  1812. MI_UNUSED_SEGMENTS_REMOVE_CHARGE (ControlArea);
  1813. }
  1814. //
  1815. // Image sections still have useful header information in their segment
  1816. // even if no pages are valid or transition so put these at the tail.
  1817. // Data sections have nothing of use if all the data pages are gone so
  1818. // we used to put those at the front. Now both types go to the rear
  1819. // so that commit extensions go to the front for earlier processing.
  1820. //
  1821. InsertTailList (&MmDereferenceSegmentHeader.ListHead,
  1822. &ControlArea->DereferenceList);
  1823. ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);
  1824. KeReleaseSemaphore (&MmDereferenceSegmentHeader.Semaphore,
  1825. 0L,
  1826. 1L,
  1827. FALSE);
  1828. }
  1829. return;
  1830. }
  1831. LOGICAL
  1832. MiCheckControlAreaStatus (
  1833. IN SECTION_CHECK_TYPE SectionCheckType,
  1834. IN PSECTION_OBJECT_POINTERS SectionObjectPointers,
  1835. IN ULONG DelayClose,
  1836. OUT PCONTROL_AREA *ControlAreaOut,
  1837. OUT PKIRQL PreviousIrql
  1838. )
  1839. /*++
  1840. Routine Description:
  1841. This routine checks the status of the control area for the specified
  1842. SectionObjectPointers. If the control area is in use, that is, the
  1843. number of section references and the number of mapped views are not
  1844. both zero, no action is taken and the function returns FALSE.
  1845. If there is no control area associated with the specified
  1846. SectionObjectPointers or the control area is in the process of being
  1847. created or deleted, no action is taken and the value TRUE is returned.
  1848. If, there are no section objects and the control area is not being
  1849. created or deleted, the address of the control area is returned
  1850. in the ControlArea argument, the address of a pool block to free
  1851. is returned in the SegmentEventOut argument and the PFN_LOCK is
  1852. still held at the return.
  1853. Arguments:
  1854. *SegmentEventOut - Returns a pointer to NonPaged Pool which much be
  1855. freed by the caller when the PFN_LOCK is released.
  1856. This value is NULL if no pool is allocated and the
  1857. PFN_LOCK is not held.
  1858. SectionCheckType - Supplies the type of section to check on, one of
  1859. CheckImageSection, CheckDataSection, CheckBothSection.
  1860. SectionObjectPointers - Supplies the section object pointers through
  1861. which the control area can be located.
  1862. DelayClose - Supplies a boolean which if TRUE and the control area
  1863. is being used, the delay on close field should be set
  1864. in the control area.
  1865. *ControlAreaOut - Returns the address of the control area.
  1866. PreviousIrql - Returns, in the case the PFN_LOCK is held, the previous
  1867. IRQL so the lock can be released properly.
  1868. Return Value:
  1869. FALSE if the control area is in use, TRUE if the control area is gone or
  1870. in the process or being created or deleted.
  1871. Environment:
  1872. Kernel mode, PFN lock NOT held.
  1873. --*/
  1874. {
  1875. PKTHREAD CurrentThread;
  1876. PEVENT_COUNTER IoEvent;
  1877. PEVENT_COUNTER SegmentEvent;
  1878. LOGICAL DeallocateSegmentEvent;
  1879. PCONTROL_AREA ControlArea;
  1880. ULONG SectRef;
  1881. KIRQL OldIrql;
  1882. //
  1883. // Allocate an event to wait on in case the segment is in the
  1884. // process of being deleted. This event cannot be allocated
  1885. // with the PFN database locked as pool expansion would deadlock.
  1886. //
  1887. *ControlAreaOut = NULL;
  1888. do {
  1889. SegmentEvent = MiGetEventCounter ();
  1890. if (SegmentEvent != NULL) {
  1891. break;
  1892. }
  1893. KeDelayExecutionThread (KernelMode,
  1894. FALSE,
  1895. (PLARGE_INTEGER)&MmShortTime);
  1896. } while (TRUE);
  1897. //
  1898. // Acquire the PFN lock and examine the section object pointer
  1899. // value within the file object.
  1900. //
  1901. // File control blocks live in non-paged pool.
  1902. //
  1903. LOCK_PFN (OldIrql);
  1904. if (SectionCheckType != CheckImageSection) {
  1905. ControlArea = ((PCONTROL_AREA)(SectionObjectPointers->DataSectionObject));
  1906. }
  1907. else {
  1908. ControlArea = ((PCONTROL_AREA)(SectionObjectPointers->ImageSectionObject));
  1909. }
  1910. if (ControlArea == NULL) {
  1911. if (SectionCheckType != CheckBothSection) {
  1912. //
  1913. // This file no longer has an associated segment.
  1914. //
  1915. UNLOCK_PFN (OldIrql);
  1916. MiFreeEventCounter (SegmentEvent);
  1917. return TRUE;
  1918. }
  1919. else {
  1920. ControlArea = ((PCONTROL_AREA)(SectionObjectPointers->ImageSectionObject));
  1921. if (ControlArea == NULL) {
  1922. //
  1923. // This file no longer has an associated segment.
  1924. //
  1925. UNLOCK_PFN (OldIrql);
  1926. MiFreeEventCounter (SegmentEvent);
  1927. return TRUE;
  1928. }
  1929. }
  1930. }
  1931. //
  1932. // Depending on the type of section, check for the pertinent
  1933. // reference count being non-zero.
  1934. //
  1935. if (SectionCheckType != CheckUserDataSection) {
  1936. SectRef = ControlArea->NumberOfSectionReferences;
  1937. }
  1938. else {
  1939. SectRef = ControlArea->NumberOfUserReferences;
  1940. }
  1941. if ((SectRef != 0) ||
  1942. (ControlArea->NumberOfMappedViews != 0) ||
  1943. (ControlArea->u.Flags.BeingCreated)) {
  1944. //
  1945. // The segment is currently in use or being created.
  1946. //
  1947. if (DelayClose) {
  1948. //
  1949. // The section should be deleted when the reference
  1950. // counts are zero, set the delete on close flag.
  1951. //
  1952. ControlArea->u.Flags.DeleteOnClose = 1;
  1953. }
  1954. UNLOCK_PFN (OldIrql);
  1955. MiFreeEventCounter (SegmentEvent);
  1956. return FALSE;
  1957. }
  1958. //
  1959. // The segment has no references, delete it. If the segment
  1960. // is already being deleted, set the event field in the control
  1961. // area and wait on the event.
  1962. //
  1963. if (ControlArea->u.Flags.BeingDeleted) {
  1964. //
  1965. // The segment object is in the process of being deleted.
  1966. // Check to see if another thread is waiting for the deletion,
  1967. // otherwise create and event object to wait upon.
  1968. //
  1969. if (ControlArea->WaitingForDeletion == NULL) {
  1970. //
  1971. // Create an event and put its address in the control area.
  1972. //
  1973. DeallocateSegmentEvent = FALSE;
  1974. ControlArea->WaitingForDeletion = SegmentEvent;
  1975. IoEvent = SegmentEvent;
  1976. }
  1977. else {
  1978. DeallocateSegmentEvent = TRUE;
  1979. IoEvent = ControlArea->WaitingForDeletion;
  1980. //
  1981. // No interlock is needed for the RefCount increment as
  1982. // no thread can be decrementing it since it is still
  1983. // pointed to by the control area.
  1984. //
  1985. IoEvent->RefCount += 1;
  1986. }
  1987. //
  1988. // Release the mutex and wait for the event.
  1989. //
  1990. CurrentThread = KeGetCurrentThread ();
  1991. KeEnterCriticalRegionThread (CurrentThread);
  1992. UNLOCK_PFN_AND_THEN_WAIT(OldIrql);
  1993. KeWaitForSingleObject(&IoEvent->Event,
  1994. WrPageOut,
  1995. KernelMode,
  1996. FALSE,
  1997. (PLARGE_INTEGER)NULL);
  1998. //
  1999. // Before this event can be set, the control area
  2000. // WaitingForDeletion field must be cleared (and may be
  2001. // reinitialized to something else), but cannot be reset
  2002. // to our local event. This allows us to dereference the
  2003. // event count lock free.
  2004. //
  2005. #if 0
  2006. //
  2007. // Note that the control area cannot be referenced at this
  2008. // point because it may have been freed.
  2009. //
  2010. ASSERT (IoEvent != ControlArea->WaitingForDeletion);
  2011. #endif
  2012. KeLeaveCriticalRegionThread (CurrentThread);
  2013. MiFreeEventCounter (IoEvent);
  2014. if (DeallocateSegmentEvent == TRUE) {
  2015. MiFreeEventCounter (SegmentEvent);
  2016. }
  2017. return TRUE;
  2018. }
  2019. //
  2020. // Return with the PFN database locked.
  2021. //
  2022. ASSERT (SegmentEvent->RefCount == 1);
  2023. ASSERT (SegmentEvent->ListEntry.Next == NULL);
  2024. //
  2025. // NO interlock is needed for the RefCount clearing as the event counter
  2026. // was never pointed to by a control area.
  2027. //
  2028. #if DBG
  2029. SegmentEvent->RefCount = 0;
  2030. #endif
  2031. InterlockedPushEntrySList (&MmEventCountSListHead,
  2032. (PSINGLE_LIST_ENTRY)&SegmentEvent->ListEntry);
  2033. *ControlAreaOut = ControlArea;
  2034. *PreviousIrql = OldIrql;
  2035. return FALSE;
  2036. }
  2037. PEVENT_COUNTER
  2038. MiGetEventCounter (
  2039. VOID
  2040. )
  2041. /*++
  2042. Routine Description:
  2043. This function maintains a list of "events" to allow waiting
  2044. on segment operations (deletion, creation, purging).
  2045. Arguments:
  2046. None.
  2047. Return Value:
  2048. Event to be used for waiting (stored into the control area) or NULL if
  2049. no event could be allocated.
  2050. Environment:
  2051. Kernel mode, APC_LEVEL or below.
  2052. --*/
  2053. {
  2054. PSINGLE_LIST_ENTRY SingleListEntry;
  2055. PEVENT_COUNTER Support;
  2056. ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);
  2057. if (ExQueryDepthSList (&MmEventCountSListHead) != 0) {
  2058. SingleListEntry = InterlockedPopEntrySList (&MmEventCountSListHead);
  2059. if (SingleListEntry != NULL) {
  2060. Support = CONTAINING_RECORD (SingleListEntry,
  2061. EVENT_COUNTER,
  2062. ListEntry);
  2063. ASSERT (Support->RefCount == 0);
  2064. KeClearEvent (&Support->Event);
  2065. Support->RefCount = 1;
  2066. #if DBG
  2067. Support->ListEntry.Next = NULL;
  2068. #endif
  2069. return Support;
  2070. }
  2071. }
  2072. Support = ExAllocatePoolWithTag (NonPagedPool,
  2073. sizeof(EVENT_COUNTER),
  2074. 'xEmM');
  2075. if (Support == NULL) {
  2076. return NULL;
  2077. }
  2078. KeInitializeEvent (&Support->Event, NotificationEvent, FALSE);
  2079. Support->RefCount = 1;
  2080. #if DBG
  2081. Support->ListEntry.Next = NULL;
  2082. #endif
  2083. return Support;
  2084. }
  2085. VOID
  2086. MiFreeEventCounter (
  2087. IN PEVENT_COUNTER Support
  2088. )
  2089. /*++
  2090. Routine Description:
  2091. This routine frees an event counter back to the free list.
  2092. Arguments:
  2093. Support - Supplies a pointer to the event counter.
  2094. Return Value:
  2095. None.
  2096. Environment:
  2097. Kernel mode, APC_LEVEL or below.
  2098. --*/
  2099. {
  2100. PSINGLE_LIST_ENTRY SingleListEntry;
  2101. ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);
  2102. ASSERT (Support->RefCount != 0);
  2103. ASSERT (Support->ListEntry.Next == NULL);
  2104. //
  2105. // An interlock is needed for the RefCount decrement as the event counter
  2106. // is no longer pointed to by a control area and thus, any number of
  2107. // threads can be running this code without any other serialization.
  2108. //
  2109. if (InterlockedDecrement ((PLONG)&Support->RefCount) == 0) {
  2110. if (ExQueryDepthSList (&MmEventCountSListHead) < 4) {
  2111. InterlockedPushEntrySList (&MmEventCountSListHead,
  2112. (PSINGLE_LIST_ENTRY)&Support->ListEntry);
  2113. return;
  2114. }
  2115. ExFreePool (Support);
  2116. }
  2117. //
  2118. // If excess event blocks are stashed then free them now.
  2119. //
  2120. while (ExQueryDepthSList (&MmEventCountSListHead) > 4) {
  2121. SingleListEntry = InterlockedPopEntrySList (&MmEventCountSListHead);
  2122. if (SingleListEntry != NULL) {
  2123. Support = CONTAINING_RECORD (SingleListEntry,
  2124. EVENT_COUNTER,
  2125. ListEntry);
  2126. ExFreePool (Support);
  2127. }
  2128. }
  2129. return;
  2130. }
  2131. BOOLEAN
  2132. MmCanFileBeTruncated (
  2133. IN PSECTION_OBJECT_POINTERS SectionPointer,
  2134. IN PLARGE_INTEGER NewFileSize
  2135. )
  2136. /*++
  2137. Routine Description:
  2138. This routine does the following:
  2139. 1. Checks to see if a image section is in use for the file,
  2140. if so it returns FALSE.
  2141. 2. Checks to see if a user section exists for the file, if
  2142. it does, it checks to make sure the new file size is greater
  2143. than the size of the file, if not it returns FALSE.
  2144. 3. If no image section exists, and no user created data section
  2145. exists or the file's size is greater, then TRUE is returned.
  2146. Arguments:
  2147. SectionPointer - Supplies a pointer to the section object pointers
  2148. from the file object.
  2149. NewFileSize - Supplies a pointer to the size the file is getting set to.
  2150. Return Value:
  2151. TRUE if the file can be truncated, FALSE if it cannot be.
  2152. Environment:
  2153. Kernel mode.
  2154. --*/
  2155. {
  2156. LARGE_INTEGER LocalOffset;
  2157. KIRQL OldIrql;
  2158. //
  2159. // Capture caller's file size, since we may modify it.
  2160. //
  2161. if (ARGUMENT_PRESENT(NewFileSize)) {
  2162. LocalOffset = *NewFileSize;
  2163. NewFileSize = &LocalOffset;
  2164. }
  2165. if (MiCanFileBeTruncatedInternal( SectionPointer, NewFileSize, FALSE, &OldIrql )) {
  2166. UNLOCK_PFN (OldIrql);
  2167. return TRUE;
  2168. }
  2169. return FALSE;
  2170. }
  2171. ULONG
  2172. MiCanFileBeTruncatedInternal (
  2173. IN PSECTION_OBJECT_POINTERS SectionPointer,
  2174. IN PLARGE_INTEGER NewFileSize OPTIONAL,
  2175. IN LOGICAL BlockNewViews,
  2176. OUT PKIRQL PreviousIrql
  2177. )
  2178. /*++
  2179. Routine Description:
  2180. This routine does the following:
  2181. 1. Checks to see if a image section is in use for the file,
  2182. if so it returns FALSE.
  2183. 2. Checks to see if a user section exists for the file, if
  2184. it does, it checks to make sure the new file size is greater
  2185. than the size of the file, if not it returns FALSE.
  2186. 3. If no image section exists, and no user created data section
  2187. exists or the files size is greater, then TRUE is returned.
  2188. Arguments:
  2189. SectionPointer - Supplies a pointer to the section object pointers
  2190. from the file object.
  2191. NewFileSize - Supplies a pointer to the size the file is getting set to.
  2192. BlockNewViews - Supplies TRUE if the caller will block new views while
  2193. the operation (usually a purge) proceeds. This allows
  2194. this routine to return TRUE even if the user has section
  2195. references, provided the user currently has no mapped views.
  2196. PreviousIrql - If returning TRUE, returns Irql to use when unlocking
  2197. Pfn database.
  2198. Return Value:
  2199. TRUE if the file can be truncated (PFN locked).
  2200. FALSE if it cannot be truncated (PFN not locked).
  2201. Environment:
  2202. Kernel mode.
  2203. --*/
  2204. {
  2205. KIRQL OldIrql;
  2206. LARGE_INTEGER SegmentSize;
  2207. PCONTROL_AREA ControlArea;
  2208. PSUBSECTION Subsection;
  2209. PMAPPED_FILE_SEGMENT Segment;
  2210. if (!MmFlushImageSection (SectionPointer, MmFlushForWrite)) {
  2211. return FALSE;
  2212. }
  2213. LOCK_PFN (OldIrql);
  2214. ControlArea = (PCONTROL_AREA)(SectionPointer->DataSectionObject);
  2215. if (ControlArea != NULL) {
  2216. if ((ControlArea->u.Flags.BeingCreated) ||
  2217. (ControlArea->u.Flags.BeingDeleted) ||
  2218. (ControlArea->u.Flags.Rom)) {
  2219. goto UnlockAndReturn;
  2220. }
  2221. //
  2222. // If there are user references and the size is less than the
  2223. // size of the user view, don't allow the truncation.
  2224. //
  2225. if ((ControlArea->NumberOfUserReferences != 0) &&
  2226. ((BlockNewViews == FALSE) || (ControlArea->NumberOfMappedViews != 0))) {
  2227. //
  2228. // You cannot truncate the entire section if there is a user
  2229. // reference.
  2230. //
  2231. if (!ARGUMENT_PRESENT(NewFileSize)) {
  2232. goto UnlockAndReturn;
  2233. }
  2234. //
  2235. // Locate last subsection and get total size.
  2236. //
  2237. ASSERT (ControlArea->u.Flags.Image == 0);
  2238. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 0);
  2239. Subsection = (PSUBSECTION)(ControlArea + 1);
  2240. if (ControlArea->FilePointer != NULL) {
  2241. Segment = (PMAPPED_FILE_SEGMENT) ControlArea->Segment;
  2242. if (MmIsAddressValid (Segment)) {
  2243. if (Segment->LastSubsectionHint != NULL) {
  2244. Subsection = (PSUBSECTION) Segment->LastSubsectionHint;
  2245. }
  2246. }
  2247. }
  2248. while (Subsection->NextSubsection != NULL) {
  2249. Subsection = Subsection->NextSubsection;
  2250. }
  2251. ASSERT (Subsection->ControlArea == ControlArea);
  2252. SegmentSize = MiEndingOffset(Subsection);
  2253. if ((UINT64)NewFileSize->QuadPart < (UINT64)SegmentSize.QuadPart) {
  2254. goto UnlockAndReturn;
  2255. }
  2256. //
  2257. // If there are mapped views, we will skip the last page
  2258. // of the section if the size passed in falls in that page.
  2259. // The caller (like Cc) may want to clear this fractional page.
  2260. //
  2261. SegmentSize.QuadPart += PAGE_SIZE - 1;
  2262. SegmentSize.LowPart &= ~(PAGE_SIZE - 1);
  2263. if ((UINT64)NewFileSize->QuadPart < (UINT64)SegmentSize.QuadPart) {
  2264. *NewFileSize = SegmentSize;
  2265. }
  2266. }
  2267. }
  2268. *PreviousIrql = OldIrql;
  2269. return TRUE;
  2270. UnlockAndReturn:
  2271. UNLOCK_PFN (OldIrql);
  2272. return FALSE;
  2273. }
  2274. PFILE_OBJECT *
  2275. MmPerfUnusedSegmentsEnumerate (
  2276. VOID
  2277. )
  2278. /*++
  2279. Routine Description:
  2280. This routine walks the MmUnusedSegmentList and returns
  2281. a pointer to a pool allocation containing the
  2282. referenced file object pointers.
  2283. Arguments:
  2284. None.
  2285. Return Value:
  2286. Returns a pointer to a NULL terminated pool allocation containing the
  2287. file object pointers from the unused segment list, NULL if the memory
  2288. could not be allocated.
  2289. It is also the responsibility of the caller to dereference each
  2290. file object in the list and then free the returned pool.
  2291. Environment:
  2292. PASSIVE_LEVEL, arbitrary thread context.
  2293. --*/
  2294. {
  2295. KIRQL OldIrql;
  2296. ULONG SegmentCount;
  2297. PFILE_OBJECT *FileObjects;
  2298. PFILE_OBJECT *File;
  2299. PLIST_ENTRY NextEntry;
  2300. PCONTROL_AREA ControlArea;
  2301. ASSERT (KeGetCurrentIrql () == PASSIVE_LEVEL);
  2302. ReAllocate:
  2303. SegmentCount = MmUnusedSegmentCount + 10;
  2304. FileObjects = (PFILE_OBJECT *) ExAllocatePoolWithTag (
  2305. NonPagedPool,
  2306. SegmentCount * sizeof(PFILE_OBJECT),
  2307. '01pM');
  2308. if (FileObjects == NULL) {
  2309. return NULL;
  2310. }
  2311. File = FileObjects;
  2312. LOCK_PFN (OldIrql);
  2313. //
  2314. // Leave space for NULL terminator.
  2315. //
  2316. if (SegmentCount - 1 < MmUnusedSegmentCount) {
  2317. UNLOCK_PFN (OldIrql);
  2318. ExFreePool (FileObjects);
  2319. goto ReAllocate;
  2320. }
  2321. NextEntry = MmUnusedSegmentList.Flink;
  2322. while (NextEntry != &MmUnusedSegmentList) {
  2323. ControlArea = CONTAINING_RECORD (NextEntry,
  2324. CONTROL_AREA,
  2325. DereferenceList);
  2326. *File = ControlArea->FilePointer;
  2327. ObReferenceObject(*File);
  2328. File += 1;
  2329. NextEntry = NextEntry->Flink;
  2330. }
  2331. UNLOCK_PFN (OldIrql);
  2332. *File = NULL;
  2333. return FileObjects;
  2334. }
  2335. #if DBG
  2336. PMSUBSECTION MiActiveSubsection;
  2337. LOGICAL MiRemoveSubsectionsFirst;
  2338. #endif
  2339. VOID
  2340. MiRemoveUnusedSegments (
  2341. VOID
  2342. )
  2343. /*++
  2344. Routine Description:
  2345. This routine removes unused segments (no section references,
  2346. no mapped views only PFN references that are in transition state).
  2347. Arguments:
  2348. None.
  2349. Return Value:
  2350. None.
  2351. Environment:
  2352. Kernel mode.
  2353. --*/
  2354. {
  2355. LOGICAL DroppedPfnLock;
  2356. KIRQL OldIrql;
  2357. PLIST_ENTRY NextEntry;
  2358. PCONTROL_AREA ControlArea;
  2359. NTSTATUS Status;
  2360. ULONG ConsecutiveFileLockFailures;
  2361. ULONG ConsecutivePagingIOs;
  2362. PSUBSECTION Subsection;
  2363. PSUBSECTION LastSubsection;
  2364. PSUBSECTION LastSubsectionWithProtos;
  2365. PMSUBSECTION MappedSubsection;
  2366. ULONG NumberOfPtes;
  2367. MMPTE PteContents;
  2368. PMMPTE PointerPte;
  2369. PMMPTE LastPte;
  2370. PMMPTE ProtoPtes;
  2371. PMMPTE ProtoPtes2;
  2372. PMMPTE LastProtoPte;
  2373. PMMPFN Pfn1;
  2374. PMMPFN Pfn2;
  2375. IO_STATUS_BLOCK IoStatus;
  2376. LOGICAL DirtyPagesOk;
  2377. PFN_NUMBER PageFrameIndex;
  2378. PFN_NUMBER PageTableFrameIndex;
  2379. ULONG ForceFree;
  2380. ULONG LoopCount;
  2381. PMMPAGE_FILE_EXPANSION PageExpand;
  2382. LoopCount = 0;
  2383. ConsecutivePagingIOs = 0;
  2384. ConsecutiveFileLockFailures = 0;
  2385. //
  2386. // If overall system pool usage is acceptable, then don't discard
  2387. // any cache.
  2388. //
  2389. while ((MI_UNUSED_SEGMENTS_SURPLUS()) || (MmUnusedSegmentForceFree != 0)) {
  2390. LoopCount += 1;
  2391. if ((LoopCount & (64 - 1)) == 0) {
  2392. //
  2393. // Periodically delay so the mapped and modified writers get
  2394. // a shot at writing out the pages this (higher priority) thread
  2395. // is releasing.
  2396. //
  2397. ExAcquireSpinLock (&MmDereferenceSegmentHeader.Lock, &OldIrql);
  2398. while (!IsListEmpty (&MmDereferenceSegmentHeader.ListHead)) {
  2399. MiSubsectionActions |= 0x8000000;
  2400. //
  2401. // The list is not empty, see if the first request is for
  2402. // a commit extension and if so, process it now.
  2403. //
  2404. NextEntry = MmDereferenceSegmentHeader.ListHead.Flink;
  2405. ControlArea = CONTAINING_RECORD (NextEntry,
  2406. CONTROL_AREA,
  2407. DereferenceList);
  2408. if (ControlArea->Segment != NULL) {
  2409. break;
  2410. }
  2411. PageExpand = (PMMPAGE_FILE_EXPANSION) ControlArea;
  2412. if (PageExpand->RequestedExpansionSize == MI_CONTRACT_PAGEFILES) {
  2413. break;
  2414. }
  2415. //
  2416. // This is a request to expand the paging files.
  2417. //
  2418. MiSubsectionActions |= 0x10000000;
  2419. RemoveEntryList (NextEntry);
  2420. ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);
  2421. MiExtendPagingFiles (PageExpand);
  2422. KeSetEvent (&PageExpand->Event, 0, FALSE);
  2423. ExAcquireSpinLock (&MmDereferenceSegmentHeader.Lock, &OldIrql);
  2424. }
  2425. ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);
  2426. KeDelayExecutionThread (KernelMode, FALSE, (PLARGE_INTEGER)&MmShortTime);
  2427. }
  2428. //
  2429. // Eliminate some of the unused segments which are only
  2430. // kept in memory because they contain transition pages.
  2431. //
  2432. Status = STATUS_SUCCESS;
  2433. LOCK_PFN (OldIrql);
  2434. if ((IsListEmpty(&MmUnusedSegmentList)) &&
  2435. (IsListEmpty(&MmUnusedSubsectionList))) {
  2436. //
  2437. // There is nothing in the list, rewait.
  2438. //
  2439. ForceFree = MmUnusedSegmentForceFree;
  2440. MmUnusedSegmentForceFree = 0;
  2441. ASSERT (MmUnusedSegmentCount == 0);
  2442. UNLOCK_PFN (OldIrql);
  2443. //
  2444. // We weren't able to get as many segments or subsections as we
  2445. // wanted. So signal the cache manager to start unmapping
  2446. // system cache views in an attempt to get back the paged
  2447. // pool containing its prototype PTEs. If Cc was able to free
  2448. // any at all, then restart our loop.
  2449. //
  2450. if (CcUnmapInactiveViews (50) == TRUE) {
  2451. LOCK_PFN (OldIrql);
  2452. if (ForceFree > MmUnusedSegmentForceFree) {
  2453. MmUnusedSegmentForceFree = ForceFree;
  2454. }
  2455. UNLOCK_PFN (OldIrql);
  2456. continue;
  2457. }
  2458. break;
  2459. }
  2460. if (MmUnusedSegmentForceFree != 0) {
  2461. MmUnusedSegmentForceFree -= 1;
  2462. }
  2463. #if DBG
  2464. if (MiRemoveSubsectionsFirst == TRUE) {
  2465. if (!IsListEmpty(&MmUnusedSubsectionList)) {
  2466. goto ProcessSubsectionsFirst;
  2467. }
  2468. }
  2469. #endif
  2470. if (IsListEmpty(&MmUnusedSegmentList)) {
  2471. #if DBG
  2472. ProcessSubsectionsFirst:
  2473. #endif
  2474. //
  2475. // The unused segment list was empty, go for the unused subsection
  2476. // list instead.
  2477. //
  2478. ASSERT (!IsListEmpty(&MmUnusedSubsectionList));
  2479. MiSubsectionsProcessed += 1;
  2480. NextEntry = RemoveHeadList(&MmUnusedSubsectionList);
  2481. MappedSubsection = CONTAINING_RECORD (NextEntry,
  2482. MSUBSECTION,
  2483. DereferenceList);
  2484. ControlArea = MappedSubsection->ControlArea;
  2485. ASSERT (ControlArea->u.Flags.Image == 0);
  2486. ASSERT (ControlArea->u.Flags.PhysicalMemory == 0);
  2487. ASSERT (ControlArea->FilePointer != NULL);
  2488. ASSERT (MappedSubsection->NumberOfMappedViews == 0);
  2489. ASSERT (MappedSubsection->u.SubsectionFlags.SubsectionStatic == 0);
  2490. MI_UNUSED_SUBSECTIONS_COUNT_REMOVE (MappedSubsection);
  2491. //
  2492. // Set the flink to NULL indicating this subsection
  2493. // is not on any lists.
  2494. //
  2495. MappedSubsection->DereferenceList.Flink = NULL;
  2496. if (ControlArea->u.Flags.BeingDeleted == 1) {
  2497. MiSubsectionActions |= 0x1;
  2498. UNLOCK_PFN (OldIrql);
  2499. ConsecutivePagingIOs = 0;
  2500. continue;
  2501. }
  2502. if (ControlArea->u.Flags.NoModifiedWriting == 1) {
  2503. MiSubsectionActions |= 0x2;
  2504. InsertTailList (&MmUnusedSubsectionList,
  2505. &MappedSubsection->DereferenceList);
  2506. MI_UNUSED_SUBSECTIONS_COUNT_INSERT (MappedSubsection);
  2507. UNLOCK_PFN (OldIrql);
  2508. ConsecutivePagingIOs = 0;
  2509. continue;
  2510. }
  2511. //
  2512. // Up the number of mapped views to prevent other threads
  2513. // from freeing this. Clear the accessed bit so we'll know
  2514. // if another thread opens the subsection while we're flushing
  2515. // and closes it before we finish the flush - the other thread
  2516. // may have modified some pages which can then cause our
  2517. // MiCleanSection call (which expects no modified pages in this
  2518. // case) to deadlock with the filesystem.
  2519. //
  2520. MappedSubsection->NumberOfMappedViews = 1;
  2521. MappedSubsection->u2.SubsectionFlags2.SubsectionAccessed = 0;
  2522. #if DBG
  2523. MiActiveSubsection = MappedSubsection;
  2524. #endif
  2525. //
  2526. // Increment the number of mapped views on the control area to
  2527. // prevent threads that are purging the section from deleting it
  2528. // from underneath us while we process one of its subsections.
  2529. //
  2530. ControlArea->NumberOfMappedViews += 1;
  2531. UNLOCK_PFN (OldIrql);
  2532. ASSERT (MappedSubsection->SubsectionBase != NULL);
  2533. PointerPte = &MappedSubsection->SubsectionBase[0];
  2534. LastPte = &MappedSubsection->SubsectionBase
  2535. [MappedSubsection->PtesInSubsection - 1];
  2536. //
  2537. // Preacquire the file to prevent deadlocks with other flushers
  2538. // Also mark ourself as a top level IRP so the filesystem knows
  2539. // we are holding no other resources and that it can unroll if
  2540. // it needs to in order to avoid deadlock. Don't hold this
  2541. // protection any longer than we need to.
  2542. //
  2543. Status = FsRtlAcquireFileForCcFlushEx (ControlArea->FilePointer);
  2544. if (NT_SUCCESS(Status)) {
  2545. IoSetTopLevelIrp((PIRP)FSRTL_FSP_TOP_LEVEL_IRP);
  2546. Status = MiFlushSectionInternal (PointerPte,
  2547. LastPte,
  2548. (PSUBSECTION) MappedSubsection,
  2549. (PSUBSECTION) MappedSubsection,
  2550. FALSE,
  2551. FALSE,
  2552. &IoStatus);
  2553. IoSetTopLevelIrp((PIRP)NULL);
  2554. //
  2555. // Now release the file.
  2556. //
  2557. FsRtlReleaseFileForCcFlush (ControlArea->FilePointer);
  2558. }
  2559. LOCK_PFN (OldIrql);
  2560. #if DBG
  2561. MiActiveSubsection = NULL;
  2562. #endif
  2563. //
  2564. // Before checking for any failure codes, see if any other
  2565. // threads accessed the subsection while the flush was ongoing.
  2566. //
  2567. // Note that beyond the case of another thread currently using
  2568. // the subsection, the more subtle one is where another
  2569. // thread accessed the subsection and modified some pages.
  2570. // The flush needs to redone (so the clean is guaranteed to work)
  2571. // before another clean can be issued.
  2572. //
  2573. // If any of these cases have occurred, grant this subsection
  2574. // a reprieve.
  2575. //
  2576. ASSERT (MappedSubsection->u.SubsectionFlags.SubsectionStatic == 0);
  2577. if ((MappedSubsection->NumberOfMappedViews != 1) ||
  2578. (MappedSubsection->u2.SubsectionFlags2.SubsectionAccessed == 1) ||
  2579. (ControlArea->u.Flags.BeingDeleted == 1)) {
  2580. Requeue:
  2581. MappedSubsection->NumberOfMappedViews -= 1;
  2582. MiSubsectionActions |= 0x4;
  2583. //
  2584. // If the other thread(s) are done with this subsection,
  2585. // it MUST be requeued here - otherwise if there are any
  2586. // pages in the subsection, when they are reclaimed,
  2587. // MiCheckForControlAreaDeletion checks for and expects
  2588. // the control area to be queued on the unused segment list.
  2589. //
  2590. // Note this must be done very carefully because if the other
  2591. // threads are not done with the subsection, it had better
  2592. // not get put on the unused subsection list.
  2593. //
  2594. if ((MappedSubsection->NumberOfMappedViews == 0) &&
  2595. (ControlArea->u.Flags.BeingDeleted == 0)) {
  2596. MiSubsectionActions |= 0x8;
  2597. ASSERT (MappedSubsection->u2.SubsectionFlags2.SubsectionAccessed == 1);
  2598. ASSERT (MappedSubsection->DereferenceList.Flink == NULL);
  2599. InsertTailList (&MmUnusedSubsectionList,
  2600. &MappedSubsection->DereferenceList);
  2601. MI_UNUSED_SUBSECTIONS_COUNT_INSERT (MappedSubsection);
  2602. }
  2603. ControlArea->NumberOfMappedViews -= 1;
  2604. UNLOCK_PFN (OldIrql);
  2605. continue;
  2606. }
  2607. ASSERT (MappedSubsection->DereferenceList.Flink == NULL);
  2608. if (!NT_SUCCESS(Status)) {
  2609. MiSubsectionActions |= 0x10;
  2610. //
  2611. // If the filesystem told us it had to unroll to avoid
  2612. // deadlock OR we hit a mapped writer collision OR
  2613. // the error occurred on a local file:
  2614. //
  2615. // Then requeue this at the end so we can try again later.
  2616. //
  2617. // Any other errors for networked files are assumed to be
  2618. // permanent (ie: the link may have gone down for an indefinite
  2619. // period), so these sections are cleaned regardless.
  2620. //
  2621. MappedSubsection->NumberOfMappedViews -= 1;
  2622. InsertTailList (&MmUnusedSubsectionList,
  2623. &MappedSubsection->DereferenceList);
  2624. MI_UNUSED_SUBSECTIONS_COUNT_INSERT (MappedSubsection);
  2625. ControlArea->NumberOfMappedViews -= 1;
  2626. UNLOCK_PFN (OldIrql);
  2627. if (Status == STATUS_FILE_LOCK_CONFLICT) {
  2628. ConsecutiveFileLockFailures += 1;
  2629. }
  2630. else {
  2631. ConsecutiveFileLockFailures = 0;
  2632. }
  2633. //
  2634. // 10 consecutive file locking failures means we need to
  2635. // yield the processor to allow the filesystem to unjam.
  2636. // Nothing magic about 10, just a number so it
  2637. // gives the worker threads a chance to run.
  2638. //
  2639. if (ConsecutiveFileLockFailures >= 10) {
  2640. KeDelayExecutionThread (KernelMode, FALSE, (PLARGE_INTEGER)&MmShortTime);
  2641. ConsecutiveFileLockFailures = 0;
  2642. }
  2643. continue;
  2644. }
  2645. //
  2646. // The final check that must be made is whether any faults are
  2647. // currently in progress which are backed by this subsection.
  2648. // Note this is the perverse case where one thread in a process
  2649. // has unmapped the relevant VAD even while other threads in the
  2650. // same process are faulting on the addresses in that VAD (if the
  2651. // VAD had not been unmapped then the subsection view count would
  2652. // have been nonzero and caught above). Clearly this is a bad
  2653. // process, but nonetheless it must be detected and handled here
  2654. // because upon conclusion of the inpage, the thread will compare
  2655. // (unsynchronized) against the prototype PTEs which may in
  2656. // various stages of deletion below and would cause corruption.
  2657. //
  2658. MiSubsectionActions |= 0x20;
  2659. ASSERT (MappedSubsection->NumberOfMappedViews == 1);
  2660. ProtoPtes = MappedSubsection->SubsectionBase;
  2661. NumberOfPtes = MappedSubsection->PtesInSubsection;
  2662. //
  2663. // Note checking the prototype PTEs must be done carefully as
  2664. // they are pagable and the PFN lock is (and must be) held.
  2665. //
  2666. ProtoPtes2 = ProtoPtes;
  2667. LastProtoPte = ProtoPtes + NumberOfPtes;
  2668. while (ProtoPtes2 < LastProtoPte) {
  2669. if ((ProtoPtes2 == ProtoPtes) ||
  2670. (MiIsPteOnPdeBoundary (ProtoPtes2))) {
  2671. if (MiCheckProtoPtePageState (ProtoPtes2, TRUE, &DroppedPfnLock) == FALSE) {
  2672. //
  2673. // Skip this chunk as it is paged out and thus, cannot
  2674. // have any valid or transition PTEs within it.
  2675. //
  2676. ProtoPtes2 = (PMMPTE)(((ULONG_PTR)ProtoPtes2 | (PAGE_SIZE - 1)) + 1);
  2677. continue;
  2678. }
  2679. else {
  2680. //
  2681. // The prototype PTE page is resident right now - but
  2682. // if the PFN lock was dropped & reacquired to make it
  2683. // so, then anything could have changed - so everything
  2684. // must be rechecked.
  2685. //
  2686. if (DroppedPfnLock == TRUE) {
  2687. if ((MappedSubsection->NumberOfMappedViews != 1) ||
  2688. (MappedSubsection->u2.SubsectionFlags2.SubsectionAccessed == 1) ||
  2689. (ControlArea->u.Flags.BeingDeleted == 1)) {
  2690. MiSubsectionActions |= 0x40;
  2691. goto Requeue;
  2692. }
  2693. }
  2694. }
  2695. }
  2696. PteContents = *ProtoPtes2;
  2697. if (PteContents.u.Hard.Valid == 1) {
  2698. KeBugCheckEx (POOL_CORRUPTION_IN_FILE_AREA,
  2699. 0x3,
  2700. (ULONG_PTR)MappedSubsection,
  2701. (ULONG_PTR)ProtoPtes2,
  2702. (ULONG_PTR)PteContents.u.Long);
  2703. }
  2704. if (PteContents.u.Soft.Prototype == 1) {
  2705. MiSubsectionActions |= 0x200;
  2706. NOTHING; // This is the expected case.
  2707. }
  2708. else if (PteContents.u.Soft.Transition == 1) {
  2709. PageFrameIndex = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&PteContents);
  2710. Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);
  2711. ASSERT (Pfn1->OriginalPte.u.Soft.Prototype == 1);
  2712. if (Pfn1->u3.e1.Modified == 1) {
  2713. //
  2714. // An I/O transfer finished after the last view was
  2715. // unmapped. MmUnlockPages can set the modified bit
  2716. // in this situation so it must be handled properly
  2717. // here - ie: mark the subsection as needing to be
  2718. // reprocessed and march on.
  2719. //
  2720. MiSubsectionActions |= 0x8000000;
  2721. MappedSubsection->u2.SubsectionFlags2.SubsectionAccessed = 1;
  2722. goto Requeue;
  2723. }
  2724. if (Pfn1->u3.e2.ReferenceCount != 0) {
  2725. ASSERT (Pfn1->u4.LockCharged == 1);
  2726. //
  2727. // A fault is being satisfied for deleted address space,
  2728. // so don't eliminate this subsection right now.
  2729. //
  2730. MiSubsectionActions |= 0x400;
  2731. MappedSubsection->u2.SubsectionFlags2.SubsectionAccessed = 1;
  2732. goto Requeue;
  2733. }
  2734. MiSubsectionActions |= 0x800;
  2735. }
  2736. else {
  2737. if (PteContents.u.Long != 0) {
  2738. KeBugCheckEx (POOL_CORRUPTION_IN_FILE_AREA,
  2739. 0x4,
  2740. (ULONG_PTR)MappedSubsection,
  2741. (ULONG_PTR)ProtoPtes2,
  2742. (ULONG_PTR)PteContents.u.Long);
  2743. }
  2744. MiSubsectionActions |= 0x1000;
  2745. }
  2746. ProtoPtes2 += 1;
  2747. }
  2748. MiSubsectionActions |= 0x2000;
  2749. //
  2750. // There can be no modified pages in this subsection at this point.
  2751. // Sever the subsection's tie to the prototype PTEs while still
  2752. // holding the lock and then decrement the counts on any resident
  2753. // prototype pages.
  2754. //
  2755. ASSERT (MappedSubsection->NumberOfMappedViews == 1);
  2756. MappedSubsection->NumberOfMappedViews = 0;
  2757. MappedSubsection->SubsectionBase = NULL;
  2758. MiSubsectionActions |= 0x8000;
  2759. ProtoPtes2 = ProtoPtes;
  2760. while (ProtoPtes2 < LastProtoPte) {
  2761. if ((ProtoPtes2 == ProtoPtes) ||
  2762. (MiIsPteOnPdeBoundary (ProtoPtes2))) {
  2763. if (MiCheckProtoPtePageState (ProtoPtes2, TRUE, &DroppedPfnLock) == FALSE) {
  2764. //
  2765. // Skip this chunk as it is paged out and thus, cannot
  2766. // have any valid or transition PTEs within it.
  2767. //
  2768. ProtoPtes2 = (PMMPTE)(((ULONG_PTR)ProtoPtes2 | (PAGE_SIZE - 1)) + 1);
  2769. continue;
  2770. }
  2771. else {
  2772. //
  2773. // The prototype PTE page is resident right now - but
  2774. // if the PFN lock was dropped & reacquired to make it
  2775. // so, then anything could have changed - but notice
  2776. // that the SubsectionBase was zeroed above before
  2777. // entering this loop, so even if the PFN lock was
  2778. // dropped & reacquired, nothing needs to be rechecked.
  2779. //
  2780. }
  2781. }
  2782. PteContents = *ProtoPtes2;
  2783. ASSERT (PteContents.u.Hard.Valid == 0);
  2784. if (PteContents.u.Soft.Prototype == 1) {
  2785. MiSubsectionActions |= 0x10000;
  2786. NOTHING; // This is the expected case.
  2787. }
  2788. else if (PteContents.u.Soft.Transition == 1) {
  2789. PageFrameIndex = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&PteContents);
  2790. Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);
  2791. ASSERT (Pfn1->OriginalPte.u.Soft.Prototype == 1);
  2792. ASSERT (Pfn1->u3.e1.Modified == 0);
  2793. //
  2794. // If the page is on the standby list, move it to the
  2795. // freelist. If it's not on the standby list (ie: I/O
  2796. // is still in progress), when the Iast I/O completes, the
  2797. // page will be placed on the freelist as the PFN entry
  2798. // is always marked as deleted now.
  2799. //
  2800. ASSERT (Pfn1->u3.e2.ReferenceCount == 0);
  2801. ASSERT (Pfn1->u4.LockCharged == 0);
  2802. MI_SET_PFN_DELETED (Pfn1);
  2803. ControlArea->NumberOfPfnReferences -= 1;
  2804. ASSERT ((LONG)ControlArea->NumberOfPfnReferences >= 0);
  2805. PageTableFrameIndex = Pfn1->u4.PteFrame;
  2806. Pfn2 = MI_PFN_ELEMENT (PageTableFrameIndex);
  2807. MiDecrementShareCountInline (Pfn2, PageTableFrameIndex);
  2808. ASSERT (Pfn1->u3.e1.PageLocation != FreePageList);
  2809. MiUnlinkPageFromList (Pfn1);
  2810. MiReleasePageFileSpace (Pfn1->OriginalPte);
  2811. MiInsertPageInFreeList (PageFrameIndex);
  2812. MiSubsectionActions |= 0x20000;
  2813. }
  2814. else {
  2815. MiSubsectionActions |= 0x80000;
  2816. ASSERT (PteContents.u.Long == 0);
  2817. }
  2818. ProtoPtes2 += 1;
  2819. }
  2820. //
  2821. // If all the cached pages for this control area have been removed
  2822. // then delete it. This will actually insert the control
  2823. // area into the dereference segment header list.
  2824. //
  2825. ControlArea->NumberOfMappedViews -= 1;
  2826. #if DBG
  2827. if ((ControlArea->NumberOfPfnReferences == 0) &&
  2828. (ControlArea->NumberOfMappedViews == 0) &&
  2829. (ControlArea->NumberOfSectionReferences == 0 )) {
  2830. MiSubsectionActions |= 0x100000;
  2831. }
  2832. #endif
  2833. MiCheckForControlAreaDeletion (ControlArea);
  2834. UNLOCK_PFN (OldIrql);
  2835. ExFreePool (ProtoPtes);
  2836. ConsecutiveFileLockFailures = 0;
  2837. continue;
  2838. }
  2839. ASSERT (!IsListEmpty(&MmUnusedSegmentList));
  2840. NextEntry = RemoveHeadList(&MmUnusedSegmentList);
  2841. ControlArea = CONTAINING_RECORD (NextEntry,
  2842. CONTROL_AREA,
  2843. DereferenceList);
  2844. MI_UNUSED_SEGMENTS_REMOVE_CHARGE (ControlArea);
  2845. #if DBG
  2846. if (ControlArea->u.Flags.BeingDeleted == 0) {
  2847. if (ControlArea->u.Flags.Image) {
  2848. ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject)) != NULL);
  2849. }
  2850. else {
  2851. ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) != NULL);
  2852. }
  2853. }
  2854. #endif
  2855. //
  2856. // Set the flink to NULL indicating this control area
  2857. // is not on any lists.
  2858. //
  2859. ControlArea->DereferenceList.Flink = NULL;
  2860. if ((ControlArea->NumberOfMappedViews == 0) &&
  2861. (ControlArea->NumberOfSectionReferences == 0) &&
  2862. (ControlArea->u.Flags.BeingDeleted == 0)) {
  2863. //
  2864. // If there is paging I/O in progress on this
  2865. // segment, just put this at the tail of the list, as
  2866. // the call to MiCleanSegment would block waiting
  2867. // for the I/O to complete. As this could tie up
  2868. // the thread, don't do it. Check if these are the only
  2869. // types of segments on the dereference list so we don't
  2870. // spin forever and wedge the system.
  2871. //
  2872. if (ControlArea->ModifiedWriteCount > 0) {
  2873. MI_INSERT_UNUSED_SEGMENT (ControlArea);
  2874. UNLOCK_PFN (OldIrql);
  2875. ConsecutivePagingIOs += 1;
  2876. if (ConsecutivePagingIOs > 10) {
  2877. KeDelayExecutionThread (KernelMode, FALSE, (PLARGE_INTEGER)&MmShortTime);
  2878. ConsecutivePagingIOs = 0;
  2879. }
  2880. continue;
  2881. }
  2882. ConsecutivePagingIOs = 0;
  2883. //
  2884. // Up the number of mapped views to prevent other threads
  2885. // from freeing this. Clear the accessed bit so we'll know
  2886. // if another thread opens the control area while we're flushing
  2887. // and closes it before we finish the flush - the other thread
  2888. // may have modified some pages which can then cause our
  2889. // MiCleanSection call (which expects no modified pages in this
  2890. // case) to deadlock with the filesystem.
  2891. //
  2892. ControlArea->NumberOfMappedViews = 1;
  2893. ControlArea->u.Flags.Accessed = 0;
  2894. if (ControlArea->u.Flags.Image == 0) {
  2895. ASSERT (ControlArea->u.Flags.GlobalOnlyPerSession == 0);
  2896. if (ControlArea->u.Flags.Rom == 0) {
  2897. Subsection = (PSUBSECTION)(ControlArea + 1);
  2898. }
  2899. else {
  2900. Subsection = (PSUBSECTION)((PLARGE_CONTROL_AREA)ControlArea + 1);
  2901. }
  2902. MiSubsectionActions |= 0x200000;
  2903. while (Subsection->SubsectionBase == NULL) {
  2904. Subsection = Subsection->NextSubsection;
  2905. if (Subsection == NULL) {
  2906. MiSubsectionActions |= 0x400000;
  2907. //
  2908. // All the subsections for this segment have already
  2909. // been trimmed so nothing left to flush. Just get rid
  2910. // of the segment carcass provided no other thread
  2911. // accessed it while we weren't holding the PFN lock.
  2912. //
  2913. UNLOCK_PFN (OldIrql);
  2914. goto skip_flush;
  2915. }
  2916. else {
  2917. MiSubsectionActions |= 0x800000;
  2918. }
  2919. }
  2920. PointerPte = &Subsection->SubsectionBase[0];
  2921. LastSubsection = Subsection;
  2922. LastSubsectionWithProtos = Subsection;
  2923. while (LastSubsection->NextSubsection != NULL) {
  2924. if (LastSubsection->SubsectionBase != NULL) {
  2925. LastSubsectionWithProtos = LastSubsection;
  2926. MiSubsectionActions |= 0x1000000;
  2927. }
  2928. else {
  2929. MiSubsectionActions |= 0x2000000;
  2930. }
  2931. LastSubsection = LastSubsection->NextSubsection;
  2932. }
  2933. if (LastSubsection->SubsectionBase == NULL) {
  2934. MiSubsectionActions |= 0x4000000;
  2935. LastSubsection = LastSubsectionWithProtos;
  2936. }
  2937. UNLOCK_PFN (OldIrql);
  2938. LastPte = &LastSubsection->SubsectionBase
  2939. [LastSubsection->PtesInSubsection - 1];
  2940. //
  2941. // Preacquire the file to prevent deadlocks with other flushers
  2942. // Also mark ourself as a top level IRP so the filesystem knows
  2943. // we are holding no other resources and that it can unroll if
  2944. // it needs to in order to avoid deadlock. Don't hold this
  2945. // protection any longer than we need to.
  2946. //
  2947. Status = FsRtlAcquireFileForCcFlushEx (ControlArea->FilePointer);
  2948. if (NT_SUCCESS(Status)) {
  2949. IoSetTopLevelIrp ((PIRP)FSRTL_FSP_TOP_LEVEL_IRP);
  2950. Status = MiFlushSectionInternal (PointerPte,
  2951. LastPte,
  2952. Subsection,
  2953. LastSubsection,
  2954. FALSE,
  2955. FALSE,
  2956. &IoStatus);
  2957. IoSetTopLevelIrp (NULL);
  2958. //
  2959. // Now release the file.
  2960. //
  2961. FsRtlReleaseFileForCcFlush (ControlArea->FilePointer);
  2962. }
  2963. skip_flush:
  2964. LOCK_PFN (OldIrql);
  2965. }
  2966. //
  2967. // Before checking for any failure codes, see if any other
  2968. // threads accessed the control area while the flush was ongoing.
  2969. //
  2970. // Note that beyond the case of another thread currently using
  2971. // the control area, the more subtle one is where another
  2972. // thread accessed the control area and modified some pages.
  2973. // The flush needs to redone (so the clean is guaranteed to work)
  2974. // before another clean can be issued.
  2975. //
  2976. // If any of these cases have occurred, grant this control area
  2977. // a reprieve.
  2978. //
  2979. if (!((ControlArea->NumberOfMappedViews == 1) &&
  2980. (ControlArea->u.Flags.Accessed == 0) &&
  2981. (ControlArea->NumberOfSectionReferences == 0) &&
  2982. (ControlArea->u.Flags.BeingDeleted == 0))) {
  2983. ControlArea->NumberOfMappedViews -= 1;
  2984. //
  2985. // If the other thread(s) are done with this control area,
  2986. // it MUST be requeued here - otherwise if there are any
  2987. // pages in the control area, when they are reclaimed,
  2988. // MiCheckForControlAreaDeletion checks for and expects
  2989. // the control area to be queued on the unused segment list.
  2990. //
  2991. // Note this must be done very carefully because if the other
  2992. // threads are not done with the control area, it had better
  2993. // not get put on the unused segment list.
  2994. //
  2995. //
  2996. // Need to do the equivalent of a MiCheckControlArea here.
  2997. // or reprocess. Only iff mappedview & sectref = 0.
  2998. //
  2999. if ((ControlArea->NumberOfMappedViews == 0) &&
  3000. (ControlArea->NumberOfSectionReferences == 0) &&
  3001. (ControlArea->u.Flags.BeingDeleted == 0)) {
  3002. ASSERT (ControlArea->u.Flags.Accessed == 1);
  3003. ASSERT(ControlArea->DereferenceList.Flink == NULL);
  3004. MI_INSERT_UNUSED_SEGMENT (ControlArea);
  3005. }
  3006. UNLOCK_PFN (OldIrql);
  3007. continue;
  3008. }
  3009. if (!NT_SUCCESS(Status)) {
  3010. //
  3011. // If the filesystem told us it had to unroll to avoid
  3012. // deadlock OR we hit a mapped writer collision OR
  3013. // the error occurred on a local file:
  3014. //
  3015. // Then requeue this at the end so we can try again later.
  3016. //
  3017. // Any other errors for networked files are assumed to be
  3018. // permanent (ie: the link may have gone down for an indefinite
  3019. // period), so these sections are cleaned regardless.
  3020. //
  3021. if ((Status == STATUS_FILE_LOCK_CONFLICT) ||
  3022. (Status == STATUS_MAPPED_WRITER_COLLISION) ||
  3023. (ControlArea->u.Flags.Networked == 0)) {
  3024. ASSERT(ControlArea->DereferenceList.Flink == NULL);
  3025. ControlArea->NumberOfMappedViews -= 1;
  3026. MI_INSERT_UNUSED_SEGMENT (ControlArea);
  3027. UNLOCK_PFN (OldIrql);
  3028. if (Status == STATUS_FILE_LOCK_CONFLICT) {
  3029. ConsecutiveFileLockFailures += 1;
  3030. }
  3031. else {
  3032. ConsecutiveFileLockFailures = 0;
  3033. }
  3034. //
  3035. // 10 consecutive file locking failures means we need to
  3036. // yield the processor to allow the filesystem to unjam.
  3037. // Nothing magic about 10, just a number so it
  3038. // gives the worker threads a chance to run.
  3039. //
  3040. if (ConsecutiveFileLockFailures >= 10) {
  3041. KeDelayExecutionThread (KernelMode, FALSE, (PLARGE_INTEGER)&MmShortTime);
  3042. ConsecutiveFileLockFailures = 0;
  3043. }
  3044. continue;
  3045. }
  3046. DirtyPagesOk = TRUE;
  3047. }
  3048. else {
  3049. ConsecutiveFileLockFailures = 0;
  3050. DirtyPagesOk = FALSE;
  3051. }
  3052. ControlArea->u.Flags.BeingDeleted = 1;
  3053. //
  3054. // Don't let any pages be written by the modified
  3055. // page writer from this point on.
  3056. //
  3057. ControlArea->u.Flags.NoModifiedWriting = 1;
  3058. ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
  3059. UNLOCK_PFN (OldIrql);
  3060. MiCleanSection (ControlArea, DirtyPagesOk);
  3061. }
  3062. else {
  3063. //
  3064. // The segment was not eligible for deletion. Just leave
  3065. // it off the unused segment list and continue the loop.
  3066. //
  3067. UNLOCK_PFN (OldIrql);
  3068. ConsecutivePagingIOs = 0;
  3069. }
  3070. }
  3071. }