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.

2997 lines
86 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. allocvm.c
  5. Abstract:
  6. This module contains the routines which implement the
  7. NtAllocateVirtualMemory service.
  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. #if DBG
  15. PEPROCESS MmWatchProcess;
  16. VOID MmFooBar(VOID);
  17. #endif // DBG
  18. const ULONG MMVADKEY = ' daV'; //Vad
  19. //
  20. // This registry-settable variable provides a way to give all applications
  21. // virtual address ranges from the highest address downwards. The idea is to
  22. // make it easy to test 3GB-aware apps on 32-bit machines and 64-bit apps on
  23. // NT64.
  24. //
  25. ULONG MmAllocationPreference;
  26. NTSTATUS
  27. MiResetVirtualMemory (
  28. IN PVOID StartingAddress,
  29. IN PVOID EndingAddress,
  30. IN PMMVAD Vad,
  31. IN PEPROCESS Process
  32. );
  33. LOGICAL
  34. MiCreatePageTablesForPhysicalRange (
  35. IN PEPROCESS Process,
  36. IN PVOID StartingAddress,
  37. IN PVOID EndingAddress
  38. );
  39. VOID
  40. MiPhysicalViewInserter (
  41. IN PEPROCESS Process,
  42. IN PMI_PHYSICAL_VIEW PhysicalView
  43. );
  44. VOID
  45. MiFlushAcquire (
  46. IN PCONTROL_AREA ControlArea
  47. );
  48. VOID
  49. MiFlushRelease (
  50. IN PCONTROL_AREA ControlArea
  51. );
  52. #ifdef ALLOC_PRAGMA
  53. #pragma alloc_text(PAGE,NtAllocateVirtualMemory)
  54. #pragma alloc_text(PAGELK,MiCreatePageTablesForPhysicalRange)
  55. #pragma alloc_text(PAGELK,MiDeletePageTablesForPhysicalRange)
  56. #pragma alloc_text(PAGELK,MiResetVirtualMemory)
  57. #endif
  58. SIZE_T MmTotalProcessCommit; // Only used for debugging
  59. NTSTATUS
  60. NtAllocateVirtualMemory(
  61. IN HANDLE ProcessHandle,
  62. IN OUT PVOID *BaseAddress,
  63. IN ULONG_PTR ZeroBits,
  64. IN OUT PSIZE_T RegionSize,
  65. IN ULONG AllocationType,
  66. IN ULONG Protect
  67. )
  68. /*++
  69. Routine Description:
  70. This function creates a region of pages within the virtual address
  71. space of a subject process.
  72. Arguments:
  73. ProcessHandle - Supplies an open handle to a process object.
  74. BaseAddress - Supplies a pointer to a variable that will receive
  75. the base address of the allocated region of pages.
  76. If the initial value of this argument is not null,
  77. then the region will be allocated starting at the
  78. specified virtual address rounded down to the next
  79. host page size address boundary. If the initial
  80. value of this argument is null, then the operating
  81. system will determine where to allocate the region.
  82. ZeroBits - Supplies the number of high order address bits that
  83. must be zero in the base address of the section view. The
  84. value of this argument must be less than or equal to the
  85. maximum number of zero bits and is only used when memory
  86. management determines where to allocate the view (i.e. when
  87. BaseAddress is null).
  88. If ZeroBits is zero, then no zero bit constraints are applied.
  89. If ZeroBits is greater than 0 and less than 32, then it is
  90. the number of leading zero bits from bit 31. Bits 63:32 are
  91. also required to be zero. This retains compatibility
  92. with 32-bit systems.
  93. If ZeroBits is greater than 32, then it is considered as
  94. a mask and then number of leading zero are counted out
  95. in the mask. This then becomes the zero bits argument.
  96. RegionSize - Supplies a pointer to a variable that will receive
  97. the actual size in bytes of the allocated region
  98. of pages. The initial value of this argument
  99. specifies the size in bytes of the region and is
  100. rounded up to the next host page size boundary.
  101. AllocationType - Supplies a set of flags that describe the type
  102. of allocation that is to be performed for the
  103. specified region of pages. Flags are:
  104. MEM_COMMIT - The specified region of pages is to be committed.
  105. MEM_RESERVE - The specified region of pages is to be reserved.
  106. MEM_TOP_DOWN - The specified region should be created at the
  107. highest virtual address possible based on ZeroBits.
  108. MEM_RESET - Reset the state of the specified region so
  109. that if the pages are in page paging file, they
  110. are discarded and pages of zeroes are brought in.
  111. If the pages are in memory and modified, they are marked
  112. as not modified so they will not be written out to
  113. the paging file. The contents are NOT zeroed.
  114. The Protect argument is ignored, but a valid protection
  115. must be specified.
  116. MEM_PHYSICAL - The specified region of pages will map physical memory
  117. directly via the AWE APIs.
  118. MEM_WRITE_WATCH - The specified private region is to be used for
  119. write-watch purposes.
  120. Protect - Supplies the protection desired for the committed region of pages.
  121. PAGE_NOACCESS - No access to the committed region
  122. of pages is allowed. An attempt to read,
  123. write, or execute the committed region
  124. results in an access violation.
  125. PAGE_EXECUTE - Execute access to the committed
  126. region of pages is allowed. An attempt to
  127. read or write the committed region results in
  128. an access violation.
  129. PAGE_READONLY - Read only and execute access to the
  130. committed region of pages is allowed. An
  131. attempt to write the committed region results
  132. in an access violation.
  133. PAGE_READWRITE - Read, write, and execute access to
  134. the committed region of pages is allowed. If
  135. write access to the underlying section is
  136. allowed, then a single copy of the pages are
  137. shared. Otherwise the pages are shared read
  138. only/copy on write.
  139. PAGE_NOCACHE - The region of pages should be allocated
  140. as non-cachable.
  141. Return Value:
  142. Various NTSTATUS codes.
  143. --*/
  144. {
  145. ULONG Locked;
  146. PMMVAD Vad;
  147. PMMVAD FoundVad;
  148. PMMVAD PreviousVad;
  149. PMMVAD NextVad;
  150. PEPROCESS Process;
  151. KPROCESSOR_MODE PreviousMode;
  152. PVOID StartingAddress;
  153. PVOID EndingAddress;
  154. NTSTATUS Status;
  155. PVOID TopAddress;
  156. PVOID CapturedBase;
  157. SIZE_T CapturedRegionSize;
  158. SIZE_T NumberOfPages;
  159. PMMPTE PointerPte;
  160. PMMPTE CommitLimitPte;
  161. ULONG ProtectionMask;
  162. PMMPTE LastPte;
  163. PMMPTE PointerPde;
  164. PMMPTE StartingPte;
  165. MMPTE TempPte;
  166. ULONG OldProtect;
  167. SIZE_T QuotaCharge;
  168. SIZE_T QuotaFree;
  169. SIZE_T CopyOnWriteCharge;
  170. LOGICAL Attached;
  171. LOGICAL ChargedExactQuota;
  172. MMPTE DecommittedPte;
  173. ULONG ChangeProtection;
  174. PVOID UsedPageTableHandle;
  175. PUCHAR Va;
  176. LOGICAL ChargedJobCommit;
  177. PMI_PHYSICAL_VIEW PhysicalView;
  178. PRTL_BITMAP BitMap;
  179. ULONG BitMapSize;
  180. ULONG BitMapBits;
  181. KAPC_STATE ApcState;
  182. SECTION Section;
  183. LARGE_INTEGER NewSize;
  184. PCONTROL_AREA ControlArea;
  185. PSEGMENT Segment;
  186. #if defined(_MIALT4K_)
  187. PVOID OriginalBase;
  188. SIZE_T OriginalRegionSize;
  189. PVOID WowProcess;
  190. PVOID StartingAddressFor4k;
  191. PVOID EndingAddressFor4k;
  192. SIZE_T CapturedRegionSizeFor4k;
  193. ULONG OriginalProtectionMask;
  194. ULONG AltFlags;
  195. ULONG NativePageProtection;
  196. #endif
  197. PETHREAD CurrentThread;
  198. PEPROCESS CurrentProcess;
  199. ULONG ExecutePermission;
  200. PAGED_CODE();
  201. Attached = FALSE;
  202. //
  203. // Check the zero bits argument for correctness.
  204. //
  205. #if defined (_WIN64)
  206. if (ZeroBits >= 32) {
  207. //
  208. // ZeroBits is a mask instead of a count. Translate it to a count now.
  209. //
  210. ZeroBits = 64 - RtlFindMostSignificantBit (ZeroBits) -1;
  211. }
  212. else if (ZeroBits) {
  213. ZeroBits += 32;
  214. }
  215. #endif
  216. if (ZeroBits > MM_MAXIMUM_ZERO_BITS) {
  217. return STATUS_INVALID_PARAMETER_3;
  218. }
  219. //
  220. // Check the AllocationType for correctness.
  221. //
  222. if ((AllocationType & ~(MEM_COMMIT | MEM_RESERVE | MEM_PHYSICAL |
  223. MEM_TOP_DOWN | MEM_RESET | MEM_WRITE_WATCH)) != 0) {
  224. return STATUS_INVALID_PARAMETER_5;
  225. }
  226. //
  227. // One of MEM_COMMIT, MEM_RESET or MEM_RESERVE must be set.
  228. //
  229. if ((AllocationType & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)) == 0) {
  230. return STATUS_INVALID_PARAMETER_5;
  231. }
  232. if ((AllocationType & MEM_RESET) && (AllocationType != MEM_RESET)) {
  233. //
  234. // MEM_RESET may not be used with any other flag.
  235. //
  236. return STATUS_INVALID_PARAMETER_5;
  237. }
  238. if (AllocationType & MEM_WRITE_WATCH) {
  239. //
  240. // Write watch address spaces can only be created with MEM_RESERVE.
  241. //
  242. if ((AllocationType & MEM_RESERVE) == 0) {
  243. return STATUS_INVALID_PARAMETER_5;
  244. }
  245. }
  246. if (AllocationType & MEM_PHYSICAL) {
  247. //
  248. // MEM_PHYSICAL must be used with MEM_RESERVE and no other flags.
  249. // This memory is always read-write when allocated.
  250. //
  251. if (AllocationType != (MEM_RESERVE | MEM_PHYSICAL)) {
  252. return STATUS_INVALID_PARAMETER_5;
  253. }
  254. if (Protect != PAGE_READWRITE) {
  255. return STATUS_INVALID_PARAMETER_6;
  256. }
  257. }
  258. //
  259. // Check the protection field.
  260. //
  261. ProtectionMask = MiMakeProtectionMask (Protect);
  262. if (ProtectionMask == MM_INVALID_PROTECTION) {
  263. return STATUS_INVALID_PAGE_PROTECTION;
  264. }
  265. ChangeProtection = FALSE;
  266. CurrentThread = PsGetCurrentThread ();
  267. CurrentProcess = PsGetCurrentProcessByThread (CurrentThread);
  268. PreviousMode = KeGetPreviousModeByThread(&CurrentThread->Tcb);
  269. //
  270. // Establish an exception handler, probe the specified addresses
  271. // for write access and capture the initial values.
  272. //
  273. try {
  274. if (PreviousMode != KernelMode) {
  275. ProbeForWritePointer (BaseAddress);
  276. ProbeForWriteUlong_ptr (RegionSize);
  277. }
  278. //
  279. // Capture the base address.
  280. //
  281. CapturedBase = *BaseAddress;
  282. //
  283. // Capture the region size.
  284. //
  285. CapturedRegionSize = *RegionSize;
  286. } except (ExSystemExceptionFilter()) {
  287. //
  288. // If an exception occurs during the probe or capture
  289. // of the initial values, then handle the exception and
  290. // return the exception code as the status value.
  291. //
  292. return GetExceptionCode();
  293. }
  294. #if defined(_MIALT4K_)
  295. OriginalBase = CapturedBase;
  296. OriginalRegionSize = CapturedRegionSize;
  297. #endif
  298. //
  299. // Make sure the specified starting and ending addresses are
  300. // within the user part of the virtual address space.
  301. //
  302. if (CapturedBase > MM_HIGHEST_VAD_ADDRESS) {
  303. //
  304. // Invalid base address.
  305. //
  306. return STATUS_INVALID_PARAMETER_2;
  307. }
  308. if ((((ULONG_PTR)MM_HIGHEST_VAD_ADDRESS + 1) - (ULONG_PTR)CapturedBase) <
  309. CapturedRegionSize) {
  310. //
  311. // Invalid region size;
  312. //
  313. return STATUS_INVALID_PARAMETER_4;
  314. }
  315. if (CapturedRegionSize == 0) {
  316. //
  317. // Region size cannot be 0.
  318. //
  319. return STATUS_INVALID_PARAMETER_4;
  320. }
  321. //
  322. // Reference the specified process handle for VM_OPERATION access.
  323. //
  324. if (ProcessHandle == NtCurrentProcess()) {
  325. Process = CurrentProcess;
  326. }
  327. else {
  328. Status = ObReferenceObjectByHandle ( ProcessHandle,
  329. PROCESS_VM_OPERATION,
  330. PsProcessType,
  331. PreviousMode,
  332. (PVOID *)&Process,
  333. NULL );
  334. if (!NT_SUCCESS(Status)) {
  335. return Status;
  336. }
  337. //
  338. // If the specified process is not the current process, attach
  339. // to the specified process.
  340. //
  341. if (CurrentProcess != Process) {
  342. KeStackAttachProcess (&Process->Pcb, &ApcState);
  343. Attached = TRUE;
  344. }
  345. }
  346. //
  347. // Add execute permission if necessary.
  348. //
  349. #if defined (_WIN64)
  350. if (Process->Wow64Process == NULL && AllocationType & MEM_COMMIT)
  351. #elif defined (_X86PAE_)
  352. if (AllocationType & MEM_COMMIT)
  353. #else
  354. if (FALSE)
  355. #endif
  356. {
  357. if (Process->Peb != NULL) {
  358. ExecutePermission = 0;
  359. try {
  360. ExecutePermission = Process->Peb->ExecuteOptions & MEM_EXECUTE_OPTION_DATA;
  361. } except (EXCEPTION_EXECUTE_HANDLER) {
  362. Status = GetExceptionCode();
  363. goto ErrorReturn1;
  364. }
  365. if (ExecutePermission != 0) {
  366. switch (Protect & 0xF) {
  367. case PAGE_READONLY:
  368. Protect &= ~PAGE_READONLY;
  369. Protect |= PAGE_EXECUTE_READ;
  370. break;
  371. case PAGE_READWRITE:
  372. Protect &= ~PAGE_READWRITE;
  373. Protect |= PAGE_EXECUTE_READWRITE;
  374. break;
  375. case PAGE_WRITECOPY:
  376. Protect &= ~PAGE_WRITECOPY;
  377. Protect |= PAGE_EXECUTE_WRITECOPY;
  378. break;
  379. default:
  380. break;
  381. }
  382. //
  383. // Recheck protection.
  384. //
  385. ProtectionMask = MiMakeProtectionMask (Protect);
  386. if (ProtectionMask == MM_INVALID_PROTECTION) {
  387. Status = STATUS_INVALID_PAGE_PROTECTION;
  388. goto ErrorReturn1;
  389. }
  390. }
  391. }
  392. }
  393. //
  394. // Get the address creation mutex to block multiple threads from
  395. // creating or deleting address space at the same time and
  396. // get the working set mutex so virtual address descriptors can
  397. // be inserted and walked. Block APCs so an APC which takes a page
  398. // fault does not corrupt various structures.
  399. //
  400. QuotaCharge = 0;
  401. if ((CapturedBase == NULL) || (AllocationType & MEM_RESERVE)) {
  402. //
  403. // PAGE_WRITECOPY is not valid for private pages.
  404. //
  405. if ((Protect & PAGE_WRITECOPY) ||
  406. (Protect & PAGE_EXECUTE_WRITECOPY)) {
  407. Status = STATUS_INVALID_PAGE_PROTECTION;
  408. goto ErrorReturn1;
  409. }
  410. //
  411. // Reserve the address space.
  412. //
  413. if (CapturedBase == NULL) {
  414. //
  415. // No base address was specified. This MUST be a reserve or
  416. // reserve and commit.
  417. //
  418. CapturedRegionSize = ROUND_TO_PAGES (CapturedRegionSize);
  419. //
  420. // If the number of zero bits is greater than zero, then calculate
  421. // the highest address.
  422. //
  423. if (ZeroBits != 0) {
  424. TopAddress = (PVOID)(((ULONG_PTR)MM_USER_ADDRESS_RANGE_LIMIT) >> ZeroBits);
  425. //
  426. // Keep the top address below the highest user vad address
  427. // regardless.
  428. //
  429. if (TopAddress > MM_HIGHEST_VAD_ADDRESS) {
  430. Status = STATUS_INVALID_PARAMETER_3;
  431. goto ErrorReturn1;
  432. }
  433. }
  434. else {
  435. TopAddress = (PVOID)MM_HIGHEST_VAD_ADDRESS;
  436. }
  437. //
  438. // Check whether the registry indicates that all applications
  439. // should be given virtual address ranges from the highest
  440. // address downwards in order to test 3GB-aware apps on 32-bit
  441. // machines and 64-bit apps on NT64.
  442. //
  443. ASSERT ((MmAllocationPreference == 0) ||
  444. (MmAllocationPreference == MEM_TOP_DOWN));
  445. #if defined (_WIN64)
  446. if (Process->Wow64Process == NULL)
  447. #endif
  448. AllocationType |= MmAllocationPreference;
  449. //
  450. // Note this calculation assumes the starting address will be
  451. // allocated on at least a page boundary.
  452. //
  453. NumberOfPages = BYTES_TO_PAGES (CapturedRegionSize);
  454. //
  455. // Initializing StartingAddress and EndingAddress is not needed for
  456. // correctness but without it the compiler cannot compile this code
  457. // W4 to check for use of uninitialized variables.
  458. //
  459. StartingAddress = NULL;
  460. EndingAddress = NULL;
  461. }
  462. else {
  463. //
  464. // A non-NULL base address was specified. Check to make sure
  465. // the specified base address to ending address is currently
  466. // unused.
  467. //
  468. EndingAddress = (PVOID)(((ULONG_PTR)CapturedBase +
  469. CapturedRegionSize - 1L) | (PAGE_SIZE - 1L));
  470. //
  471. // Align the starting address on a 64k boundary.
  472. //
  473. StartingAddress = (PVOID)MI_64K_ALIGN(CapturedBase);
  474. NumberOfPages = BYTES_TO_PAGES ((PCHAR)EndingAddress -
  475. (PCHAR)StartingAddress);
  476. //
  477. // Initializing TopAddress is not needed for
  478. // correctness but without it the compiler cannot compile this code
  479. // W4 to check for use of uninitialized variables.
  480. //
  481. TopAddress = NULL;
  482. }
  483. BitMapSize = 0;
  484. //
  485. // Allocate resources up front before acquiring mutexes to reduce
  486. // contention.
  487. //
  488. Vad = ExAllocatePoolWithTag (NonPagedPool, sizeof(MMVAD_SHORT), 'SdaV');
  489. if (Vad == NULL) {
  490. Status = STATUS_INSUFFICIENT_RESOURCES;
  491. goto ErrorReturn1;
  492. }
  493. Vad->u.LongFlags = 0;
  494. //
  495. // Calculate the page file quota for this address range.
  496. //
  497. if (AllocationType & MEM_COMMIT) {
  498. QuotaCharge = NumberOfPages;
  499. Vad->u.VadFlags.MemCommit = 1;
  500. }
  501. if (AllocationType & MEM_PHYSICAL) {
  502. Vad->u.VadFlags.UserPhysicalPages = 1;
  503. }
  504. Vad->u.VadFlags.Protection = ProtectionMask;
  505. Vad->u.VadFlags.PrivateMemory = 1;
  506. Vad->u.VadFlags.CommitCharge = QuotaCharge;
  507. //
  508. // Initializing BitMap & PhysicalView is not needed for
  509. // correctness but without it the compiler cannot compile this code
  510. // W4 to check for use of uninitialized variables.
  511. //
  512. BitMap = NULL;
  513. PhysicalView = NULL;
  514. if (AllocationType & MEM_PHYSICAL) {
  515. if (AllocationType & MEM_WRITE_WATCH) {
  516. ExFreePool (Vad);
  517. Status = STATUS_INVALID_PARAMETER_5;
  518. goto ErrorReturn1;
  519. }
  520. if ((Process->AweInfo == NULL) && (MiAllocateAweInfo () == NULL)) {
  521. ExFreePool (Vad);
  522. Status = STATUS_INSUFFICIENT_RESOURCES;
  523. goto ErrorReturn1;
  524. }
  525. PhysicalView = (PMI_PHYSICAL_VIEW) ExAllocatePoolWithTag (
  526. NonPagedPool,
  527. sizeof(MI_PHYSICAL_VIEW),
  528. MI_PHYSICAL_VIEW_KEY);
  529. if (PhysicalView == NULL) {
  530. ExFreePool (Vad);
  531. Status = STATUS_INSUFFICIENT_RESOURCES;
  532. goto ErrorReturn1;
  533. }
  534. PhysicalView->Vad = Vad;
  535. PhysicalView->u.LongFlags = MI_PHYSICAL_VIEW_AWE;
  536. }
  537. else if (AllocationType & MEM_WRITE_WATCH) {
  538. ASSERT (AllocationType & MEM_RESERVE);
  539. #if defined (_WIN64)
  540. if (NumberOfPages >= _4gb) {
  541. //
  542. // The bitmap package only handles 32 bits.
  543. //
  544. ExFreePool (Vad);
  545. Status = STATUS_INSUFFICIENT_RESOURCES;
  546. goto ErrorReturn1;
  547. }
  548. #endif
  549. BitMapBits = (ULONG)NumberOfPages;
  550. BitMapSize = sizeof(RTL_BITMAP) + (ULONG)(((BitMapBits + 31) / 32) * 4);
  551. BitMap = ExAllocatePoolWithTag (NonPagedPool, BitMapSize, 'wwmM');
  552. if (BitMap == NULL) {
  553. ExFreePool (Vad);
  554. Status = STATUS_INSUFFICIENT_RESOURCES;
  555. goto ErrorReturn1;
  556. }
  557. //
  558. // Charge quota for the nonpaged pool for the bitmap. This is
  559. // done here rather than by using ExAllocatePoolWithQuota
  560. // so the process object is not referenced by the quota charge.
  561. //
  562. Status = PsChargeProcessNonPagedPoolQuota (Process,
  563. BitMapSize);
  564. if (!NT_SUCCESS(Status)) {
  565. ExFreePool (Vad);
  566. ExFreePool (BitMap);
  567. goto ErrorReturn1;
  568. }
  569. PhysicalView = (PMI_PHYSICAL_VIEW) ExAllocatePoolWithTag (
  570. NonPagedPool,
  571. sizeof(MI_PHYSICAL_VIEW),
  572. MI_WRITEWATCH_VIEW_KEY);
  573. if (PhysicalView == NULL) {
  574. ExFreePool (Vad);
  575. ExFreePool (BitMap);
  576. PsReturnProcessNonPagedPoolQuota (Process, BitMapSize);
  577. Status = STATUS_INSUFFICIENT_RESOURCES;
  578. goto ErrorReturn1;
  579. }
  580. RtlInitializeBitMap (BitMap, (PULONG)(BitMap + 1), BitMapBits);
  581. RtlClearAllBits (BitMap);
  582. PhysicalView->Vad = Vad;
  583. PhysicalView->u.BitMap = BitMap;
  584. Vad->u.VadFlags.WriteWatch = 1;
  585. }
  586. //
  587. // Now acquire mutexes, check ranges and insert.
  588. //
  589. LOCK_ADDRESS_SPACE (Process);
  590. //
  591. // Make sure the address space was not deleted, if so,
  592. // return an error.
  593. //
  594. if (Process->Flags & PS_PROCESS_FLAGS_VM_DELETED) {
  595. Status = STATUS_PROCESS_IS_TERMINATING;
  596. goto ErrorReleaseVad;
  597. }
  598. //
  599. // Find a (or validate the) starting address.
  600. //
  601. if (CapturedBase == NULL) {
  602. if (AllocationType & MEM_TOP_DOWN) {
  603. //
  604. // Start from the top of memory downward.
  605. //
  606. Status = MiFindEmptyAddressRangeDown (Process->VadRoot,
  607. CapturedRegionSize,
  608. TopAddress,
  609. X64K,
  610. &StartingAddress);
  611. }
  612. else {
  613. Status = MiFindEmptyAddressRange (CapturedRegionSize,
  614. X64K,
  615. (ULONG)ZeroBits,
  616. &StartingAddress);
  617. }
  618. if (!NT_SUCCESS (Status)) {
  619. goto ErrorReleaseVad;
  620. }
  621. //
  622. // Calculate the ending address based on the top address.
  623. //
  624. EndingAddress = (PVOID)(((ULONG_PTR)StartingAddress +
  625. CapturedRegionSize - 1L) | (PAGE_SIZE - 1L));
  626. if (EndingAddress > TopAddress) {
  627. //
  628. // The allocation does not honor the zero bits argument.
  629. //
  630. Status = STATUS_NO_MEMORY;
  631. goto ErrorReleaseVad;
  632. }
  633. }
  634. else {
  635. //
  636. // See if a VAD overlaps with this starting/ending address pair.
  637. //
  638. if (MiCheckForConflictingVadExistence (Process, StartingAddress, EndingAddress) == TRUE) {
  639. Status = STATUS_CONFLICTING_ADDRESSES;
  640. goto ErrorReleaseVad;
  641. }
  642. }
  643. //
  644. // An unoccupied address range has been found, finish initializing
  645. // the virtual address descriptor to describe this range, then
  646. // insert it into the tree.
  647. //
  648. Vad->StartingVpn = MI_VA_TO_VPN (StartingAddress);
  649. Vad->EndingVpn = MI_VA_TO_VPN (EndingAddress);
  650. LOCK_WS_UNSAFE (Process);
  651. Status = MiInsertVad (Vad);
  652. if (!NT_SUCCESS(Status)) {
  653. UNLOCK_WS_UNSAFE (Process);
  654. ErrorReleaseVad:
  655. //
  656. // The quota charge in InsertVad failed, deallocate the pool
  657. // and return an error.
  658. //
  659. UNLOCK_ADDRESS_SPACE (Process);
  660. ExFreePool (Vad);
  661. if (AllocationType & MEM_PHYSICAL) {
  662. ExFreePool (PhysicalView);
  663. }
  664. else if (BitMapSize != 0) {
  665. ExFreePool (PhysicalView);
  666. ExFreePool (BitMap);
  667. PsReturnProcessNonPagedPoolQuota (Process, BitMapSize);
  668. }
  669. goto ErrorReturn1;
  670. }
  671. //
  672. // Initialize page directory and table pages for the physical range.
  673. //
  674. if (AllocationType & MEM_PHYSICAL) {
  675. if (MiCreatePageTablesForPhysicalRange (Process,
  676. StartingAddress,
  677. EndingAddress) == FALSE) {
  678. PreviousVad = MiGetPreviousVad (Vad);
  679. NextVad = MiGetNextVad (Vad);
  680. MiRemoveVad (Vad);
  681. //
  682. // Return commitment for page table pages if possible.
  683. //
  684. MiReturnPageTablePageCommitment (StartingAddress,
  685. EndingAddress,
  686. Process,
  687. PreviousVad,
  688. NextVad);
  689. UNLOCK_WS_AND_ADDRESS_SPACE (Process);
  690. ExFreePool (Vad);
  691. ExFreePool (PhysicalView);
  692. Status = STATUS_INSUFFICIENT_RESOURCES;
  693. goto ErrorReturn1;
  694. }
  695. PhysicalView->StartVa = StartingAddress;
  696. PhysicalView->EndVa = EndingAddress;
  697. //
  698. // Insert the physical view into this process' list using a
  699. // nonpaged wrapper since the PFN lock is required.
  700. //
  701. ASSERT (PhysicalView->u.LongFlags == MI_PHYSICAL_VIEW_AWE);
  702. MiAweViewInserter (Process, PhysicalView);
  703. }
  704. else if (BitMapSize != 0) {
  705. PhysicalView->StartVa = StartingAddress;
  706. PhysicalView->EndVa = EndingAddress;
  707. MiPhysicalViewInserter (Process, PhysicalView);
  708. }
  709. //
  710. // Unlock the working set lock, page faults can now be taken.
  711. //
  712. UNLOCK_WS_UNSAFE (Process);
  713. //
  714. // Update the current virtual size in the process header, the
  715. // address space lock protects this operation.
  716. //
  717. CapturedRegionSize = (PCHAR)EndingAddress - (PCHAR)StartingAddress + 1L;
  718. Process->VirtualSize += CapturedRegionSize;
  719. if (Process->VirtualSize > Process->PeakVirtualSize) {
  720. Process->PeakVirtualSize = Process->VirtualSize;
  721. }
  722. #if defined(_MIALT4K_)
  723. if (Process->Wow64Process != NULL) {
  724. if (OriginalBase == NULL) {
  725. OriginalRegionSize = ROUND_TO_4K_PAGES(OriginalRegionSize);
  726. EndingAddress = (PVOID)(((ULONG_PTR) StartingAddress +
  727. OriginalRegionSize - 1L) | (PAGE_4K - 1L));
  728. }
  729. else {
  730. EndingAddress = (PVOID)(((ULONG_PTR)OriginalBase +
  731. OriginalRegionSize - 1L) | (PAGE_4K - 1L));
  732. }
  733. CapturedRegionSize = (PCHAR)EndingAddress - (PCHAR)StartingAddress + 1L;
  734. //
  735. // Set the alternate permission table
  736. //
  737. AltFlags = (AllocationType & MEM_COMMIT) ? ALT_COMMIT : 0;
  738. MiProtectFor4kPage (StartingAddress,
  739. CapturedRegionSize,
  740. ProtectionMask,
  741. ALT_ALLOCATE|AltFlags,
  742. Process);
  743. }
  744. #endif
  745. //
  746. // Release the address space lock, lower IRQL, detach, and dereference
  747. // the process object.
  748. //
  749. UNLOCK_ADDRESS_SPACE(Process);
  750. if (Attached == TRUE) {
  751. KeUnstackDetachProcess (&ApcState);
  752. }
  753. if (ProcessHandle != NtCurrentProcess()) {
  754. ObDereferenceObject (Process);
  755. }
  756. //
  757. // Establish an exception handler and write the size and base
  758. // address.
  759. //
  760. try {
  761. *RegionSize = CapturedRegionSize;
  762. *BaseAddress = StartingAddress;
  763. } except (EXCEPTION_EXECUTE_HANDLER) {
  764. //
  765. // Return success at this point even if the results
  766. // cannot be written.
  767. //
  768. NOTHING;
  769. }
  770. return STATUS_SUCCESS;
  771. }
  772. //
  773. // Commit previously reserved pages. Note that these pages could
  774. // be either private or a section.
  775. //
  776. if (AllocationType == MEM_RESET) {
  777. //
  778. // Round up to page boundaries so good data is not reset.
  779. //
  780. EndingAddress = (PVOID)((ULONG_PTR)PAGE_ALIGN ((ULONG_PTR)CapturedBase +
  781. CapturedRegionSize) - 1);
  782. StartingAddress = (PVOID)PAGE_ALIGN((PUCHAR)CapturedBase + PAGE_SIZE - 1);
  783. if (StartingAddress > EndingAddress) {
  784. Status = STATUS_CONFLICTING_ADDRESSES;
  785. goto ErrorReturn1;
  786. }
  787. }
  788. else {
  789. EndingAddress = (PVOID)(((ULONG_PTR)CapturedBase +
  790. CapturedRegionSize - 1) | (PAGE_SIZE - 1));
  791. StartingAddress = (PVOID)PAGE_ALIGN(CapturedBase);
  792. }
  793. CapturedRegionSize = (PCHAR)EndingAddress - (PCHAR)StartingAddress + 1;
  794. LOCK_ADDRESS_SPACE (Process);
  795. //
  796. // Make sure the address space was not deleted, if so,
  797. // return an error.
  798. //
  799. if (Process->Flags & PS_PROCESS_FLAGS_VM_DELETED) {
  800. Status = STATUS_PROCESS_IS_TERMINATING;
  801. goto ErrorReturn0;
  802. }
  803. FoundVad = MiCheckForConflictingVad (Process, StartingAddress, EndingAddress);
  804. if (FoundVad == NULL) {
  805. //
  806. // No virtual address is reserved at the specified base address,
  807. // return an error.
  808. //
  809. Status = STATUS_CONFLICTING_ADDRESSES;
  810. goto ErrorReturn0;
  811. }
  812. if (FoundVad->u.VadFlags.UserPhysicalPages == 1) {
  813. Status = STATUS_CONFLICTING_ADDRESSES;
  814. goto ErrorReturn0;
  815. }
  816. //
  817. // Ensure that the starting and ending addresses are all within
  818. // the same virtual address descriptor.
  819. //
  820. if ((MI_VA_TO_VPN (StartingAddress) < FoundVad->StartingVpn) ||
  821. (MI_VA_TO_VPN (EndingAddress) > FoundVad->EndingVpn)) {
  822. //
  823. // Not within the section virtual address descriptor,
  824. // return an error.
  825. //
  826. Status = STATUS_CONFLICTING_ADDRESSES;
  827. goto ErrorReturn0;
  828. }
  829. if (FoundVad->u.VadFlags.CommitCharge == MM_MAX_COMMIT) {
  830. //
  831. // This is a special VAD, don't let any commits occur.
  832. //
  833. Status = STATUS_CONFLICTING_ADDRESSES;
  834. goto ErrorReturn0;
  835. }
  836. #if defined(_MIALT4K_)
  837. WowProcess = Process->Wow64Process;
  838. OriginalProtectionMask = 0;
  839. if (WowProcess != NULL) {
  840. OriginalProtectionMask = MiMakeProtectionMask (Protect);
  841. if (OriginalProtectionMask == MM_INVALID_PROTECTION) {
  842. Status = STATUS_INVALID_PAGE_PROTECTION;
  843. goto ErrorReturn0;
  844. }
  845. if (StartingAddress >= (PVOID)MM_MAX_WOW64_ADDRESS) {
  846. Status = STATUS_CONFLICTING_ADDRESSES;
  847. goto ErrorReturn0;
  848. }
  849. //
  850. // If protection changes on this region are allowed then proceed.
  851. //
  852. if (FoundVad->u.VadFlags.NoChange == 0) {
  853. NativePageProtection = MiMakeProtectForNativePage (StartingAddress,
  854. Protect,
  855. Process);
  856. ProtectionMask = MiMakeProtectionMask (NativePageProtection);
  857. if (ProtectionMask == MM_INVALID_PROTECTION) {
  858. Status = STATUS_INVALID_PAGE_PROTECTION;
  859. goto ErrorReturn0;
  860. }
  861. }
  862. }
  863. #endif
  864. if (AllocationType == MEM_RESET) {
  865. LOCK_WS_UNSAFE (Process);
  866. Status = MiResetVirtualMemory (StartingAddress,
  867. EndingAddress,
  868. FoundVad,
  869. Process);
  870. UNLOCK_WS_AND_ADDRESS_SPACE (Process);
  871. goto done;
  872. }
  873. if (FoundVad->u.VadFlags.PrivateMemory == 0) {
  874. Status = STATUS_SUCCESS;
  875. //
  876. // The no cache option is not allowed for sections.
  877. //
  878. if (Protect & PAGE_NOCACHE) {
  879. Status = STATUS_INVALID_PAGE_PROTECTION;
  880. goto ErrorReturn0;
  881. }
  882. if (FoundVad->u.VadFlags.NoChange == 1) {
  883. //
  884. // An attempt is made at changing the protection
  885. // of a SEC_NO_CHANGE section.
  886. //
  887. Status = MiCheckSecuredVad (FoundVad,
  888. CapturedBase,
  889. CapturedRegionSize,
  890. ProtectionMask);
  891. if (!NT_SUCCESS (Status)) {
  892. goto ErrorReturn0;
  893. }
  894. }
  895. if (FoundVad->ControlArea->FilePointer != NULL) {
  896. if (FoundVad->u2.VadFlags2.ExtendableFile == 0) {
  897. //
  898. // Only page file backed sections can be committed.
  899. //
  900. Status = STATUS_ALREADY_COMMITTED;
  901. goto ErrorReturn0;
  902. }
  903. //
  904. // Commit the requested portions of the extendable file.
  905. //
  906. RtlZeroMemory (&Section, sizeof(SECTION));
  907. ControlArea = FoundVad->ControlArea;
  908. Section.Segment = ControlArea->Segment;
  909. Section.u.LongFlags = ControlArea->u.LongFlags;
  910. Section.InitialPageProtection = PAGE_READWRITE;
  911. NewSize.QuadPart = FoundVad->u2.VadFlags2.FileOffset;
  912. NewSize.QuadPart = NewSize.QuadPart << 16;
  913. NewSize.QuadPart += 1 +
  914. ((PCHAR)EndingAddress - (PCHAR)MI_VPN_TO_VA (FoundVad->StartingVpn));
  915. //
  916. // The working set and address space mutexes must be
  917. // released prior to calling MmExtendSection otherwise
  918. // a deadlock with the filesystem can occur.
  919. //
  920. // Prevent the control area from being deleted while
  921. // the (potential) extension is ongoing.
  922. //
  923. MiFlushAcquire (ControlArea);
  924. UNLOCK_ADDRESS_SPACE (Process);
  925. Status = MmExtendSection (&Section, &NewSize, FALSE);
  926. MiFlushRelease (ControlArea);
  927. if (NT_SUCCESS(Status)) {
  928. LOCK_ADDRESS_SPACE (Process);
  929. //
  930. // The Vad and/or the control area may have been changed
  931. // or deleted before the mutexes were regained above.
  932. // So everything must be revalidated. Note that
  933. // if anything has changed, success is silently
  934. // returned just as if the protection change had failed.
  935. // It is the caller's fault if any of these has gone
  936. // away and they will suffer.
  937. //
  938. if (Process->Flags & PS_PROCESS_FLAGS_VM_DELETED) {
  939. // Status = STATUS_PROCESS_IS_TERMINATING;
  940. goto ErrorReturn0;
  941. }
  942. FoundVad = MiCheckForConflictingVad (Process,
  943. StartingAddress,
  944. EndingAddress);
  945. if (FoundVad == NULL) {
  946. //
  947. // No virtual address is reserved at the specified
  948. // base address, return an error.
  949. //
  950. // Status = STATUS_CONFLICTING_ADDRESSES;
  951. goto ErrorReturn0;
  952. }
  953. if (ControlArea != FoundVad->ControlArea) {
  954. goto ErrorReturn0;
  955. }
  956. if (FoundVad->u.VadFlags.UserPhysicalPages == 1) {
  957. // Status = STATUS_CONFLICTING_ADDRESSES;
  958. goto ErrorReturn0;
  959. }
  960. if (FoundVad->u.VadFlags.CommitCharge == MM_MAX_COMMIT) {
  961. //
  962. // This is a special VAD, no commits are allowed.
  963. //
  964. // Status = STATUS_CONFLICTING_ADDRESSES;
  965. goto ErrorReturn0;
  966. }
  967. //
  968. // Ensure that the starting and ending addresses are
  969. // all within the same virtual address descriptor.
  970. //
  971. if ((MI_VA_TO_VPN (StartingAddress) < FoundVad->StartingVpn) ||
  972. (MI_VA_TO_VPN (EndingAddress) > FoundVad->EndingVpn)) {
  973. //
  974. // Not within the section virtual address
  975. // descriptor, return an error.
  976. //
  977. // Status = STATUS_CONFLICTING_ADDRESSES;
  978. goto ErrorReturn0;
  979. }
  980. if (FoundVad->u.VadFlags.NoChange == 1) {
  981. //
  982. // An attempt is made at changing the protection
  983. // of a SEC_NO_CHANGE section.
  984. //
  985. NTSTATUS Status2;
  986. Status2 = MiCheckSecuredVad (FoundVad,
  987. CapturedBase,
  988. CapturedRegionSize,
  989. ProtectionMask);
  990. if (!NT_SUCCESS (Status2)) {
  991. goto ErrorReturn0;
  992. }
  993. }
  994. if (FoundVad->ControlArea->FilePointer == NULL) {
  995. goto ErrorReturn0;
  996. }
  997. if (FoundVad->u2.VadFlags2.ExtendableFile == 0) {
  998. goto ErrorReturn0;
  999. }
  1000. #if defined(_MIALT4K_)
  1001. if (WowProcess != NULL) {
  1002. StartingAddressFor4k = (PVOID)PAGE_4K_ALIGN(OriginalBase);
  1003. EndingAddressFor4k = (PVOID)(((ULONG_PTR)OriginalBase +
  1004. OriginalRegionSize - 1) | (PAGE_4K - 1));
  1005. CapturedRegionSizeFor4k = (ULONG_PTR)EndingAddressFor4k -
  1006. (ULONG_PTR)StartingAddressFor4k + 1L;
  1007. if ((FoundVad->u.VadFlags.ImageMap == 1) ||
  1008. (FoundVad->u2.VadFlags2.CopyOnWrite == 1)) {
  1009. //
  1010. // Only set the MM_PROTECTION_COPY_MASK if the new protection includes
  1011. // MM_PROTECTION_WRITE_MASK, otherwise, it will be considered as MM_READ
  1012. // inside MiProtectFor4kPage().
  1013. //
  1014. if ((OriginalProtectionMask & MM_PROTECTION_WRITE_MASK) == MM_PROTECTION_WRITE_MASK) {
  1015. OriginalProtectionMask |= MM_PROTECTION_COPY_MASK;
  1016. }
  1017. }
  1018. MiProtectFor4kPage (StartingAddressFor4k,
  1019. CapturedRegionSizeFor4k,
  1020. OriginalProtectionMask,
  1021. ALT_COMMIT,
  1022. Process);
  1023. }
  1024. #endif
  1025. MiSetProtectionOnSection (Process,
  1026. FoundVad,
  1027. StartingAddress,
  1028. EndingAddress,
  1029. Protect,
  1030. &OldProtect,
  1031. TRUE,
  1032. &Locked);
  1033. //
  1034. // *** WARNING ***
  1035. //
  1036. // The alternate PTE support routines called by
  1037. // MiSetProtectionOnSection may have deleted the old (small)
  1038. // VAD and replaced it with a different (large) VAD - if so,
  1039. // the old VAD is freed and cannot be referenced.
  1040. //
  1041. UNLOCK_ADDRESS_SPACE (Process);
  1042. }
  1043. goto ErrorReturn1;
  1044. }
  1045. StartingPte = MiGetProtoPteAddress (FoundVad,
  1046. MI_VA_TO_VPN(StartingAddress));
  1047. LastPte = MiGetProtoPteAddress (FoundVad,
  1048. MI_VA_TO_VPN(EndingAddress));
  1049. #if 0
  1050. if (AllocationType & MEM_CHECK_COMMIT_STATE) {
  1051. //
  1052. // Make sure none of the pages are already committed.
  1053. //
  1054. ExAcquireFastMutexUnsafe (&MmSectionCommitMutex);
  1055. PointerPte = StartingPte;
  1056. while (PointerPte <= LastPte) {
  1057. //
  1058. // Check to see if the prototype PTE is committed.
  1059. // Note that prototype PTEs cannot be decommitted so
  1060. // the PTEs only need to be checked for zeroes.
  1061. //
  1062. if (PointerPte->u.Long != 0) {
  1063. ExReleaseFastMutexUnsafe (&MmSectionCommitMutex);
  1064. UNLOCK_ADDRESS_SPACE (Process);
  1065. Status = STATUS_ALREADY_COMMITTED;
  1066. goto ErrorReturn1;
  1067. }
  1068. PointerPte += 1;
  1069. }
  1070. ExReleaseFastMutexUnsafe (&MmSectionCommitMutex);
  1071. }
  1072. #endif //0
  1073. //
  1074. // Check to ensure these pages can be committed if this
  1075. // is a page file backed segment. Note that page file quota
  1076. // has already been charged for this.
  1077. //
  1078. PointerPte = StartingPte;
  1079. QuotaCharge = 1 + LastPte - StartingPte;
  1080. CopyOnWriteCharge = 0;
  1081. if (MI_IS_PTE_PROTECTION_COPY_WRITE(ProtectionMask)) {
  1082. //
  1083. // If the protection is copy on write, charge for
  1084. // the copy on writes.
  1085. //
  1086. CopyOnWriteCharge = QuotaCharge;
  1087. }
  1088. //
  1089. // Charge commitment for the range.
  1090. //
  1091. ChargedExactQuota = FALSE;
  1092. ChargedJobCommit = FALSE;
  1093. if (CopyOnWriteCharge != 0) {
  1094. Status = PsChargeProcessPageFileQuota (Process, CopyOnWriteCharge);
  1095. if (!NT_SUCCESS (Status)) {
  1096. UNLOCK_ADDRESS_SPACE (Process);
  1097. goto ErrorReturn1;
  1098. }
  1099. //
  1100. // Note this job charging is unusual because it is not
  1101. // followed by an immediate process charge.
  1102. //
  1103. if (Process->CommitChargeLimit) {
  1104. if (Process->CommitCharge + CopyOnWriteCharge > Process->CommitChargeLimit) {
  1105. if (Process->Job) {
  1106. PsReportProcessMemoryLimitViolation ();
  1107. }
  1108. UNLOCK_ADDRESS_SPACE (Process);
  1109. PsReturnProcessPageFileQuota (Process, CopyOnWriteCharge);
  1110. Status = STATUS_COMMITMENT_LIMIT;
  1111. goto ErrorReturn1;
  1112. }
  1113. }
  1114. if (Process->JobStatus & PS_JOB_STATUS_REPORT_COMMIT_CHANGES) {
  1115. if (PsChangeJobMemoryUsage(CopyOnWriteCharge) == FALSE) {
  1116. UNLOCK_ADDRESS_SPACE (Process);
  1117. PsReturnProcessPageFileQuota (Process, CopyOnWriteCharge);
  1118. Status = STATUS_COMMITMENT_LIMIT;
  1119. goto ErrorReturn1;
  1120. }
  1121. ChargedJobCommit = TRUE;
  1122. }
  1123. }
  1124. do {
  1125. if (MiChargeCommitment (QuotaCharge + CopyOnWriteCharge, NULL) == TRUE) {
  1126. break;
  1127. }
  1128. //
  1129. // Reduce the charge we are asking for if possible.
  1130. //
  1131. if (ChargedExactQuota == TRUE) {
  1132. //
  1133. // We have already tried for the precise charge,
  1134. // so just return an error.
  1135. //
  1136. ExReleaseFastMutexUnsafe (&MmSectionCommitMutex);
  1137. if (CopyOnWriteCharge != 0) {
  1138. if (ChargedJobCommit == TRUE) {
  1139. PsChangeJobMemoryUsage (-(SSIZE_T)CopyOnWriteCharge);
  1140. }
  1141. UNLOCK_ADDRESS_SPACE (Process);
  1142. PsReturnProcessPageFileQuota (Process, CopyOnWriteCharge);
  1143. }
  1144. else {
  1145. UNLOCK_ADDRESS_SPACE (Process);
  1146. }
  1147. Status = STATUS_COMMITMENT_LIMIT;
  1148. goto ErrorReturn1;
  1149. }
  1150. //
  1151. // The commitment charging of quota failed, calculate the
  1152. // exact quota taking into account pages that may already be
  1153. // committed and retry the operation.
  1154. //
  1155. ExAcquireFastMutexUnsafe (&MmSectionCommitMutex);
  1156. while (PointerPte <= LastPte) {
  1157. //
  1158. // Check to see if the prototype PTE is committed.
  1159. // Note that prototype PTEs cannot be decommitted so
  1160. // PTEs only need to be checked for zeroes.
  1161. //
  1162. if (PointerPte->u.Long != 0) {
  1163. QuotaCharge -= 1;
  1164. }
  1165. PointerPte += 1;
  1166. }
  1167. PointerPte = StartingPte;
  1168. ChargedExactQuota = TRUE;
  1169. //
  1170. // If the entire range is committed then there's nothing to charge.
  1171. //
  1172. if (QuotaCharge + CopyOnWriteCharge == 0) {
  1173. ExReleaseFastMutexUnsafe (&MmSectionCommitMutex);
  1174. QuotaFree = 0;
  1175. goto FinishedCharging;
  1176. }
  1177. } while (TRUE);
  1178. if (ChargedExactQuota == FALSE) {
  1179. ExAcquireFastMutexUnsafe (&MmSectionCommitMutex);
  1180. }
  1181. //
  1182. // Commit all the pages.
  1183. //
  1184. Segment = FoundVad->ControlArea->Segment;
  1185. TempPte = Segment->SegmentPteTemplate;
  1186. ASSERT (TempPte.u.Long != 0);
  1187. QuotaFree = 0;
  1188. while (PointerPte <= LastPte) {
  1189. if (PointerPte->u.Long != 0) {
  1190. //
  1191. // Page is already committed, back out commitment.
  1192. //
  1193. QuotaFree += 1;
  1194. }
  1195. else {
  1196. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  1197. }
  1198. PointerPte += 1;
  1199. }
  1200. //
  1201. // Subtract out any excess, then update the segment charges.
  1202. // Note only segment commit is excess - process commit must
  1203. // remain fully charged.
  1204. //
  1205. if (ChargedExactQuota == FALSE) {
  1206. ASSERT (QuotaCharge >= QuotaFree);
  1207. QuotaCharge -= QuotaFree;
  1208. //
  1209. // Return the QuotaFree excess commitment after the
  1210. // mutexes are released to remove needless contention.
  1211. //
  1212. }
  1213. else {
  1214. //
  1215. // Exact quota was charged so zero this to signify
  1216. // there is no excess to return.
  1217. //
  1218. QuotaFree = 0;
  1219. }
  1220. if (QuotaCharge != 0) {
  1221. Segment->NumberOfCommittedPages += QuotaCharge;
  1222. InterlockedExchangeAddSizeT (&MmSharedCommit, QuotaCharge);
  1223. MM_TRACK_COMMIT (MM_DBG_COMMIT_ALLOCVM_SEGMENT, QuotaCharge);
  1224. }
  1225. ExReleaseFastMutexUnsafe (&MmSectionCommitMutex);
  1226. //
  1227. // Update the per-process charges.
  1228. //
  1229. if (CopyOnWriteCharge != 0) {
  1230. FoundVad->u.VadFlags.CommitCharge += CopyOnWriteCharge;
  1231. Process->CommitCharge += CopyOnWriteCharge;
  1232. MI_INCREMENT_TOTAL_PROCESS_COMMIT (CopyOnWriteCharge);
  1233. if (Process->CommitCharge > Process->CommitChargePeak) {
  1234. Process->CommitChargePeak = Process->CommitCharge;
  1235. }
  1236. MM_TRACK_COMMIT (MM_DBG_COMMIT_ALLOCVM_PROCESS, CopyOnWriteCharge);
  1237. }
  1238. FinishedCharging:
  1239. #if defined(_MIALT4K_)
  1240. //
  1241. // Update the alternate table before PTEs are created
  1242. // for the protection change.
  1243. //
  1244. if (WowProcess != NULL) {
  1245. StartingAddressFor4k = (PVOID)PAGE_4K_ALIGN(OriginalBase);
  1246. EndingAddressFor4k = (PVOID)(((ULONG_PTR)OriginalBase +
  1247. OriginalRegionSize - 1) | (PAGE_4K - 1));
  1248. CapturedRegionSizeFor4k = (ULONG_PTR)EndingAddressFor4k -
  1249. (ULONG_PTR)StartingAddressFor4k + 1L;
  1250. if ((FoundVad->u.VadFlags.ImageMap == 1) ||
  1251. (FoundVad->u2.VadFlags2.CopyOnWrite == 1)) {
  1252. //
  1253. // Only set the MM_PROTECTION_COPY_MASK if the new protection includes
  1254. // MM_PROTECTION_WRITE_MASK, otherwise, it will be considered as MM_READ
  1255. // inside MiProtectFor4kPage().
  1256. //
  1257. if ((OriginalProtectionMask & MM_PROTECTION_WRITE_MASK) == MM_PROTECTION_WRITE_MASK) {
  1258. OriginalProtectionMask |= MM_PROTECTION_COPY_MASK;
  1259. }
  1260. }
  1261. //
  1262. // Set the alternate permission table.
  1263. //
  1264. MiProtectFor4kPage (StartingAddressFor4k,
  1265. CapturedRegionSizeFor4k,
  1266. OriginalProtectionMask,
  1267. ALT_COMMIT,
  1268. Process);
  1269. }
  1270. else {
  1271. //
  1272. // Initializing these is not needed for
  1273. // correctness but without it the compiler cannot compile this code
  1274. // W4 to check for use of uninitialized variables.
  1275. //
  1276. StartingAddressFor4k = NULL;
  1277. CapturedRegionSizeFor4k = 0;
  1278. }
  1279. #endif
  1280. //
  1281. // Change all the protections to be protected as specified.
  1282. //
  1283. MiSetProtectionOnSection (Process,
  1284. FoundVad,
  1285. StartingAddress,
  1286. EndingAddress,
  1287. Protect,
  1288. &OldProtect,
  1289. TRUE,
  1290. &Locked);
  1291. //
  1292. // *** WARNING ***
  1293. //
  1294. // The alternate PTE support routines called by
  1295. // MiSetProtectionOnSection may have deleted the old (small)
  1296. // VAD and replaced it with a different (large) VAD - if so,
  1297. // the old VAD is freed and cannot be referenced.
  1298. //
  1299. UNLOCK_ADDRESS_SPACE (Process);
  1300. //
  1301. // Return any excess segment commit that may have been charged.
  1302. //
  1303. if (QuotaFree != 0) {
  1304. MiReturnCommitment (QuotaFree);
  1305. MM_TRACK_COMMIT (MM_DBG_COMMIT_RETURN_ALLOCVM_SEGMENT, QuotaFree);
  1306. }
  1307. if (Attached == TRUE) {
  1308. KeUnstackDetachProcess (&ApcState);
  1309. }
  1310. if (ProcessHandle != NtCurrentProcess()) {
  1311. ObDereferenceObject (Process);
  1312. }
  1313. #if defined(_MIALT4K_)
  1314. if (WowProcess != NULL) {
  1315. CapturedRegionSize = CapturedRegionSizeFor4k;
  1316. StartingAddress = StartingAddressFor4k;
  1317. }
  1318. #endif
  1319. try {
  1320. *RegionSize = CapturedRegionSize;
  1321. *BaseAddress = StartingAddress;
  1322. } except (EXCEPTION_EXECUTE_HANDLER) {
  1323. //
  1324. // Return success at this point even if the results
  1325. // cannot be written.
  1326. //
  1327. NOTHING;
  1328. }
  1329. return STATUS_SUCCESS;
  1330. }
  1331. //
  1332. // PAGE_WRITECOPY is not valid for private pages.
  1333. //
  1334. if ((Protect & PAGE_WRITECOPY) ||
  1335. (Protect & PAGE_EXECUTE_WRITECOPY)) {
  1336. Status = STATUS_INVALID_PAGE_PROTECTION;
  1337. goto ErrorReturn0;
  1338. }
  1339. //
  1340. // Ensure none of the pages are already committed as described
  1341. // in the virtual address descriptor.
  1342. //
  1343. #if 0
  1344. if (AllocationType & MEM_CHECK_COMMIT_STATE) {
  1345. if ( !MiIsEntireRangeDecommitted(StartingAddress,
  1346. EndingAddress,
  1347. FoundVad,
  1348. Process)) {
  1349. //
  1350. // Previously reserved pages have been committed, or
  1351. // an error occurred, release mutex and return status.
  1352. //
  1353. Status = STATUS_ALREADY_COMMITTED;
  1354. goto ErrorReturn0;
  1355. }
  1356. }
  1357. #endif //0
  1358. //
  1359. // Build a demand zero PTE with the proper protection.
  1360. //
  1361. TempPte = ZeroPte;
  1362. TempPte.u.Soft.Protection = ProtectionMask;
  1363. DecommittedPte = ZeroPte;
  1364. DecommittedPte.u.Soft.Protection = MM_DECOMMIT;
  1365. if (FoundVad->u.VadFlags.MemCommit) {
  1366. CommitLimitPte = MiGetPteAddress (MI_VPN_TO_VA (FoundVad->EndingVpn));
  1367. }
  1368. else {
  1369. CommitLimitPte = NULL;
  1370. }
  1371. //
  1372. // The address range has not been committed, commit it now.
  1373. // Note that for private pages, commitment is handled by
  1374. // explicitly updating PTEs to contain Demand Zero entries.
  1375. //
  1376. PointerPde = MiGetPdeAddress (StartingAddress);
  1377. PointerPte = MiGetPteAddress (StartingAddress);
  1378. LastPte = MiGetPteAddress (EndingAddress);
  1379. //
  1380. // Check to ensure these pages can be committed.
  1381. //
  1382. QuotaCharge = 1 + LastPte - PointerPte;
  1383. //
  1384. // Charge quota and commitment for the range.
  1385. //
  1386. ChargedExactQuota = FALSE;
  1387. do {
  1388. ChargedJobCommit = FALSE;
  1389. if (Process->CommitChargeLimit) {
  1390. if (Process->CommitCharge + QuotaCharge > Process->CommitChargeLimit) {
  1391. if (Process->Job) {
  1392. PsReportProcessMemoryLimitViolation ();
  1393. }
  1394. Status = STATUS_COMMITMENT_LIMIT;
  1395. goto Failed;
  1396. }
  1397. }
  1398. if (Process->JobStatus & PS_JOB_STATUS_REPORT_COMMIT_CHANGES) {
  1399. if (PsChangeJobMemoryUsage(QuotaCharge) == FALSE) {
  1400. Status = STATUS_COMMITMENT_LIMIT;
  1401. goto Failed;
  1402. }
  1403. ChargedJobCommit = TRUE;
  1404. }
  1405. if (MiChargeCommitment (QuotaCharge, NULL) == FALSE) {
  1406. Status = STATUS_COMMITMENT_LIMIT;
  1407. goto Failed;
  1408. }
  1409. Status = PsChargeProcessPageFileQuota (Process, QuotaCharge);
  1410. if (!NT_SUCCESS (Status)) {
  1411. MiReturnCommitment (QuotaCharge);
  1412. goto Failed;
  1413. }
  1414. MM_TRACK_COMMIT (MM_DBG_COMMIT_ALLOCVM_PROCESS2, QuotaCharge);
  1415. FoundVad->u.VadFlags.CommitCharge += QuotaCharge;
  1416. Process->CommitCharge += QuotaCharge;
  1417. MI_INCREMENT_TOTAL_PROCESS_COMMIT (QuotaCharge);
  1418. if (Process->CommitCharge > Process->CommitChargePeak) {
  1419. Process->CommitChargePeak = Process->CommitCharge;
  1420. }
  1421. //
  1422. // Successful so break out now.
  1423. //
  1424. break;
  1425. Failed:
  1426. //
  1427. // Charging of commitment failed. Release the held mutexes and return
  1428. // the failure status to the user.
  1429. //
  1430. if (ChargedJobCommit == TRUE) {
  1431. PsChangeJobMemoryUsage (0 - QuotaCharge);
  1432. }
  1433. if (ChargedExactQuota == TRUE) {
  1434. //
  1435. // We have already tried for the precise charge,
  1436. // return an error.
  1437. //
  1438. goto ErrorReturn;
  1439. }
  1440. LOCK_WS_UNSAFE (Process);
  1441. //
  1442. // Quota charge failed, calculate the exact quota
  1443. // taking into account pages that may already be
  1444. // committed, subtract this from the total and retry the operation.
  1445. //
  1446. QuotaFree = MiCalculatePageCommitment (StartingAddress,
  1447. EndingAddress,
  1448. FoundVad,
  1449. Process);
  1450. if (QuotaFree == 0) {
  1451. goto ErrorReturn;
  1452. }
  1453. ChargedExactQuota = TRUE;
  1454. QuotaCharge -= QuotaFree;
  1455. ASSERT ((SSIZE_T)QuotaCharge >= 0);
  1456. if (QuotaCharge == 0) {
  1457. //
  1458. // All the pages are already committed so just march on.
  1459. // Explicitly set status to success as code above may have
  1460. // generated a failure status when overcharging.
  1461. //
  1462. Status = STATUS_SUCCESS;
  1463. break;
  1464. }
  1465. } while (TRUE);
  1466. QuotaFree = 0;
  1467. if (ChargedExactQuota == FALSE) {
  1468. LOCK_WS_UNSAFE (Process);
  1469. }
  1470. //
  1471. // Fill in all the page directory and page table pages with the
  1472. // demand zero PTE.
  1473. //
  1474. MiMakePdeExistAndMakeValid (PointerPde, Process, FALSE);
  1475. while (PointerPte <= LastPte) {
  1476. if (MiIsPteOnPdeBoundary (PointerPte)) {
  1477. PointerPde = MiGetPteAddress (PointerPte);
  1478. //
  1479. // Pointing to the next page table page, make
  1480. // a page table page exist and make it valid.
  1481. //
  1482. MiMakePdeExistAndMakeValid (PointerPde, Process, FALSE);
  1483. }
  1484. if (PointerPte->u.Long == 0) {
  1485. if (PointerPte <= CommitLimitPte) {
  1486. //
  1487. // This page is implicitly committed.
  1488. //
  1489. QuotaFree += 1;
  1490. }
  1491. //
  1492. // Increment the count of non-zero page table entries
  1493. // for this page table and the number of private pages
  1494. // for the process.
  1495. //
  1496. Va = MiGetVirtualAddressMappedByPte (PointerPte);
  1497. UsedPageTableHandle = MI_GET_USED_PTES_HANDLE (Va);
  1498. MI_INCREMENT_USED_PTES_BY_HANDLE (UsedPageTableHandle);
  1499. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  1500. }
  1501. else {
  1502. if (PointerPte->u.Long == DecommittedPte.u.Long) {
  1503. //
  1504. // Only commit the page if it is already decommitted.
  1505. //
  1506. MI_WRITE_INVALID_PTE (PointerPte, TempPte);
  1507. }
  1508. else {
  1509. QuotaFree += 1;
  1510. //
  1511. // Make sure the protection for the page is right.
  1512. //
  1513. if (!ChangeProtection &&
  1514. (Protect != MiGetPageProtection (PointerPte,
  1515. Process,
  1516. FALSE))) {
  1517. ChangeProtection = TRUE;
  1518. }
  1519. }
  1520. }
  1521. PointerPte += 1;
  1522. }
  1523. UNLOCK_WS_UNSAFE (Process);
  1524. #if defined(_MIALT4K_)
  1525. if (WowProcess != NULL) {
  1526. StartingAddress = (PVOID) PAGE_4K_ALIGN(OriginalBase);
  1527. EndingAddress = (PVOID)(((ULONG_PTR)OriginalBase +
  1528. OriginalRegionSize - 1) | (PAGE_4K - 1));
  1529. CapturedRegionSize = (ULONG_PTR)EndingAddress -
  1530. (ULONG_PTR)StartingAddress + 1L;
  1531. //
  1532. // Update the alternate permission table.
  1533. //
  1534. MiProtectFor4kPage (StartingAddress,
  1535. CapturedRegionSize,
  1536. OriginalProtectionMask,
  1537. ALT_COMMIT,
  1538. Process);
  1539. }
  1540. #endif
  1541. if ((ChargedExactQuota == FALSE) && (QuotaFree != 0)) {
  1542. FoundVad->u.VadFlags.CommitCharge -= QuotaFree;
  1543. ASSERT ((LONG_PTR)FoundVad->u.VadFlags.CommitCharge >= 0);
  1544. Process->CommitCharge -= QuotaFree;
  1545. UNLOCK_ADDRESS_SPACE (Process);
  1546. MI_INCREMENT_TOTAL_PROCESS_COMMIT (0 - QuotaFree);
  1547. MiReturnCommitment (QuotaFree);
  1548. MM_TRACK_COMMIT (MM_DBG_COMMIT_RETURN_ALLOCVM2, QuotaFree);
  1549. PsReturnProcessPageFileQuota (Process, QuotaFree);
  1550. if (ChargedJobCommit) {
  1551. PsChangeJobMemoryUsage (-(SSIZE_T)QuotaFree);
  1552. }
  1553. }
  1554. else {
  1555. UNLOCK_ADDRESS_SPACE (Process);
  1556. }
  1557. //
  1558. // Previously reserved pages have been committed or an error occurred.
  1559. // Detach, dereference process and return status.
  1560. //
  1561. done:
  1562. if (ChangeProtection) {
  1563. PVOID Start;
  1564. SIZE_T Size;
  1565. ULONG LastProtect;
  1566. Start = StartingAddress;
  1567. Size = CapturedRegionSize;
  1568. MiProtectVirtualMemory (Process,
  1569. &Start,
  1570. &Size,
  1571. Protect,
  1572. &LastProtect);
  1573. }
  1574. if (Attached == TRUE) {
  1575. KeUnstackDetachProcess (&ApcState);
  1576. }
  1577. if (ProcessHandle != NtCurrentProcess()) {
  1578. ObDereferenceObject (Process);
  1579. }
  1580. //
  1581. // Establish an exception handler and write the size and base
  1582. // address.
  1583. //
  1584. try {
  1585. *RegionSize = CapturedRegionSize;
  1586. *BaseAddress = StartingAddress;
  1587. } except (EXCEPTION_EXECUTE_HANDLER) {
  1588. return GetExceptionCode();
  1589. }
  1590. return Status;
  1591. ErrorReturn:
  1592. UNLOCK_WS_UNSAFE (Process);
  1593. ErrorReturn0:
  1594. UNLOCK_ADDRESS_SPACE (Process);
  1595. ErrorReturn1:
  1596. if (Attached == TRUE) {
  1597. KeUnstackDetachProcess (&ApcState);
  1598. }
  1599. if (ProcessHandle != NtCurrentProcess()) {
  1600. ObDereferenceObject (Process);
  1601. }
  1602. return Status;
  1603. }
  1604. NTSTATUS
  1605. MiResetVirtualMemory (
  1606. IN PVOID StartingAddress,
  1607. IN PVOID EndingAddress,
  1608. IN PMMVAD Vad,
  1609. IN PEPROCESS Process
  1610. )
  1611. /*++
  1612. Routine Description:
  1613. Arguments:
  1614. StartingAddress - Supplies the starting address of the range.
  1615. RegionsSize - Supplies the size.
  1616. Process - Supplies the current process.
  1617. Return Value:
  1618. Environment:
  1619. Kernel mode, APCs disabled, WorkingSetMutex and AddressCreation mutexes
  1620. held.
  1621. --*/
  1622. {
  1623. PMMPTE PointerPte;
  1624. PMMPTE ProtoPte;
  1625. PMMPTE PointerPde;
  1626. PMMPTE PointerPpe;
  1627. PMMPTE PointerPxe;
  1628. PMMPTE LastPte;
  1629. MMPTE PteContents;
  1630. ULONG Waited;
  1631. LOGICAL PfnHeld;
  1632. ULONG First;
  1633. KIRQL OldIrql;
  1634. PMMPFN Pfn1;
  1635. PMMCLONE_BLOCK CloneBlock;
  1636. PMMCLONE_DESCRIPTOR CloneDescriptor;
  1637. if (Vad->u.VadFlags.PrivateMemory == 0) {
  1638. if (Vad->ControlArea->FilePointer != NULL) {
  1639. //
  1640. // Only page file backed sections can be committed.
  1641. //
  1642. return STATUS_USER_MAPPED_FILE;
  1643. }
  1644. }
  1645. PfnHeld = FALSE;
  1646. //
  1647. // Initializing OldIrql is not needed for correctness, but without it
  1648. // the compiler cannot compile this code W4 to check for use of
  1649. // uninitialized variables.
  1650. //
  1651. OldIrql = PASSIVE_LEVEL;
  1652. First = TRUE;
  1653. PointerPte = MiGetPteAddress (StartingAddress);
  1654. LastPte = MiGetPteAddress (EndingAddress);
  1655. MmLockPagableSectionByHandle (ExPageLockHandle);
  1656. //
  1657. // Examine all the PTEs in the range.
  1658. //
  1659. while (PointerPte <= LastPte) {
  1660. if (MiIsPteOnPdeBoundary (PointerPte) || (First)) {
  1661. if (MiIsPteOnPpeBoundary (PointerPte)) {
  1662. if (MiIsPteOnPxeBoundary (PointerPte)) {
  1663. PointerPxe = MiGetPpeAddress (PointerPte);
  1664. if (!MiDoesPxeExistAndMakeValid(PointerPxe,
  1665. Process,
  1666. PfnHeld,
  1667. &Waited)) {
  1668. //
  1669. // This extended page directory parent entry is empty,
  1670. // go to the next one.
  1671. //
  1672. PointerPxe += 1;
  1673. PointerPpe = MiGetVirtualAddressMappedByPte (PointerPxe);
  1674. PointerPde = MiGetVirtualAddressMappedByPte (PointerPpe);
  1675. PointerPte = MiGetVirtualAddressMappedByPte (PointerPde);
  1676. continue;
  1677. }
  1678. }
  1679. PointerPpe = MiGetPdeAddress (PointerPte);
  1680. if (!MiDoesPpeExistAndMakeValid(PointerPpe,
  1681. Process,
  1682. PfnHeld,
  1683. &Waited)) {
  1684. //
  1685. // This page directory parent entry is empty,
  1686. // go to the next one.
  1687. //
  1688. PointerPpe += 1;
  1689. PointerPde = MiGetVirtualAddressMappedByPte (PointerPpe);
  1690. PointerPte = MiGetVirtualAddressMappedByPte (PointerPde);
  1691. continue;
  1692. }
  1693. }
  1694. //
  1695. // Pointing to the next page table page, make
  1696. // a page table page exist and make it valid.
  1697. //
  1698. First = FALSE;
  1699. PointerPde = MiGetPteAddress (PointerPte);
  1700. if (!MiDoesPdeExistAndMakeValid(PointerPde,
  1701. Process,
  1702. PfnHeld,
  1703. &Waited)) {
  1704. //
  1705. // This page directory entry is empty, go to the next one.
  1706. //
  1707. PointerPde += 1;
  1708. PointerPte = MiGetVirtualAddressMappedByPte (PointerPde);
  1709. continue;
  1710. }
  1711. }
  1712. PteContents = *PointerPte;
  1713. ProtoPte = NULL;
  1714. if ((PteContents.u.Hard.Valid == 0) &&
  1715. (PteContents.u.Soft.Prototype == 1)) {
  1716. //
  1717. // This is a prototype PTE, evaluate the prototype PTE. Note that
  1718. // the fact it is a prototype PTE does not guarantee that this is a
  1719. // regular or long VAD - it may be a short VAD in a forked process,
  1720. // so check PrivateMemory before referencing the FirstPrototypePte
  1721. // field.
  1722. //
  1723. if ((Vad->u.VadFlags.PrivateMemory == 0) &&
  1724. (Vad->FirstPrototypePte != NULL)) {
  1725. ProtoPte = MiGetProtoPteAddress(Vad,
  1726. MI_VA_TO_VPN (
  1727. MiGetVirtualAddressMappedByPte(PointerPte)));
  1728. }
  1729. else {
  1730. CloneBlock = (PMMCLONE_BLOCK)MiPteToProto (PointerPte);
  1731. ProtoPte = (PMMPTE) CloneBlock;
  1732. CloneDescriptor = MiLocateCloneAddress (Process, (PVOID)CloneBlock);
  1733. ASSERT (CloneDescriptor != NULL);
  1734. }
  1735. if (!PfnHeld) {
  1736. PfnHeld = TRUE;
  1737. LOCK_PFN (OldIrql);
  1738. }
  1739. //
  1740. // The working set mutex may be released in order to make the
  1741. // prototype PTE which resides in paged pool resident. If this
  1742. // occurs, the page directory and/or page table of the original
  1743. // user address may get trimmed. Account for that here.
  1744. //
  1745. if (MiMakeSystemAddressValidPfnWs (ProtoPte, Process) != 0) {
  1746. //
  1747. // Working set mutex was released, restart from the top.
  1748. //
  1749. First = TRUE;
  1750. continue;
  1751. }
  1752. PteContents = *ProtoPte;
  1753. }
  1754. if (PteContents.u.Hard.Valid == 1) {
  1755. if (!PfnHeld) {
  1756. PfnHeld = TRUE;
  1757. LOCK_PFN (OldIrql);
  1758. continue;
  1759. }
  1760. Pfn1 = MI_PFN_ELEMENT (PteContents.u.Hard.PageFrameNumber);
  1761. if (Pfn1->u3.e2.ReferenceCount == 1) {
  1762. //
  1763. // Only this process has the page mapped.
  1764. //
  1765. MI_SET_MODIFIED (Pfn1, 0, 0x20);
  1766. MiReleasePageFileSpace (Pfn1->OriginalPte);
  1767. Pfn1->OriginalPte.u.Soft.PageFileHigh = 0;
  1768. }
  1769. if ((!ProtoPte) && (MI_IS_PTE_DIRTY (PteContents))) {
  1770. //
  1771. // Clear the dirty bit and flush tb if it is NOT a prototype
  1772. // PTE.
  1773. //
  1774. MI_SET_PTE_CLEAN (PteContents);
  1775. KeFlushSingleTb (MiGetVirtualAddressMappedByPte (PointerPte),
  1776. TRUE,
  1777. FALSE,
  1778. (PHARDWARE_PTE)PointerPte,
  1779. PteContents.u.Flush);
  1780. }
  1781. }
  1782. else if (PteContents.u.Soft.Transition == 1) {
  1783. if (!PfnHeld) {
  1784. PfnHeld = TRUE;
  1785. LOCK_PFN (OldIrql);
  1786. continue;
  1787. }
  1788. Pfn1 = MI_PFN_ELEMENT (PteContents.u.Trans.PageFrameNumber);
  1789. if ((Pfn1->u3.e1.PageLocation == ModifiedPageList) &&
  1790. (Pfn1->u3.e2.ReferenceCount == 0)) {
  1791. //
  1792. // Remove from the modified list, release the page
  1793. // file space and insert on the standby list.
  1794. //
  1795. MI_SET_MODIFIED (Pfn1, 0, 0x21);
  1796. MiUnlinkPageFromList (Pfn1);
  1797. MiReleasePageFileSpace (Pfn1->OriginalPte);
  1798. Pfn1->OriginalPte.u.Soft.PageFileHigh = 0;
  1799. MiInsertPageInList (&MmStandbyPageListHead,
  1800. MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE(&PteContents));
  1801. }
  1802. }
  1803. else {
  1804. if (PteContents.u.Soft.PageFileHigh != 0) {
  1805. if (!PfnHeld) {
  1806. LOCK_PFN (OldIrql);
  1807. }
  1808. MiReleasePageFileSpace (PteContents);
  1809. if (ProtoPte) {
  1810. ProtoPte->u.Soft.PageFileHigh = 0;
  1811. }
  1812. UNLOCK_PFN (OldIrql);
  1813. PfnHeld = FALSE;
  1814. if (!ProtoPte) {
  1815. PointerPte->u.Soft.PageFileHigh = 0;
  1816. }
  1817. }
  1818. else {
  1819. if (PfnHeld) {
  1820. UNLOCK_PFN (OldIrql);
  1821. }
  1822. PfnHeld = FALSE;
  1823. }
  1824. }
  1825. PointerPte += 1;
  1826. }
  1827. if (PfnHeld) {
  1828. UNLOCK_PFN (OldIrql);
  1829. }
  1830. MmUnlockPagableImageSection (ExPageLockHandle);
  1831. return STATUS_SUCCESS;
  1832. }
  1833. LOGICAL
  1834. MiCreatePageTablesForPhysicalRange (
  1835. IN PEPROCESS Process,
  1836. IN PVOID StartingAddress,
  1837. IN PVOID EndingAddress
  1838. )
  1839. /*++
  1840. Routine Description:
  1841. This routine initializes page directory and page table pages for a
  1842. user-controlled physical range of pages.
  1843. Arguments:
  1844. Process - Supplies the current process.
  1845. StartingAddress - Supplies the starting address of the range.
  1846. EndingAddress - Supplies the ending address of the range.
  1847. Return Value:
  1848. TRUE if the page tables were created, FALSE if not.
  1849. Environment:
  1850. Kernel mode, APCs disabled, WorkingSetMutex and AddressCreation mutexes
  1851. held.
  1852. --*/
  1853. {
  1854. MMPTE PteContents;
  1855. PMMPTE LastPte;
  1856. PMMPTE LastPde;
  1857. PMMPTE LastPpe;
  1858. PMMPTE PointerPte;
  1859. PMMPTE PointerPde;
  1860. PMMPTE PointerPpe;
  1861. PVOID UsedPageTableHandle;
  1862. LOGICAL FirstTime;
  1863. KIRQL OldIrql;
  1864. PMMPFN Pfn1;
  1865. PFN_NUMBER PagesNeeded;
  1866. FirstTime = TRUE;
  1867. PointerPpe = MiGetPpeAddress (StartingAddress);
  1868. PointerPde = MiGetPdeAddress (StartingAddress);
  1869. PointerPte = MiGetPteAddress (StartingAddress);
  1870. LastPpe = MiGetPpeAddress (EndingAddress);
  1871. LastPde = MiGetPdeAddress (EndingAddress);
  1872. LastPte = MiGetPteAddress (EndingAddress);
  1873. //
  1874. // Charge resident available pages for all of the page directory and table
  1875. // pages as they will not be paged until the VAD is freed.
  1876. //
  1877. if (LastPte != PointerPte) {
  1878. PagesNeeded = MI_COMPUTE_PAGES_SPANNED (PointerPte,
  1879. LastPte - PointerPte);
  1880. #if (_MI_PAGING_LEVELS >= 3)
  1881. if (LastPde != PointerPde) {
  1882. PagesNeeded += MI_COMPUTE_PAGES_SPANNED (PointerPde,
  1883. LastPde - PointerPde);
  1884. #if (_MI_PAGING_LEVELS >= 4)
  1885. if (LastPpe != PointerPpe) {
  1886. PagesNeeded += MI_COMPUTE_PAGES_SPANNED (PointerPpe,
  1887. LastPpe - PointerPpe);
  1888. }
  1889. #endif
  1890. }
  1891. #endif
  1892. }
  1893. else {
  1894. PagesNeeded = 1;
  1895. #if (_MI_PAGING_LEVELS >= 3)
  1896. PagesNeeded += 1;
  1897. #endif
  1898. #if (_MI_PAGING_LEVELS >= 4)
  1899. PagesNeeded += 1;
  1900. #endif
  1901. }
  1902. MmLockPagableSectionByHandle (ExPageLockHandle);
  1903. LOCK_PFN (OldIrql);
  1904. if ((SPFN_NUMBER)PagesNeeded > MI_NONPAGABLE_MEMORY_AVAILABLE() - 20) {
  1905. UNLOCK_PFN (OldIrql);
  1906. MmUnlockPagableImageSection (ExPageLockHandle);
  1907. return FALSE;
  1908. }
  1909. MmResidentAvailablePages -= PagesNeeded;
  1910. MM_BUMP_COUNTER(58, PagesNeeded);
  1911. UNLOCK_PFN (OldIrql);
  1912. //
  1913. // Initializing UsedPageTableHandle is not needed for correctness
  1914. // but without it the compiler cannot compile this code
  1915. // W4 to check for use of uninitialized variables.
  1916. //
  1917. UsedPageTableHandle = NULL;
  1918. //
  1919. // Fill in all the page table pages with the zero PTE.
  1920. //
  1921. while (PointerPte <= LastPte) {
  1922. if (MiIsPteOnPdeBoundary (PointerPte) || FirstTime == TRUE) {
  1923. PointerPde = MiGetPteAddress (PointerPte);
  1924. //
  1925. // Pointing to the next page table page, make
  1926. // a page table page exist and make it valid.
  1927. //
  1928. // Note this ripples sharecounts through the paging hierarchy so
  1929. // there is no need to up sharecounts to prevent trimming of the
  1930. // page directory (and parent) page as making the page table
  1931. // valid below does this automatically.
  1932. //
  1933. MiMakePdeExistAndMakeValid (PointerPde, Process, FALSE);
  1934. //
  1935. // Up the sharecount so the page table page will not get
  1936. // trimmed even if it has no currently valid entries.
  1937. //
  1938. PteContents = *PointerPde;
  1939. Pfn1 = MI_PFN_ELEMENT (PteContents.u.Hard.PageFrameNumber);
  1940. LOCK_PFN (OldIrql);
  1941. Pfn1->u2.ShareCount += 1;
  1942. UNLOCK_PFN (OldIrql);
  1943. FirstTime = FALSE;
  1944. UsedPageTableHandle = MI_GET_USED_PTES_HANDLE (StartingAddress);
  1945. }
  1946. ASSERT (PointerPte->u.Long == 0);
  1947. //
  1948. // Increment the count of non-zero page table entries
  1949. // for this page table - even though this entry is still zero,
  1950. // this is a special case.
  1951. //
  1952. MI_INCREMENT_USED_PTES_BY_HANDLE (UsedPageTableHandle);
  1953. PointerPte += 1;
  1954. StartingAddress = (PVOID)((PUCHAR)StartingAddress + PAGE_SIZE);
  1955. }
  1956. MmUnlockPagableImageSection (ExPageLockHandle);
  1957. return TRUE;
  1958. }
  1959. VOID
  1960. MiDeletePageTablesForPhysicalRange (
  1961. IN PVOID StartingAddress,
  1962. IN PVOID EndingAddress
  1963. )
  1964. /*++
  1965. Routine Description:
  1966. This routine deletes page directory and page table pages for a
  1967. user-controlled physical range of pages.
  1968. Even though PTEs may be zero in this range, UsedPageTable counts were
  1969. incremented for these special ranges and must be decremented now.
  1970. Arguments:
  1971. StartingAddress - Supplies the starting address of the range.
  1972. EndingAddress - Supplies the ending address of the range.
  1973. Return Value:
  1974. None.
  1975. Environment:
  1976. Kernel mode, APCs disabled, WorkingSetMutex and AddressCreation mutexes
  1977. held.
  1978. --*/
  1979. {
  1980. PVOID TempVa;
  1981. MMPTE PteContents;
  1982. PMMPTE LastPte;
  1983. PMMPTE LastPde;
  1984. PMMPTE LastPpe;
  1985. PMMPTE PointerPte;
  1986. PMMPTE PointerPde;
  1987. PFN_NUMBER PagesNeeded;
  1988. PEPROCESS CurrentProcess;
  1989. PVOID UsedPageTableHandle;
  1990. KIRQL OldIrql;
  1991. PMMPFN Pfn1;
  1992. PMMPTE PointerPpe;
  1993. #if (_MI_PAGING_LEVELS >= 4)
  1994. PMMPTE PointerPxe;
  1995. #endif
  1996. CurrentProcess = PsGetCurrentProcess();
  1997. PointerPpe = MiGetPpeAddress (StartingAddress);
  1998. PointerPde = MiGetPdeAddress (StartingAddress);
  1999. PointerPte = MiGetPteAddress (StartingAddress);
  2000. LastPpe = MiGetPpeAddress (EndingAddress);
  2001. LastPde = MiGetPdeAddress (EndingAddress);
  2002. LastPte = MiGetPteAddress (EndingAddress);
  2003. UsedPageTableHandle = MI_GET_USED_PTES_HANDLE (StartingAddress);
  2004. //
  2005. // Each PTE is already zeroed - just delete the containing pages.
  2006. //
  2007. // Restore resident available pages for all of the page directory and table
  2008. // pages as they can now be paged again.
  2009. //
  2010. if (LastPte != PointerPte) {
  2011. PagesNeeded = MI_COMPUTE_PAGES_SPANNED (PointerPte,
  2012. LastPte - PointerPte);
  2013. #if (_MI_PAGING_LEVELS >= 3)
  2014. if (LastPde != PointerPde) {
  2015. PagesNeeded += MI_COMPUTE_PAGES_SPANNED (PointerPde,
  2016. LastPde - PointerPde);
  2017. #if (_MI_PAGING_LEVELS >= 4)
  2018. if (LastPpe != PointerPpe) {
  2019. PagesNeeded += MI_COMPUTE_PAGES_SPANNED (PointerPpe,
  2020. LastPpe - PointerPpe);
  2021. }
  2022. #endif
  2023. }
  2024. #endif
  2025. }
  2026. else {
  2027. PagesNeeded = 1;
  2028. #if (_MI_PAGING_LEVELS >= 3)
  2029. PagesNeeded += 1;
  2030. #endif
  2031. #if (_MI_PAGING_LEVELS >= 4)
  2032. PagesNeeded += 1;
  2033. #endif
  2034. }
  2035. MmLockPagableSectionByHandle (ExPageLockHandle);
  2036. LOCK_PFN (OldIrql);
  2037. MmResidentAvailablePages += PagesNeeded;
  2038. MM_BUMP_COUNTER(59, PagesNeeded);
  2039. while (PointerPte <= LastPte) {
  2040. ASSERT (PointerPte->u.Long == 0);
  2041. PointerPte += 1;
  2042. MI_DECREMENT_USED_PTES_BY_HANDLE (UsedPageTableHandle);
  2043. if ((MiIsPteOnPdeBoundary(PointerPte)) || (PointerPte > LastPte)) {
  2044. //
  2045. // The virtual address is on a page directory boundary or it is
  2046. // the last address in the entire range.
  2047. //
  2048. // If all the entries have been eliminated from the previous
  2049. // page table page, delete the page table page itself.
  2050. //
  2051. PointerPde = MiGetPteAddress (PointerPte - 1);
  2052. ASSERT (PointerPde->u.Hard.Valid == 1);
  2053. //
  2054. // Down the sharecount on the finished page table page.
  2055. //
  2056. PteContents = *PointerPde;
  2057. Pfn1 = MI_PFN_ELEMENT (PteContents.u.Hard.PageFrameNumber);
  2058. ASSERT (Pfn1->u2.ShareCount > 1);
  2059. Pfn1->u2.ShareCount -= 1;
  2060. //
  2061. // If all the entries have been eliminated from the previous
  2062. // page table page, delete the page table page itself.
  2063. //
  2064. if (MI_GET_USED_PTES_FROM_HANDLE (UsedPageTableHandle) == 0) {
  2065. ASSERT (PointerPde->u.Long != 0);
  2066. #if (_MI_PAGING_LEVELS >= 3)
  2067. UsedPageTableHandle = MI_GET_USED_PTES_HANDLE (PointerPte - 1);
  2068. MI_DECREMENT_USED_PTES_BY_HANDLE (UsedPageTableHandle);
  2069. #endif
  2070. TempVa = MiGetVirtualAddressMappedByPte(PointerPde);
  2071. MiDeletePte (PointerPde,
  2072. TempVa,
  2073. FALSE,
  2074. CurrentProcess,
  2075. NULL,
  2076. NULL);
  2077. #if (_MI_PAGING_LEVELS >= 3)
  2078. if ((MiIsPteOnPpeBoundary(PointerPte)) || (PointerPte > LastPte)) {
  2079. PointerPpe = MiGetPteAddress (PointerPde);
  2080. ASSERT (PointerPpe->u.Hard.Valid == 1);
  2081. //
  2082. // If all the entries have been eliminated from the previous
  2083. // page directory page, delete the page directory page too.
  2084. //
  2085. if (MI_GET_USED_PTES_FROM_HANDLE (UsedPageTableHandle) == 0) {
  2086. ASSERT (PointerPpe->u.Long != 0);
  2087. #if (_MI_PAGING_LEVELS >= 4)
  2088. UsedPageTableHandle = MI_GET_USED_PTES_HANDLE (PointerPde - 1);
  2089. MI_DECREMENT_USED_PTES_BY_HANDLE (UsedPageTableHandle);
  2090. #endif
  2091. TempVa = MiGetVirtualAddressMappedByPte(PointerPpe);
  2092. MiDeletePte (PointerPpe,
  2093. TempVa,
  2094. FALSE,
  2095. CurrentProcess,
  2096. NULL,
  2097. NULL);
  2098. #if (_MI_PAGING_LEVELS >= 4)
  2099. PointerPxe = MiGetPdeAddress (PointerPde);
  2100. if (MI_GET_USED_PTES_FROM_HANDLE (UsedPageTableHandle) == 0) {
  2101. ASSERT (PointerPxe->u.Long != 0);
  2102. TempVa = MiGetVirtualAddressMappedByPte(PointerPxe);
  2103. MiDeletePte (PointerPxe,
  2104. TempVa,
  2105. FALSE,
  2106. CurrentProcess,
  2107. NULL,
  2108. NULL);
  2109. }
  2110. #endif
  2111. }
  2112. }
  2113. #endif
  2114. }
  2115. if (PointerPte > LastPte) {
  2116. break;
  2117. }
  2118. //
  2119. // Release the PFN lock. This prevents a single thread
  2120. // from forcing other high priority threads from being
  2121. // blocked while a large address range is deleted.
  2122. //
  2123. UNLOCK_PFN (OldIrql);
  2124. UsedPageTableHandle = MI_GET_USED_PTES_HANDLE ((PVOID)((PUCHAR)StartingAddress + PAGE_SIZE));
  2125. LOCK_PFN (OldIrql);
  2126. }
  2127. StartingAddress = (PVOID)((PUCHAR)StartingAddress + PAGE_SIZE);
  2128. }
  2129. UNLOCK_PFN (OldIrql);
  2130. MmUnlockPagableImageSection (ExPageLockHandle);
  2131. //
  2132. // All done, return.
  2133. //
  2134. return;
  2135. }
  2136. //
  2137. // Commented out, no longer used.
  2138. //
  2139. #if 0
  2140. LOGICAL
  2141. MiIsEntireRangeDecommitted (
  2142. IN PVOID StartingAddress,
  2143. IN PVOID EndingAddress,
  2144. IN PMMVAD Vad,
  2145. IN PEPROCESS Process
  2146. )
  2147. /*++
  2148. Routine Description:
  2149. This routine examines the range of pages from the starting address
  2150. up to and including the ending address and returns TRUE if every
  2151. page in the range is either not committed or decommitted, FALSE otherwise.
  2152. Arguments:
  2153. StartingAddress - Supplies the starting address of the range.
  2154. EndingAddress - Supplies the ending address of the range.
  2155. Vad - Supplies the virtual address descriptor which describes the range.
  2156. Process - Supplies the current process.
  2157. Return Value:
  2158. TRUE if the entire range is either decommitted or not committed.
  2159. FALSE if any page within the range is committed.
  2160. Environment:
  2161. Kernel mode, APCs disabled, WorkingSetMutex and AddressCreation mutexes
  2162. held.
  2163. --*/
  2164. {
  2165. PMMPTE PointerPte;
  2166. PMMPTE LastPte;
  2167. PMMPTE PointerPde;
  2168. ULONG Waited;
  2169. ULONG FirstTime;
  2170. PVOID Va;
  2171. FirstTime = TRUE;
  2172. PointerPde = MiGetPdeAddress (StartingAddress);
  2173. PointerPte = MiGetPteAddress (StartingAddress);
  2174. LastPte = MiGetPteAddress (EndingAddress);
  2175. //
  2176. // Set the Va to the starting address + 8, this solves problems
  2177. // associated with address 0 (NULL) being used as a valid virtual
  2178. // address and NULL in the VAD commitment field indicating no pages
  2179. // are committed.
  2180. //
  2181. Va = (PVOID)((PCHAR)StartingAddress + 8);
  2182. //
  2183. // A page table page exists, examine the individual PTEs to ensure
  2184. // none are in the committed state.
  2185. //
  2186. while (PointerPte <= LastPte) {
  2187. //
  2188. // Check to see if a page table page (PDE) exists if the PointerPte
  2189. // address is on a page boundary or this is the first time through
  2190. // the loop.
  2191. //
  2192. if (MiIsPteOnPdeBoundary (PointerPte) || (FirstTime)) {
  2193. //
  2194. // This is a PDE boundary, check to see if the entire
  2195. // PDE page exists.
  2196. //
  2197. FirstTime = FALSE;
  2198. PointerPde = MiGetPteAddress (PointerPte);
  2199. while (!MiDoesPdeExistAndMakeValid (PointerPde,
  2200. Process,
  2201. FALSE,
  2202. &Waited)) {
  2203. //
  2204. // No PDE exists for the starting address, check the VAD
  2205. // to see whether the pages are committed or not.
  2206. //
  2207. PointerPde += 1;
  2208. PointerPte = MiGetVirtualAddressMappedByPte (PointerPde);
  2209. if (PointerPte > LastPte) {
  2210. //
  2211. // No page table page exists, if explicit commitment
  2212. // via VAD indicates PTEs of zero should be committed,
  2213. // return an error.
  2214. //
  2215. if (EndingAddress <= Vad->CommittedAddress) {
  2216. //
  2217. // The entire range is committed, return an error.
  2218. //
  2219. return FALSE;
  2220. }
  2221. else {
  2222. //
  2223. // All pages are decommitted, return TRUE.
  2224. //
  2225. return TRUE;
  2226. }
  2227. }
  2228. Va = MiGetVirtualAddressMappedByPte (PointerPte);
  2229. //
  2230. // Make sure the range thus far is not committed.
  2231. //
  2232. if (Va <= Vad->CommittedAddress) {
  2233. //
  2234. // This range is committed, return an error.
  2235. //
  2236. return FALSE;
  2237. }
  2238. }
  2239. }
  2240. //
  2241. // The page table page exists, check each PTE for commitment.
  2242. //
  2243. if (PointerPte->u.Long == 0) {
  2244. //
  2245. // This PTE for the page is zero, check the VAD.
  2246. //
  2247. if (Va <= Vad->CommittedAddress) {
  2248. //
  2249. // The entire range is committed, return an error.
  2250. //
  2251. return FALSE;
  2252. }
  2253. }
  2254. else {
  2255. //
  2256. // Has this page been explicitly decommitted?
  2257. //
  2258. if (!MiIsPteDecommittedPage (PointerPte)) {
  2259. //
  2260. // This page is committed, return an error.
  2261. //
  2262. return FALSE;
  2263. }
  2264. }
  2265. PointerPte += 1;
  2266. Va = (PVOID)((PCHAR)(Va) + PAGE_SIZE);
  2267. }
  2268. return TRUE;
  2269. }
  2270. #endif //0
  2271. #if DBG
  2272. VOID
  2273. MmFooBar(VOID){}
  2274. #endif