| 1 | // Copyright 2026 The Memory Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package memory // import "modernc.org/memory" |
| 6 | |
| 7 | // canDecommit gates the decommit policy: pooled regions past the hot window |
| 8 | // hand their pages back to the OS. |
| 9 | const canDecommit = true |
| 10 | |
| 11 | // decommit returns the physical pages and the commit charge backing the empty |
| 12 | // region at p to the OS without releasing the address reservation - the |
| 13 | // windows analogue of the unix madvise(MADV_DONTNEED) path. Returning the |
| 14 | // commit charge matters more here than the working set: Windows does not |
| 15 | // overcommit, so a drained pool that stayed committed would hold |
| 16 | // pagefile-backed commit against the machine-global limit for as long as it |
| 17 | // is retained. |
| 18 | // |
| 19 | // The first OS page stays committed because it carries the page header. |
| 20 | // Unlike MADV_DONTNEED'ed pages, MEM_DECOMMIT'ed pages fault on touch instead |
| 21 | // of soft-faulting zeroes, so the reuse path recommits them via recommit |
| 22 | // before the region is handed out; the pool's cold watermark is what knows |
| 23 | // when that is needed. |
| 24 | // |
| 25 | // A failed VirtualFree leaves the pages committed, which is safe: the region |
| 26 | // is merely counted as decommitted, and recommit of already-committed pages |
| 27 | // succeeds and preserves them. |
| 28 | func decommit(p uintptr, size int) { |
| 29 | if size <= osPageSize { |
| 30 | return |
| 31 | } |
| 32 | |
| 33 | procVirtualFree.Call(p+uintptr(osPageSize), uintptr(size-osPageSize), _MEM_DECOMMIT) |
| 34 | } |
| 35 | |
| 36 | // recommit commits, zero-filled, the pages decommit returned, making a region |
| 37 | // popped from the pool's decommitted prefix usable again. It can fail when |
| 38 | // the machine is out of commit; the caller then leaves the pool untouched and |
| 39 | // reports the failure. |
| 40 | func recommit(p uintptr, size int) error { |
| 41 | if size <= osPageSize { |
| 42 | return nil |
| 43 | } |
| 44 | |
| 45 | addr, _, err := procVirtualAlloc.Call(p+uintptr(osPageSize), uintptr(size-osPageSize), _MEM_COMMIT, _PAGE_READWRITE) |
| 46 | if addr == 0 { |
| 47 | return err |
| 48 | } |
| 49 | |
| 50 | return nil |
| 51 | } |